计算机总是说我错了 - 随机问题



我正试图用一个简单的积分系统制作一个随机的"猜数字"游戏。问题是我一遍又一遍地检查代码,我不知道问题出在哪里。问题是计算机总是说我错了,我从来没有赢过,我甚至尝试过使用random.randint(1,2),但什么都没有。我通常运气不好,但我很确定是代码不起作用。

import random
print("Guess the number from 1 to 10")
while True:
number = random.randint(1, 2)
number = int(number)
guess = input("Enter number: ")
points = 0
if number == guess:
print("You guessed right!")
points += 1
else:
print("Sorry, wrong guess")
print("You have: " + str(points) + " points.")
print("Wanna try again? ")
tryagain = input("Y or N: ")
if tryagain == "Y" or "y":
continue
else:
break

正如其他人所提到的,您忘记将猜测更改为int。你还做到了每一轮都将点数重置为零;points=0语句应该出现在循环之外。

以下是您的脚本的工作版本:

import random 
print("Guess the number from 1 to 10")
points = 0
while True:
number = random.randint(1, 2)   # no need for "int"
#     print(number) # uncomment to cheat 
guess = input("Enter number: ")
if int(guess) == number:
print("You guessed right!")
points += 1
else:
print("Sorry, wrong guess")
print("You have: " + str(points) + " points.")
print("Wanna try again? ")
tryagain = input("Y or N: ")
if tryagain.upper() == "N": # you only do something *different* in the N case
break

您还可以进一步缩短代码,因为您不需要在if语句之外使用用户输入。

import random

print("Guess the number from 1 to 10")
points = 0
while True:
number = random.randint(1, 2)   # no need for "int"
#     print(number) # uncomment to cheat 
if int(input("Enter number: ")) == number:
print("You guessed right!")
points += 1
else:
print("Sorry, wrong guess")
print("You have: %s points."%points)
print("Wanna try again? ") 
if input("Y or N: ").upper() == "N": # you only do something *different* in the N case
break

这是因为您的"猜测;变量仍然被识别为字符串,并且不会被识别为等于您的整数";数字";变量

将您的if number == guess:更改为if number == int(guess):

在你改变后,它应该会很好!

最新更新