Проблема запуска очень простой программы на Python - PullRequest
2 голосов
/ 06 октября 2009

Почему моя программа выдает здесь ошибку?

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) + "!")

Ошибка в последней строке. Что я могу сделать?

Edit:

Кроме того, почему я не могу использовать Tries ++ здесь, в Python? Разве нет автоинкрементного кода?

Редактировать 2: Ошибка:

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

Ответы [ 2 ]

3 голосов
/ 06 октября 2009

В последней строке замените string на str - это должно позаботиться об ошибке, на которую жалуется питон, по крайней мере.

2 голосов
/ 06 октября 2009

это str, а не string. но ваша бесконечная петля - большая проблема. автоинкремент записывается так:

Tries += 1

Общий комментарий: вы могли бы немного улучшить свой код:

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)
...