这个猜数字游戏代码有什么问题?

时间:2014-09-22 16:28:00

标签: python loops if-statement random while-loop

#Guess my number

import random

print ("Welcome to the guess my number game")
print ("***********************************")
print ("You will choose a random number between 1-100")
print ("and the computer must guess what it is.")
print ()

number = int(input("Please choose a number between 1-100: "))
guesses = 0
guess = 0

while guess != number:
    guess = ("My guess is: ",random.randint(1,100))
    guesses=guesses+1

    if guess > number:
        print("Lower...")
        continue

    elif guess < number:
        print ("Higher...")

    else:
        print ("Well done you have guessed my number and it took you")          print ("guesses,"guesses!")

基本上你选择一个数字,计算机必须继续猜测,直到它正确,但我似乎无法让它工作。

1 个答案:

答案 0 :(得分:0)

你应该学习基本的调试技巧。调试此程序的最简单方法是添加print()语句以查看变量中的值。

您的基本问题是您将guess设置为具有两个值的元组:字符串"My guess is: "和1到100之间的随机数。您可能打算将guess设置为仅数字。

你可能想要这样的东西:

guess = random.randint(1,100)
print("My guess is: {}".format(guess))

这会让你更近一步。然后,您需要弄清楚如何更改程序,以便缩小猜测范围。如果你遇到麻烦,也许你应该找个人来辅导你。