首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >while循环正确嵌套

while循环正确嵌套
EN

Stack Overflow用户
提问于 2018-08-10 20:45:36
回答 5查看 89关注 0票数 0

我正在寻求关于正确使用以下3个while循环的帮助:

代码语言:javascript
复制
while choice is None:  ...
while not isinstance (choice, int):  ...
while int(choice) not in range(0,1):  ...

可能是这样的:

代码语言:javascript
复制
while choice is None and not isinstance (choice, int) and int(choice) not in range(0,1):
    print("Invalid option!")
    choice = input("Choose key: ")

我该如何正确地嵌套它呢?

代码语言:javascript
复制
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)
EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2018-08-10 20:53:49

您可以通过将所有内容移动到一个循环中来很好地压缩这些内容:

代码语言:javascript
复制
while True:
    choice = input("Choose key: ")
    if choice in ("0", "1"):
        choice = int(choice)
        break
票数 5
EN

Stack Overflow用户

发布于 2018-08-10 20:52:34

input返回一个str对象period。它永远不会返回None,它永远不会返回int。只需(尝试)将choice转换为int,然后检查结果值,只有在输入0或1时才会中断。

代码语言:javascript
复制
while True:
    choice = input("Choose key: ")
    try:
        choice = int(choice)
    except ValueError:
        continue
    if choice in (0, 1):
        break
票数 3
EN

Stack Overflow用户

发布于 2018-08-10 20:51:50

如果你需要一个整数输入...

代码语言:javascript
复制
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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51786872

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档