python - 为什么我的嵌套while循环不起作用python?
问题描述
所以我正在制作一个摇滚纸游戏,我已经添加了我的源代码。到目前为止,我已经让玩家输入他们的选择。我尝试添加检查以确保他们输入的选项是三个选项之一。我的程序纠正了一次,然后它停止做任何事情
这是我的源代码。
print('''Please pick one of the following:
Rock
Paper
Scissors''')
p1 = None
p2 = None
while True:
gameDict = {"rock":1,"paper":2,"scissors":3}
in1 = input("Player 1: ").lower()
in2 = input("Player 2: ").lower()
p1 = gameDict.get(in1)
p2 =gameDict.get(in2)
while gameDict.get(p1)==None or gameDict.get(p2)==None:
if(p1==None):
p1=input("Player 1, please enter one of the choices listed above: ")
elif p2== None:
p2=input("Player 2, please enter one of the choices listed above: ")
print('Done!!')
print(p1,p2)
解决方案
并不是它什么都没做。事实上它做了很多,它处于一个无限循环中。输入错误时会发生什么:
p1 = None
,p2 = None
.- 在第一次迭代中,由于
p1 == None
计算结果为true
,它执行if
语句,分配一个新值p1
,现在它不再存在None
了。 - 在第二次迭代中,
p2 == None
计算结果为true
,它执行if
语句,分配一个新值p2
,现在它不再存在None
了。 - 之后,两者
p1
和p2
都不是None
,因此没有任何if
语句被执行并且循环无限迭代。
我建议您执行以下操作:
print('''Please pick one of the following:
Rock
Paper
Scissors''')
p1 = None
p2 = None
while True:
gameDict = {"rock":1, "paper":2, "scissors":3}
in1 = input("Player 1: ").lower()
in2 = input("Player 2: ").lower()
p1 = gameDict.get(in1)
p2 = gameDict.get(in2)
while p1 ==None or p2 ==None:
if(p1 == None):
val = input("Player 1, please enter one of the choices listed above: ")
if(gameDict.get(val) != None):
p1 = val
if p2 == None:
val = input("Player 2, please enter one of the choices listed above: ")
if(gameDict.get(val) != None):
p2 = val
print('Done!!')
print(p1, p2)
我已经修复的东西:
- 为输入字符串值制作了一个专用变量,即
val
. - 更改
elif
为,if
因为任何一个玩家的输入都可以是有效的,但不是另一个,你会想要循环直到两者都有效。
推荐阅读
- javascript - 将 dataTable 输入字段宽度设置为自动
- android - 使用函数引用来注册和注销监听器是否安全?
- reactjs - 样式化组件 - 具有嵌套类的 css 变量
- debian - 如何在 Debian 软件包控制文件“Depends:”“Pre-Depends”子句中指定次要版本的范围
- go - 如何将字符串转换为复数?
- python - 我如何根据 12 个数组(12 个月)制作颜色图?
- github - 如何从 github API 获取网站链接?
- python - 如何确定使用 lmfit 进行曲线拟合的初始参数值
- mesibo - 在mesibo群聊中,我无法创建群,有人知道如何创建吗?
- vue.js - 如何在 vuejs 中创建记忆搜索功能