BYU logo Computer Science

To start this guide, download this zip file.

Input loops

When writing interactive programs, you often will want to loop while receiving input. The basic structure of an input is:

  • while some condition is True
    • read input
    • check the input and either
      • do something with the input
      • break or return from the loop

This is an event stream pattern!

The examples below will illustrate how to do this.

Road Trip

We are going to write a small program that checks helps you on a road trip:

  • loop forever
    • ask the driver “Are we there yet?”
    • if the answer is yes, break out of the loop

The code in road_trip.py shows a program that does this:

def is_yes(response):
    return response == "yes" or response == "Yes"


def road_trip():
    while True:
        response = input("Are we there yet? ")

        if is_yes(response):
            print("Hurray!")
            break


if __name__ == '__main__':
    road_trip()

The most important thing to notice here is that the road_trip() function uses while True to loop. This will loop literally forever unless you include some way of breaking out of the loop when a condition is met. In this case, we use break to leave the loop whenever the user types yes or Yes as input. The keyword break does exactly what it sounds like — it leaves the while loop it is inside of and goes to the next line of code that is outside of the loop. In this example, there is no other code in the road_trip() function, so once the code uses break, it leaves the function and then ends the program.

Notice also that the is_yes() function checks a response string to see if it is ‘yes’ or ‘Yes’, so we can handle different ways a person types a response. The correct way to write this code is:

    return response == "yes" or response == "Yes"

Do NOT write:

    return response == 'yes' or 'Yes'

This will ALWAYS return true. Imagine a person types ‘no’. Then Python will check response == 'yes', and this is False. However it then checks Yes, which by itself evaluates to True, and the function will return True. This is not what you want.

Run the program and you will see something like this:

Are we there yet? no
Are we there yet? no
Are we there yet? nyet
Are we there yet? nope
Are we there yet? sorry
Are we there yet? sigh
Are we there yet? yes
Hurray!

Bigger

Let’s write a program to check whether one number is bigger than another. The idea is to do this:

  • have the person enter number1
  • have the person enter number2
  • tell the person which number is bigger

Remember, input() always returns a string! If a person enters '5' and '10', then you don’t want to compare the string ‘5’ to the string ‘10’! You will be checking which string comes first alphabetically, which is not what you want.

So whenever you use input() to enter numbers, you need to convert the string that a person enters into an integer. You do this with int():

response = input('Enter a number: ')
number = int(response)

When you use input() to ask for a number, be sure to use int() to convert the string a person types into a number

The code in bigger.py contains a program that checks two numbers:

def get_number():
    response = input("Enter a number: ")
    return int(response)


def main():
    number1 = get_number()
    number2 = get_number()

    if number1 > number2:
        print(f"{number1} is bigger than {number2}")

    elif number1 < number2:
        print(f"{number1} is smaller than {number2}")

    else:
        print(f"You entered {number1} twice.")


if __name__ == '__main__':
    main()

If you run this program, you will see something like this:

Enter a number: 5
Enter a number: 10
5 is smaller than 10

Guessing game

Let’s put these two concepts together. Write a program that asks a person to guess a secret number:

  • loop forever
    • get a guess
    • if the guess is too high, tell them to go lower
    • if the guess is too low, tell them to go higher
    • if the guess is correct, tell them they won and break

This combines both an input loop and converting strings to integers with int(). Work with a friend to see if you can solve this problem.

work with a friend to solve this problem

The code in guessing_game.py contains a solution:

def play(secret_number):
    while True:
        response = int(input('Guess a number: '))

        if response > secret_number:
            print('Lower!')

        elif response < secret_number:
            print('Higher!')

        else:
            print('You got it!')
            return


if __name__ == '__main__':
    play(37)

In this program we use return to break out of the while loop. This works just as well as break. The only difference is that break would continue to execute code in the play() function if there was more code after the while loop.

Notice that we “hard code” the answer to 37. Later we will show you how to choose a random number instead. If you run this program, you should see something like this:

Guess a number: 50
Lower!
Guess a number: 20
Higher!
Guess a number: 30
Higher!
Guess a number: 35
Higher!
Guess a number: 37
You got it!