Reputation: 3
I'm making a number guessing game and can someone tell me why it wont work properly?
import random
import time
time.time()
count=0
a = random.randint(0,100)
b = int(input("What number will you guess?"))
while b != a:
if b > a:
print("TOO BIG")
count = count + 1
elif b < a:
print("TOO SMALL")
count = count + 1
else b == a:
print("YOU WIN")
count = count + 1
time=time.time()
print("You took",count,"tries")
print("It took you",time,"second")
Upvotes: 0
Views: 66
Reputation: 5059
The reason this isn't working properly is because you're calling b = input
outside of your while loop. As it stands, the user will be asked a single time what their guess is, then the loop will just move infinitely, because b
is never being modified.
This loop will accomplish more what you want:
a = random.randint(0,100)
b = -1
while b != a:
b = int(input("What number will you guess?"))
A few notes, though:
Firstly, as Lee Daniel Crocker points out, the user will actually never see "YOU WIN", because you've structured your if-elif-else
statement incorrectly. else
by definition cannot have a condition - it exists purely in exclusion to all other conditionals in the same block. Additionally, your else statement is the opposite of your while
condition. When that else
becomes true, the loop exits. You'll need to handle printing "YOU WIN" somewhere else.
Second, you're not validating the user's input in any way - if they enter 'a', the program will crash, because you can't cast 'a' to an int. Either add an exception handler (for ValueError
) or using isdigit()
on the string, then casting it.
Third, you're not using time.time()
correctly - you need to subtract the time at which the user wins from the time at which they started, then represent that value, which is in seconds, in some meaningful way. As it stands you're telling each player that they took the number of seconds since the beginning of the UNIX epoch to complete the game.
Also, for usability reasons, you should probably provide the user some way to break out - a string like "QUIT" - because as it stands, the only way to restart/quit is to either close the application or KeyboardInterrupt
.
Upvotes: 3
Reputation: 302
You need to accept input in the loop. Move the line b = int(input("What number will you guess?")) within the loop.
Upvotes: 0