Computer Science

# Scripts

A Python program is also called a script. You can run a Python script by putting it into a file, for example simple_script.py, and then running it in PyCharm (Right-click -> run) or from the command line:

python simple_script.py

This is a very simple script. You can put it into a file called simple_script.py and then run it.

print('This is a self-referential statement.')
print('Self-referential statements can get into all kinds of logical conundrum.')
print('This statement is false.')
skepticism = '🤨'
print(skepticism)

When you run it, the script prints four lines:

This is a self-referential statement.
Self-referential statements can get into all kinds of logical conundrum.
This statement is false.
🤨

This is the key idea:

When you run a script, every line is executed in order.

## Functions are not executed until they are called

When you define a function in a Python script, it is not executed until you call it. Consider the following code:

def say_it_with_a_preamble(message):
print('I am pleased to announce that:')
print(message)

print('Bit was fun.')
say_it_with_a_preamble('we are moving on from Bit')

As Python runs this file, it finds a function definition for say_it_with_a_preamble(). It does not run this function at this time. Instead, it files it away for later, remembering its name and the block of code it should execute.

Next, Python finds the line that begins with print() and it executes this line.

Then, Python finds a line that tells it to execute say_it_with_a_preamble('we are moving on from Bit'). Now it needs to go and execute this function, which it saw defined earlier.

It runs say_it_with_a_preamble() and sets message="we are moving on from Bit". This function runs several print() statements and then exits.

Now the script is done.

You have to define the function before you call it. If you try to execute a function that is not yet defined, even if it is defined later in the script, you will get an error.