I've just written a quick script guessing a random number. Though the last line of the script 'Congrats you won etc' isn't running. Also in some interpreters it is giving an error 'Failed to run script'.
import random
attempts = 0
secret_number = random.randint(1,100)
isCorrect = False
guess = int(input("Take a guess: "))
while secret_number != guess:
if guess < secret_number:
print("Higher...")
guess = int(input("Take a guess: "))
attempts+= 1
elif guess > secret_number:
print("Lower...")
guess = int(input("Take a guess: "))
attempts+= 1
else:
print("\nYou guessed it! The number was " ,secret_number)
I made a few revisions to your script. Note that its functioning is regulated by the execution flow and no special control statements (eg continue
, break
) or explicit intervention were necessary to make it logically consistent:
import random
secret_number = random.randint(1, 100)
guess = None
attempts = 0
while secret_number != guess:
guess = int(input("Take a guess: "))
attempts += 1
if secret_number == guess:
print("\nYou guessed it! The number was ", secret_number)
elif guess < secret_number:
print("Higher...")
elif guess > secret_number:
print("Lower...")
I changed:
isCorrect
variable. I deleted it because it was unused; guess
variable is initialized. It is None
before the while statement; I recommend to get an intuitive sense of why the script is working.
I tried running it and received the following output:
None@vacuum:~$ python3.6 ./test.py
Take a guess: 70
Higher...
Take a guess: 80
Higher...
Take a guess: 90
Higher...
Take a guess: 95
Lower...
Take a guess: 94
Lower...
Take a guess: 93
Lower...
Take a guess: 92
Lower...
Take a guess: 91
You guessed it! The number was 91
You should print the line out of the while loop, as your loop will break when secret_number == guess.
while ...:
if:
...
elif:
...
print "You guessed it! The number was {0}".format(secret_number)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.