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

Running Python as a script

In Java, you first compile your source code into intermediate bytecode (i.e. your *.class files). You then run the Java Virtual Machine (JVM) to interpret the bytecode.

Similarly, Python compiles your script into intermediate bytecode, and interprets the bytecode.

Unlike Java, you do NOT have to manually compile your code and then run the bytecode interpreter separately.

Instead, you simply run your Python script directly with the Python interpreter. In the background, the interpreter will automatically compile your script into bytecode. 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