我正在寻求关于正确使用以下3个while循环的帮助:
while choice is None: ...
while not isinstance (choice, int): ...
while int(choice) not in range(0,1): ...可能是这样的:
while choice is None and not isinstance (choice, int) and int(choice) not in range(0,1):
print("Invalid option!")
choice = input("Choose key: ")我该如何正确地嵌套它呢?
choice = None
choice = input("Choose key: ")
while choice is None:
choice = input("Choose key: ")
while not isinstance (choice, int):
print("choice is an integer and I equal 0 or 1")
print("Also if I am None or not an int, I will loop until I meet I am")
while int(choice) not in range(0,1):
choice = input("Choose key: ")
choice = int(choice)发布于 2018-08-10 20:53:49
您可以通过将所有内容移动到一个循环中来很好地压缩这些内容:
while True:
choice = input("Choose key: ")
if choice in ("0", "1"):
choice = int(choice)
break发布于 2018-08-10 20:52:34
input返回一个str对象period。它永远不会返回None,它永远不会返回int。只需(尝试)将choice转换为int,然后检查结果值,只有在输入0或1时才会中断。
while True:
choice = input("Choose key: ")
try:
choice = int(choice)
except ValueError:
continue
if choice in (0, 1):
break发布于 2018-08-10 20:51:50
如果你需要一个整数输入...
while True:
try:
choice = int(input('Enter choice: '))
except ValueError:
print('Invalid choice')
else:
# add an if statement here to add another condition to test the int against before accepting input
break
# .... do whatever next with you integerhttps://stackoverflow.com/questions/51786872
复制相似问题