【问题标题】:Prompting the user for an int, not a string, until they do even if it's a negative number提示用户输入一个整数,而不是一个字符串,直到他们这样做,即使它是一个负数
【发布时间】:2018-01-07 01:16:14
【问题描述】:

我正在编写一个程序,它要求用户输入一个数字,我需要确保该数字是实际数字而不是字符串。这个数字可以是正数或负数。我尝试过使用 .isnumerical() 和 .isdigit() 但它们除了负数之外不会。

lowest_num = input("What would you like the lowest possible number to be?")
while lowest_num.isdigit() is not True:
    lowest_num = (input("Please only enter a number : ")).lower()

提前感谢您的帮助

【问题讨论】:

标签: python-3.6


【解决方案1】:

lowest_num = int(input("What would you like the lowest possible number to be?")) 应该这样做

好的,试试这个:

number_not_entered = True
num = 0 
while number_not_entered:
  try: 
    num = int(input("enter num"))
    number_not_entered = False
  except ValueError:
    print("please try again")

请注意,捕获所有异常通常是一种不好的做法。

【讨论】:

  • 这不会提示用户输入 int,直到他们这样做,这只会引发错误并结束程序。
  • 原来的问题中没有,您认为可以更新吗?
  • 很高兴为您提供帮助:)
【解决方案2】:

使用 numpy 库中的 isnan() 函数。先导入numpy再使用numpy.isnan(a number)

【讨论】:

  • 我尝试导入 numpy,但它告诉我没有名为 that 的模块。仅供参考,我使用的是 Pycharm 2017.3,不知道这是否重要。
猜你喜欢
  • 2022-12-18
  • 2019-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-09
  • 1970-01-01
  • 2015-12-08
  • 1970-01-01
相关资源
最近更新 更多