while循环正确的嵌套

时间:2018-08-10 12:45:36

标签: python python-3.x

我正在寻求以下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)

5 个答案:

答案 0 :(得分:5)

您可以通过将所有内容移入一个循环来很好地压缩它:

while True:
    choice = input("Choose key: ")
    if choice in ("0", "1"):
        choice = int(choice)
        break

答案 1 :(得分:3)

input返回一个str对象,即句点。它永远不会返回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

答案 2 :(得分:1)

如果您需要整数输入...

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 integer

答案 3 :(得分:0)

如果我了解得很清楚,这与嵌套无关,而与订购有关,对吗?怎么样:

In [10]: choice = None

In [11]: while (
...:     not choice or
...:     not choice.isdigit() or
...:     int(choice) not in range(0,2)
...: ):
...:     print("Invalid option!")
...:     choice = input("Choose key: ")

答案 4 :(得分:0)

choice = None
while choice not in range(0,1):
    choice = int(input("Choose key: "))

我不知道那是你想做的