繁体   English   中英

AttributeError: 'int' 对象没有属性 'isdigit' 和 NameError

[英]AttributeError: 'int' object has no attribute 'isdigit' and NameError

我正在尝试制作一个程序,如果我输入一个正数,它会进一步执行,但是如果我输入一个负数或一个字母,它应该打印“房价必须是一个正数”,它应该再次要求输入。 这是我到目前为止所做的,但是当我输入一个数字时,我得到一个AttributeError ,当我输入一个字母时,我得到一个NameError

import math

while True:
    home_price = input('Enter the price of your dreams house')
    if home_price.isdigit():
        if home_price > 0:    
            home_price = int(house_price)
            break
        else:
            print('House price must be a positive number only')

如果您使用的是 Python 2,其input函数对用户输入执行eval(..) ,并且eval("2")返回int ,而不是str

python2 -c 'print(eval("2").__class__)'
<type 'int'>

如果您将input替换为raw_input ,则您的代码将在 Python 2 上运行,而raw_input不执行eval

如果您想保持循环运行直到收到正整数,您可以只测试输入的负整数/非数字值,然后继续下一次迭代。 否则你可以从你的循环中解脱出来

while True:
    home_price = input('Enter the price of your dream house: ')

    if not home_price.isdigit() or not int(home_price) > 0:
        print('House price must be a positive integer only')
        continue

    print('The price of your dream house is: %s' % home_price)
    break

Enter the price of your dream house: a
House price must be a positive integer only
Enter the price of your dream house: -1
House price must be a positive integer only
Enter the price of your dream house: 1000
The price of your dream house is: 1000

我推荐异常处理。 "-10".isdigit() 返回 false。

import math

while True:
    home_price = input('Enter the price of your dreams house')
    try:
        if int(home_price) > 0:    
            house_price = int(home_price)
            break
        else:
            print('House price must be a positive number only')
    except ValueError:
        continue

这是一种不同的方法:

home_price_gotten = False

while not home_price_gotten:
    try:
        home_price = input('Enter the price of your dream house\n')
        home_price = int(home_price)
        if home_price < 1:
            raise TypeError
        home_price_gotten = True
        break
    except ValueError:
        print("Home price must be a number, but '{}' is not.".format(home_price))
    except TypeError:
        print('Home price must be a positive number')


print("Success! Home price is : '{}'".format(home_price))

基本上,在用户给出有效的房屋价格之前,循环会要求他提供一个,并尝试将他的输入转换为一个数字。 如果失败,可能是因为输入的不是数字。 如果它小于 1,则会引发另一个错误。 所以你被覆盖了。

顺便说一句,这仅适用于 python 3。 对于 python 2,将input()交换为raw_input()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM