[英]How do I check two conditions at the same time in a for loop in python?
[英]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.