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 C++ 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
25
26
27
28
29
#include <iostream>

using namespace std;

int main() {
    int secret_number, num_of_guesses, user_guess;

    secret_number = 42;

    num_of_guesses = 1;

    // Read in user's guess as an integer
    cout << "Please enter a number: ";
    cin >> user_guess;

    while ((user_guess != secret_number) && (num_of_guesses < 5)) {
        cout << "Incorrect. " << "Please enter a number: ";
        cin >> user_guess;
        num_of_guesses++;
    }

    if (user_guess == secret_number) {
        cout << "Correct" << endl;
    } else {
        cout << "Incorrect. Game over." << endl;
    }

    return 0;
}

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.