【问题标题】:Computer always says I'm wrong - random.randint question计算机总是说我错了 - random.randint 问题
【发布时间】:2022-01-11 00:26:50
【问题描述】:

我正在尝试使用简单的积分系统制作随机猜数游戏。问题是我一遍又一遍地检查代码,我看不出问题出在哪里。问题是计算机总是说我错了,我从来没有赢过,我什至尝试过使用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

【问题讨论】:

  • 另外值得一提的是:number = int(number) 没有做任何事情,因为randint() 已经返回了int

标签: python random


【解决方案1】:

正如其他人所提到的,您忘记将猜测更改为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

【讨论】:

  • 谢谢!我还不能投票,因为我是 StackOverflow 的新手,但我也遇到了积分系统的问题,谢谢!
  • 没问题!如果这解决了您的问题,请点击我的答案左侧投票按钮下的复选标记来接受我的答案。
【解决方案2】:

这是因为您的“猜测”变量仍被识别为字符串,不会被识别为等于您的整数“数字”变量。

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

更改后它应该可以正常工作!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-27
    • 2023-02-11
    • 2011-11-14
    • 1970-01-01
    相关资源
    最近更新 更多