Chapter 3: Running Python

Running Python as a script

face Josiah Wang

Of course, it might be quite tiresome to type your code into the interactive Python prompt, especially when your code gets more complex, and when you need to save your code.

Fortunately, you can also execute Python scripts (that you have pre-typed into a file) using the Python interpreter.

Now, try copy and pasting the guessing game below into your favourite plain text editor (Notepad, Atom, gedit, vim, emacs, etc.). Save it somewhere on your hard drive as guessing_game.py.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
secret_number = 42

num_of_guesses = 1

# Read in user's guess as an integer
user_guess = int(input("Please enter a number: "))

while user_guess != secret_number and num_of_guesses < 5:
    print("Incorrect. ")
    user_guess = int(input("Please enter a number: "))
    num_of_guesses = num_of_guesses + 1

if user_guess == secret_number:
    print("Correct")
else:
    print("Incorrect. Game over.")

Then launch a command line console. Navigate to the folder where you saved guessing_game.py earlier (cd your_folder_name).

Type python guessing_game.py (or python3 guessing_game.py, just make sure you are running the correct version of Python).

user@MACHINE:~/$ python guessing_game.py
Please enter a number: 34
Incorrect.
Please enter a number: 88
Incorrect.
Please enter a number: 1
Incorrect.
Please enter a number: 42
Correct

And that is how you run a Python script 😊