首页 文章

AttributeError:'int' object没有属性'isdigit'和NameError

提问于
浏览
2

我正在尝试制作一个程序,如果我输入一个正数,那么它会进一步执行,但如果我输入一个负数或一个字母,它应该打印'House price must be a positive number',它应该再次要求输入 . 这是我到目前为止所做的,但是当我输入一个数字时,我得到一个 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')

4 回答

  • 1

    如果要保持循环运行直到收到正整数,则可以测试输入的负整数/非数字值,然后继续下一次迭代 . 否则你可以摆脱你的循环

    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
    
  • 0

    我建议异常处理 . “-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
    
  • 0

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

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

    如果用 raw_input 替换 input ,那么你的代码将适用于Python 2,而 eval 不会 eval .

  • 0

    这是一个不同的方法:

    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()

相关问题