我尝试使用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
答案 0 :(得分:0)
为什么不只检查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
答案 1 :(得分:0)
在中断之前添加检查,然后将错误消息移至循环末尾。
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")
答案 2 :(得分:0)
# 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()
注意:我测试了几个输入,因此我认为这足以帮助您理解该过程,如果没有请发表评论,消息等。此外,如果此答案有帮助,请选择它作为回答帮助别人。
答案 3 :(得分:-1)
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")
该号码可用于进一步的操作。