Skip to main content
 首页 » 编程设计

python之属性错误 : 'int' object has no attribute 'isdigit' and NameError

2025年02月15日31langtianya

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

请您参考如下方法:

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

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