Caleb Swartz
Caleb Swartz

Reputation: 41

While Loop Number Game in Python

I am attempting to make a very basic number game in Python. When I give the program input it just loops and keeps asking for input instead of displaying the given print statements and completing the code.

    import random
    win = False
    numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

    while not win:
    guess = input("Guess a number between 1 and 10:")
    num = random.choice(numbers)
    if num > int(guess):
    print("Too high! Try again.")
    if num < int(guess):
        print("Too low! Try again.")
    if num == int(guess):
     win = True
    print("You win!")

Upvotes: 0

Views: 155

Answers (2)

Buddy Bob
Buddy Bob

Reputation: 5889

First of all you can take an input like this. int(input()), that way you don't always have to convert your variable. Secondly, you have your <, > symbols mixed up. And your random.choice() should be outside your loop or it will keep choosing new numbers.

Your code should look like this.

import random
win = False
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
num = random.choice(numbers)
while not win:
    guess = int(input("Guess a number between 1 and 10:"))
    if num < guess:
        print("Too high! Try again.")
    if num > guess:
        print("Too low! Try again.")
    if num == guess:
        win = True
print("You win!")

Upvotes: 1

enzo
enzo

Reputation: 11496

Some remarks:

  1. You're creating a new num every time the loop is run, so the user will have no clue if the number is low or high than the expected number since it's being created on every attempt.

  2. You can use elifs and elses to avoid unnecessary checks.

  3. I don't know if it's a copy-paste error but you must also fix the identation of your code.

Fixed code:

import random
win = False
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# 1. Create the expected number outside the loop
num = random.choice(numbers)
while not win:
    # Just convert the input as integer if you won't use it as string
    guess = int(input("Guess a number between 1 and 10:"))
    
    # 2. Use elifs and elses
    if num > guess:
        print("Too high! Try again.")
    elif num < guess:
        print("Too low! Try again.")
    else:
        win = True
        print("You win!")

Upvotes: 0

Related Questions