2

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
1
  • Most importantly, your casting of a variable to string is unnecessary in Python. Commented Dec 20, 2012 at 16:55

2 Answers 2

3

In your last line, replace string with str -- that should take care of the error python is complaining about, at least.

Sign up to request clarification or add additional context in comments.

Comments

2

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)

3 Comments

I fixed it with your code, and my computer shot itself in the motherboard. Thanks a lot SO.
Did you fix the infinite loop before the shooting?
I meant that infinite loop made my computer kill itself xD

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.