【问题标题】:Python user must only enter float numbersPython 用户只能输入浮点数
【发布时间】:2014-09-14 20:14:15
【问题描述】:

我正在尝试找出如何做到这一点,以便用户[仅输入数字

edgeone = input("Enter the first edge of the triangle: ")

【问题讨论】:

  • 您使用的是 Python 2 还是 Python 3?
  • 我是 python 新手,只有 2 周的经验。我只是不明白设置此 try/catch 的正确方法,或者我应该使用 if/else。这就是我寻求帮助的原因,因为我想从视觉上看到有人设置它的方式。

标签: python input numbers


【解决方案1】:

我认为您只需要 > 0 的数字,还是希望小于零?无论如何,您可以在 while 循环中使用 try/except。

对于我认为您正在使用的 Python 3?

goodnumber = False
while not goodnumber:
    try:
        edgeone = int(input('Enter the first edge of the triangle:'))
        if edgeone > 0:
            print('thats a good number, thanks')
            goodnumber = True
        else:
            print('thats not a number greater than 0, try again please')
    except ValueError:
        print('Thats not a number, try again please')

希望这会有所帮助。

【讨论】:

  • 感谢您的回复。是的,这很有帮助。
【解决方案2】:

对于这种情况,您必须使用 except 处理程序:

try:
    value = int(raw_input("Enter your number:"))
    if not ( value < 0 ):
        raise ValueError()
except ValueError:
    print "you must enter a number <0 "
else:
    print value #or something else 

另外这个问题在这里已经有了答案:Accepting only numbers as input in Python

【讨论】:

  • 感谢您的回复。这很有帮助。
【解决方案3】:

你可以这样做。

i = 1
while(type(i)!=float):
    i=input("enter no.")
    try:
        int(i):
    except:
        try:
            i = float(i)
        except:
            pass
print(i)

【讨论】:

  • 在代码中添加一些解释会很好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-27
  • 2016-04-20
  • 2014-11-10
  • 2015-11-26
相关资源
最近更新 更多