繁体   English   中英

如何在Python 3的同一循环或函数中检查用户输入的多个条件?

[英]How to check user input for multiple conditions within same loop or function in Python 3?

我正在尝试接受user-input但是我需要输入一个整数,并且介于1到9之间。我尝试在代码中的几个位置放置“ inrange(1,10)”,但没有工作。 我需要程序不断询问用户正确的输入,直到他们提供正确的输入为止。 到目前为止,我只能使用下面的代码来确保它们的输入是整数。 我将使用int(input("..."))而不是input("...")

while True:
    try:
        ui1 = int(input("Player 1, Your move. Select your move. "))
        break
    except ValueError:
        print("You have to choose a number between 1 and 9")
        continue

为什么不只检查isdigit()in range呢?

while True:
    ui1 = input("Player 1, Your move. Select your move. ")
    if ui1.isdigit() and int(ui1) in range(1,10):
        break
    print("You have to choose a number between 1 and 9")

# Continue code out of the loop

在中断之前添加检查,然后将错误消息移至循环末尾。

while True:
    try:
        ui1 = int(input("Player 1, Your move. Select your move. "))
        if 1 <= ui1 <= 9:
            break
    except ValueError:
        pass
    print("You have to choose a number between 1 and 9")
# beJeb
# Stack overflow -
# https://stackoverflow.com/questions/51202856/how-to-check-user-input-for-multiple-conditions-within-same-loop-or-function-in

# Our main function, only used to grab input and call our other function(s).
def main():

    while True:   
        try:
            userVar = int(input("Player 1, Your move. Select your move: "))
            break
        except ValueError:
            print("Incorrect input type, please enter an integer: ")

    # We can assume that our input is an int if we get here, so check for range
    checkRange = isGoodRange(userVar)

    # Checking to make sure our input is in range and reprompt, or print.
    if(checkRange != False):
        print("Player 1 chooses to make the move: %d" %(userVar))
    else:
        print("Your input is not in the range of 1-9, please enter a correct var.")
        main()

# This function will check if our number is within our range.
def isGoodRange(whatNum):
    if(whatNum < 10) & (whatNum > 0):
        return True

    else: return False

# Protecting the main function
if __name__ == "__main__":
    main()

注意:我测试了几个输入,因此我认为这应该足以帮助您理解该过程,如果不能,请发表评论,消息等。此外,如果此答案对您有所帮助,请选择它作为回答来帮助其他人。

假设数字是您从用户那里得到的输入。

while(1): #To ensure that input is continuous
    number = int(input())
    if number>=1 and number<=10 and number.isdigit():
        break #if the input is valid, you can proceed with the number
    else:
        print("Enter a valid Number")

该号码可用于进一步的操作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM