This is an archived version of the course. Please see the latest version of the course.

Running Python as a script

Compared to C++, Python is an interpreted language. So rather than you having to manually compile your code to machine code and then run the resulting executable, you can simply run your Python script directly with the Python interpreter. In the background, the interpreter will automatically compile your script into bytecode (an assembly language-like instruction, but to be interpreted and executed by a virtual machine or an interpreter). Assuming no syntax errors, the interpreter will then execute your script. The compilation all happens seamlessly in the background - you will not even notice it!

Now, try copy and pasting my guessing game below and save it 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 run python3 guessing_game.py from the command line. Depending on your machine’s setup, you may also be able to run python guessing_game.py instead. Just make sure you are running the correct version of Python!

$ python3 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