Chapter 1: Introduction

Example Python program

face Josiah Wang

It is probably easier to showcase the features of Python with an example program.

Let us say we want to write a simple guessing game. Users are asked to guess a pre-defined secret integer, and they can make at most 5 guesses.

Here is the pseudocode of one possible algorithm.

secret_number = 42

num_of_guesses = 1

user_guess = input("Please enter a number: ")

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

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

Here is an example Java implementation of the above algorithm.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class GuessingGame {
    public static void main(String[] args) {
        int secretNumber = 42;

        int numOfGuesses = 1;

        // Read in user's guess as an integer
        System.out.print("Please enter a number: ");
        int userGuess = Integer.parseInt(System.console().readLine());

        while (userGuess != secretNumber && numOfGuesses < 5) {
            System.out.println("Incorrect.");
            System.out.print("Please enter a number: ");
            userGuess = Integer.parseInt(System.console().readLine());
            numOfGuesses++;
        }

        if (userGuess == secretNumber) {
            System.out.println("Correct");
        } else {
            System.out.println("Incorrect. Game over.");
        }
    }
}

A Python implementation looks like this.

 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.")

Compare my Python implementation to the pseudocode earlier. Notice the similarities.

Ok, I lied when I said that it was pseudocode. 🤥

That was not pseudocode. That was actually a valid piece of Python code. 😈

The only things I changed were the extra comment (line 5) and converting the user input from a string into an integer (lines 6 and 10)!

This demonstrates the simplicity of the Python language.