Python Beginner Concepts Tutorial

Build a Number Guessing Game with Keyboard Input

What is Input?

In programs, you can build interactivity with others to accept input from them and respond to certain condtions.

Python provides a built-in function called input that stops the program and waits for input. When the user pressed Return or Enter, the program is resumed and the input returns what the user typed as a string.

I can ask a user for their name. The \n is a newline character that causes a line break. The user prompt will display below the input prompt.

In [6]:
name = input("What's your name?\n")
In [7]:

Guessing Game Example

Let's build a game that allows a user up to 10 guesses in order to guess a number between 0 and 100. If the user guesses too low, we'll respond with "you guessed too low". If the user guesses too high, we'll respond with "you guessed too high". Lastly, if the user guesses correct, we'll respond "you guessed correct!" and end the game.

We'll assign any value between 0 and 100 to a correct_number variable to be our answer.

In [8]:
correct_number = 20

We'll assign a count_of_guesses variable to be 0 since we're at 0 guesses in the game to start.

In [9]:
count_of_guesses = 0

We utilize a while loop to evaluate the condition inside the loop as long as we've guessed less than 10 times.

We assign the variable user_guess to the result of our input that prompts the user to guess. We convert the guess from a string value to an integer; once an integer, we can logically compare it to our correct_number variable of 20.

We use conditional statements to evaluate how user_guess compares to correct_number based on the game specifications above.

The un-indented else statement at the end only executes if a user exhausts all 10 guesses. If not, our program will evaluate that else condition to False and not execute the print statement in its body.

In [10]:
while count_of_guesses <= 10:
    user_guess = int(input("Guess: \n"))
    count_of_guesses += 1

    if user_guess < correct_number:
        print("you guessed too low")
    elif user_guess > correct_number:
        print("you guessed too high")
        print("you guessed correct!")
    print("Sorry you lost the game")
you guessed too low
you guessed correct!