此代码接受用户输入并将其更改为整数,然后检查int是否在0到10之间。我还希望此代码针对浮点数和非数字字符串验证用户输入,并在返回时返回用户输入了错误的输入。例如:用户输入3.5或“十”并出现错误并再次循环。
pyramid = int(input("Please enter an integer between 0 and 10 to begin the sequence: "))
while pyramid < 0 or pyramid > 10:
print("That value is not in the correct range. Please try again.")
pyramid = int(input("Please enter an integer between 0 and 10 to begin the sequence: "))
答案 0 :(得分:0)
我建议尝试:
while 1
)pyramid % 1 != 0
),并在这种情况下打印相应的错误。while 1:
str_in = input("Please enter an integer between 0 and 10 to begin the sequence: ")
try:
pyramid = float(str_in)
if(pyramid % 1 != 0):
print("That value is a float not an integer. Please try again.")
continue
except:
pass
try:
pyramid = int(str_in)
if pyramid >= 0 and pyramid <= 10:
break
except:
pass
print("That value is a string not an integer. Please try again.")
print("Your value is {}".format(pyramid))