Problem running a very simple Python program
-
19-09-2019 - |
Question
Why is my program giving me an error here?
import random
TheNumber = random.randrange(1,200,1)
NotGuessed = True
Tries = 0
GuessedNumber = int(input("Take a guess at the magic number!: "))
while NotGuessed == True:
if GuessedNumber < TheNumber:
print("Your guess is a bit too low.")
Tries = Tries + 1
GuessedNumber = int(input("Take another guess at the magic number!: "))
if GuessedNumber > TheNumber:
print("Your guess is a bit too high!")
Tries = Tries + 1
GuessedNumber = int(input("Take another guess at the magic number!: "))
if GuessedNumber == TheNumber:
print("You've guess the number, and it only took you " + string(Tries) + "!")
The error is on the last line. What can I do?
Edit:
Also, why can;t I use Tries++ here in Python? Isn't there an autoincrement code?
Edit 2: Error is:
Traceback (most recent call last):
File "C:/Users/Sergio/Desktop/GuessingGame.py", line 21, in <module>
print("You've guess the number, and it only took you " + string(Tries) + "!")
NameError: name 'string' is not defined
Solution
it's str
, not string
. but your infinite loop is a bigger problem. auto-increment is written like this:
Tries += 1
General comment: you could improve your code slightly:
the_number = random.randrange(1,200,1)
tries = 1
guessed_number = int(input("Take a guess at the magic number!: "))
while True:
if guessed_number < the_number:
print("Your guess is a bit too low.")
if guessed_number > the_number:
print("Your guess is a bit too high!")
if guessed_number == the_number:
break
else:
guessed_number = int(input("Take another guess at the magic number!: "))
tries += 1
print("You've guessed the number, and it only took you %d tries!" % tries)
OTHER TIPS
In your last line, replace string
with str
-- that should take care of the error python is complaining about, at least.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow