首页 > 解决方案 > 你知道这个简单的脚本有什么问题吗

问题描述

我要做的就是制作一个随机数,如果用户正确,它会输出“你知道了!” 但无论什么总是显示好像我弄错了,即使我回答了 n

import random

n = random.randint(1,2)
guess = input("1 or 2?")
if guess == n:
  print("You won!")

标签: pythoninput

解决方案


在 python 中,"10" == 10False. 您必须比较相同的类型,例如10 == 10"10" == "10"

input()返回 a str,当random.randint()返回 an时intguess == n总是如此False

这是解决您的问题的简单方法:

guess = int(input("1 or 2?"))

或者

n = str(random.randint(1, 2))

或者

n = random.choice("12")

推荐阅读