gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 04:58:20 61 4
gpt4 key购买 nike

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

关于python - 属性错误 : 'int' object has no attribute 'isdigit' and NameError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46473142/

61 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com