python - 你知道这个简单的脚本有什么问题吗
问题描述
我要做的就是制作一个随机数,如果用户正确,它会输出“你知道了!” 但无论什么总是显示好像我弄错了,即使我回答了 n
import random
n = random.randint(1,2)
guess = input("1 or 2?")
if guess == n:
print("You won!")
解决方案
在 python 中,"10" == 10
是False
. 您必须比较相同的类型,例如10 == 10
或"10" == "10"
。
input()
返回 a str
,当random.randint()
返回 an时int
,guess == n
总是如此False
。
这是解决您的问题的简单方法:
guess = int(input("1 or 2?"))
或者
n = str(random.randint(1, 2))
或者
n = random.choice("12")
推荐阅读
- amazon-web-services - 预配置 EC2 上的 AWS 系统设计
- laravel - 如何在 Laravel 中使用一个用户模型创建单独的登录视图和重定向
- c - 使用字符串和固定大小的动态内存分配
- symfony - 不使用自定义子资源路径时关系实体字段上的安全投票者
- c++ - 如何在 MFC 中从弹出所有者绘制 ListBox 中获取 selchange msg
- markdown - Doxygen 中的 Markdown 文件,两个谜题
- ios - MapKit Tile Overlay 需要很长时间才能加载
- javascript - 如果数组中已存在特定项,则删除并将对象项添加到数组中并更改对象键
- memory - 在 128 个内核上进行大型模拟的内存出现硬件错误
- database - 如何定义没有主键的持久表?