python - 我想返回 "duo"列表中顶级元素的数量

标签 python while-loop boolean

尝试做一个 boolean 测试循环,用户需要输入一个介于 10 和 1000 之间的数字,包括 10 和 1000,他们需要留在这个循环中,直到他们输入正确的数字,然后我将完成 else 语句.

我试过这个:

while (num_years < 10) and (num_years > 1000):  # boolean test , note ==  (= will give you an error!)
    print("Your input must be 10 and 1000")
    input("Enter number of years to simulate (currently " + str(num_years) + "): ")  
else:
    print()

还有这个:

while (num_years == range(10, 1000)):  # boolean test , note ==  (= will give you an error!)
    print("Your input must be 10 and 1000")
    input("Enter number of years to simulate (currently " + str(num_years) + "): ")  
else:
    print()

最佳答案

您可以尝试这样的操作,因为它还会检查用户输入的数字是否有效:

while True:
  number = input("Enter number of years to simulate (10-1000): ")
  try:
    years = int(number)
    if years >= 10 and years <= 1000: 
      break
    else:
      print("Your input must be between 10 and 1000 inclusive")
  except ValueError:
    print("That's not an int!")

print("Simulating %d years..." % years)

示例用法:

Enter number of years to simulate (10-1000):  asd
That's not an int!
Enter number of years to simulate (10-1000):  5
Your input must be between 10 and 1000 inclusive
Enter number of years to simulate (10-1000):  245
Simulating 245 years...

试一试 here!

关于python - 我想返回 "duo"列表中顶级元素的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42171241/

相关文章:

python - Pandas:当至少 N 个其他 bool 列为 True 时,新的 bool 列

java - java代码中的复选框

Java:锁定线程时,AtomicBoolean 和静态 boolean 变量有什么区别?

python - 如何在 Python 中使用自定义消息引发相同的异常?

python - pyodbc 中的字符串参数

python - 从嵌套子列表返回八元组模式

php - 从 While 循环填充 PHP 数组

python - 循环更新列表中的项目

java - 为什么 BlueJ 给我的代码一个 "unreachable statement"错误?

mysql - 为 mysql boolean 列中的先前值插入 NULL 值