[英]Basic while loops in Python
我一直在尝试用Python 3.3.4制作一个简单的游戏,在游戏开始时,我希望用户在1到3之间选择一个难度,并且如果他们输入除1、2或3以外的其他字符,则会收到信息“无效输入”。
我已经在下面编写了代码,但是即使用户输入了1、2或3,我也无法使其正常运行,但会出现错误“无效输入”,我尝试以各种组合来解决它无济于事。 我了解这是相当基本的,因为我刚接触Python时可能忽略了一些简单的事情。 提前致谢。
while True:
while True:
cmd = input('Please select a diffuculty from 1 to 3, with three being the hardest: ')
if cmd in (1, 2, 3):
break
print ('Invalid input.')
if cmd == 1:
dopt = 3
continue
elif cmd == 2:
dopt = 4
continue
elif cmd == 2:
dopt = 5
continue
问题出在您的类型上。 input
返回一个字符串,因此cmd
是一个字符串。 然后,您询问cmd
是否位于(1,2,3)
int,int (1,2,3)
中。 让我与您一起探讨您的选择。
你可以改变
cmd = input("...")
至
cmd = int(input("..."))
这样,cmd是一个int,正如稍后所预期的那样。 问题是有人输入了无法解析为int的内容,例如"foo"
,您的程序将立即退出并出现ValueError。
尝试这样的事情:
...
while True:
cmd = input('Please select a diffuculty from 1 to 3, with three being the hardest: ')
if cmd in ('1', '2', '3'):
break
print ('Invalid input.')
cmd = int(cmd)
if cmd == 1:
dopt = 3
continue
...
在这里,您有一个字符串元组,而不是cmd验证中的整数元组。 之后,将cmd解析为一个int,然后程序按预期继续。
另外,您的if-else链可以替换为dopt = cmd+2
祝你好运!
从文档中:
input([prompt])
等效于eval(raw_input(prompt))。
raw_input([prompt])
:
如果存在提示参数,则将其写入到标准输出中,而无需尾随换行符。 然后,该函数从输入中读取一行,将其转换为字符串 (将尾随换行符分隔),然后将其返回。
我修改了您的代码:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
while True:
cmd = int(input('Please select a diffuculty from 1 to 3, with three being the hardest: '))
print("cmd:{}, type:{}".format(cmd, type(cmd)))
if cmd not in (1, 2, 3):
print ('Invalid input.')
continue
if cmd == 1:
dopt = 3
break
elif cmd == 2:
dopt = 4
break
elif cmd == 3:
dopt = 5
break
print ("cmd:{}; dopt:{}".format(cmd, dopt))
您可以使用type
来知道输入的类型。
您的代码有一个问题。
input()
返回一个字符串 ,而不是整数。 因为您的输入是一个字符串 ,所以检查字符串是否为整数元组将不起作用:
>>> tup = (1, 2, 3)
>>> '1' in tup
False
>>> '3' in tup
False
因此,可以将int()
为input()
,以便它接受整数,并且仅将整数作为输入:
>>> x = int(input())
4
>>> type(x)
<class 'int'>
>>> x = int(input())
'hello'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: "'hello'"
>>>
因此,您可以然后检查输入是否在您的元组中:
>>> tup = (1, 2, 3)
>>> x = int(input())
2
>>> x in tup
True
>>> x = int(input())
7
>>> x in tup
False
>>>
这是您编辑的代码:
while True:
while True:
cmd = int(input('Please select a diffuculty from 1 to 3, with three being the hardest: '))
if cmd in (1, 2, 3):
break
print ('Invalid input.')
if cmd == 1:
dopt = 3
continue
elif cmd == 2:
dopt = 4
continue
elif cmd == 2:
dopt = 5
continue
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.