سؤال

لماذا يعطيني برنامجي خطأ هنا؟

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

الخطأ موجود في السطر الأخير. ماذا افعل؟

يحرر:

أيضا، لماذا يمكن أن تستخدم Tries ++ هنا في بيثون؟ أليس هناك رمز AutoIncrement؟

تحرير 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
هل كانت مفيدة؟

المحلول

إنه 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)

نصائح أخرى

في السطر الأخير الخاص بك، استبدال string مع str - يجب أن تهتم بالخطأ بيونثون يشكو، على الأقل.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top