Reputation: 117
I'm currently in the process of creating a game where it loops over and over again until you guess the right number.
The problem I'm having is getting the looping command right. I want to go for a while loop but I can get it to work, for certain parts of the script. If I use a "while true" loop, the if statement's print command is repeated over and over again but if I use any symbols (<, >, <=, >= etc.) I can't seem to get it to work on the elif statements. The code can be found below:
#GAME NUMBER 1: GUESS THE NUMBER
from random import randint
x = randint(1,100)
print(x) #This is just here for testing
name = str(input("Hello there, my name's Jarvis. What's your name?"))
print("Hello there ",name," good to see you!")
num = int(input("I'm thinking of a number between 1 and 100. can you guess which one it is?"))
attempt = 1
while
if num == x:
print("Good job! it took you ",attempt," tries!")
num + 1
elif num >= x:
print("Too high!")
attempt = attempt + 1
elif num <= x:
print("Too low!")
attempt = attempt + 1
else:
print("ERROR MESSAGE!")
Any and all help is appreciated.
Upvotes: 1
Views: 73
Reputation: 1035
Your while needs a colon, and a condition
while True:
and if you use a while True: you have to end the loop, you can use a variable for this.
while foo:
#Your Code
if num == x:
foo = False
Also, you could use string format instead of breaking your string. For example,
print("Good job! it took you %s tries!" % attempt)
or
print("Good job! it took you {0} tries!".format(attempt))
Upvotes: 1
Reputation: 158
You can use a boolean in the while
:
from random import randint
x = randint(1,100)
print(x) #This is just here for testing
name = str(input("Hello there, my name's Jarvis. What's your name?"))
print("Hello there ",name," good to see you!")
attempt = 1
not_found = True
while not_found:
num = int(input("I'm thinking of a number between 1 and 100. can you guess which one it is?"))
if num == x:
print("Good job! it took you ",attempt," tries!")
not_found = False
elif num > x: #Don't need the equals
print("Too high!")
elif num < x: #Don't need the equals
print("Too low!")
else:
print("ERROR MESSAGE!")
attempt = attempt + 1
Upvotes: 2
Reputation: 350756
You should put your question in the loop, because you want to repeat asking after each failure to get it right. Then also break
the loop when user found it:
attempt = 0
while True:
attempt = attempt + 1
num = int(input("I'm thinking of a number between 1 and 100. can you guess which one it is?"))
if num == x:
print("Good job! it took you ",attempt," tries!")
break
elif num >= x:
print("Too high!")
attempt = attempt + 1
elif num <= x:
print("Too low!")
else:
print("ERROR MESSAGE!")
Upvotes: 1