![](/img/trans.png)
[英]Boolean condition is reading True, but the while loop still isn't breaking
[英]While loop isn't returning its condition
attempts=0
number=int(input("Enter a number from a range of 0 to a 100: "))
while number<0 and number>100:
attempts=attempts+1
number=int(input("Number is invalid. Please enter a number from a range of 0 to a 100: "))
attempts=attempts+1
print("Number of attempts for inputting a valid number: ", attempts)
我正在编写一个程序,其中输入的数字在 0 到 100 的范围内进行验证。如果它无效,则该数字将被拒绝,并会显示提示以重新输入数字。 然后我需要 output 尝试输入有效数字的次数。
至此,当输入大于 0 小于 100 的 integer 时,程序运行正常。 如果输入 integer,假设输入 -50,则应显示提示,然后需要重新输入数字 - 但我的 while 循环没有返回其条件,它会显示 output:
Enter a number from a range of 0 to a 100: -50
Number of attempts for inputting a valid number: 1
我认为在while
循环中,条件应该是or
不是and
。
attempts=0
number=int(input("Enter a number from a range of 0 to a 100: "))
while number<0 or number>100:
attempts=attempts+1
number=int(input("Number is invalid. Please enter a number from a range of 0 to a 100: "))
attempts=attempts+1
print("Number of attempts for inputting a valid number: ", attempts)
您应该使用“或”来代替“和”:
attempts=0
number=int(input("Enter a number from a range of 0 to a 100: "))
while number<0 or number>100:
attempts=attempts+1
number=int(input("Number is invalid. Please enter a number from a range of 0 to a 100: "))
attempts=attempts+1
print("Number of attempts for inputting a valid number: ", attempts)
这是我的建议:
attempts=0
number=int(input("Enter a number from a range of 0 to a 100: "))
while number not in range(0, 101):
attempts=attempts+1
number=int(input("Number is invalid. Please enter a number from a range of 0 to a 100: "))
attempts=attempts+1
print("Number of attempts for inputting a valid number: ", attempts)
结果:
Enter a number from a range of 0 to a 100: -1
Number is invalid. Please enter a number from a range of 0 to a 100: 101
Number is invalid. Please enter a number from a range of 0 to a 100: 100
Number of attempts for inputting a valid number: 3
Enter a number from a range of 0 to a 100: 0
Number of attempts for inputting a valid number: 1
错误在这里,而number<0 and number>100:
or意味着至少一个条件是正确的,但意味着所有条件都是正确的。 现在看看条件 没有数字可以同时满足您的条件,例如less than 0 and greater than 100 at a sametime.
因此您可以使用或操作,因此条件之一满足要求然后执行代码。
attempts=0
invalid_attempts=0
number=int(input("Enter a number from a range of 0 to a 100: "))
while number<0 or number>100:
number=int(input("Number is invalid. Please enter a number from a range of 0 to a 100: "))
invalid_attempts+=1
attempts=attempts+1
print("Number of attempts for inputting a valid number: ", attempts)
print("Number of attempts for inputting a Invalid number: ", invalid_attempts)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.