python while循环查找由分隔符分隔的2个整数的条目



我需要能够接受3,4的条目,基本上是用逗号分隔的2个整数。我需要一个while循环来不断要求输入,直到他们以2个数字的正确格式输入。这是我到目前为止的代码

def main():
try:
move = [int(s) for s in input("Select a cell (row,col) > ").split(",")]
except:
while move != []#stuck here
x = move[0]
y = move[1]

main()

您可以通过以下方式完成:

def main():
print('Enter the two points as comma seperated, e.g. 3,4')
while True:
try:
x, y = map(int, input().split(','))
except ValueError:
print('Enter the two points as comma seperated, e.g. 3,4')
continue
else:
break

main()

你几乎已经掌握了。你只需要整理一些细节。首先,如果输入失败,您需要一个空输入:

try:
move = [int(s) for s in input("Select a cell (row,col) > ").split(",")]
except:
move = []

现在,您需要重复输入,直到它有效为止。您首先需要while循环的语法:

while <condition>:
<body>

其中condition计算为布尔值,<body>是要重复的行。在这种情况下,您需要重复try...except

def main():
while move != []:
try:
move = [int(s) for s in input("Select a cell (row,col) > ").split(",")]
except:
move = []
x = move[0]
y = move[1]

当你遇到这样的语法问题时,我建议你阅读上的文档和教程https://python.org.他们解释了如何正确地编写while循环或尝试。。。除了更多。

如果输入不符合预期,可以使用嵌套函数和递归调用来完成此操作。

import re

def main():
def prompt():
digits = input("Select a cell (row,col) > ")
if not re.match(r'd+,d+', digits):
print('Error message')
prompt()
return digits.split(',')
move = prompt()
x = move[0]
y = move[1]

main()

最新更新