Skip to content
Advertisement

While loop spamming output instead of printing output once?

I’m making a regular guess the number game. I’m having problems when I enter the guess and the program spams lower or higher instead of just typing it once, since I’m using a while True loop.

Here I’m just opening the CSV file and picking a random number.

import random

numbers = open('numbers_1-200.csv').read().splitlines()
number = int(random.choice(numbers))

Here I’m importing numbers 1-50 and picking two random numbers which will be what’s added and subtracted from the original number. So the computer can write two numbers where the original number is between.

I know I could have just made the program pick two numbers from the first fifty lines in the same CSV that includes numbers from 1-200 but I choose to make another CSV which only had the numbers 1-50.

differences = open('numbers_1-50').read().splitlines()
difference = int(random.choice(differences))
difference2 = int(random.choice(differences))
clue = number + difference
clue2 = number - difference2

This is my welcome screen which also includes the main program on the last row¨

def welcome_screen():
    print('The number is between ' + str(clue) + ' and ' + str(clue2))
    print('Guess the number: ')
    guess_the_number()

This is my loop where you guess the number

def guess_the_number():
    guess = int(input())
    while True:
        if guess == number:
            print('Correct! The number was' + str(number))
            break
        elif guess > number:
            print('Lower')
        elif guess < number:
            print('Higher')

I’m getting outputs like these:

The number is between 45 and 97
Guess the number: 72
lower
lower
lower
lower
lower
lower
lower
lower

How can I get a output where it just says “lower” (or “higher”) one time and then I can guess again?

Advertisement

Answer

Just move the input function inside the while loop:

def guess_the_number():
    while True:
        guess = int(input())
        if guess == number:
            print('Correct! The number was' + str(number))
            break
        elif guess > number:
            print('Lower')
        elif guess < number:
            print('Higher')
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement