我正在尝试制作一个程序,如果我输入一个正数,那么它会进一步执行,但是如果我输入一个负数或一个字母,它应该打印“房价必须是一个正数'它应该再次要求输入。这是我到目前为止所做的,但当我输入一个数字时,我得到一个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')
答案 0 :(得分: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
答案 1 :(得分:0)
如果您使用的是Python 2,其input
函数对用户输入有eval(..)
,而eval("2")
则返回int
,而不是str
python2 -c 'print(eval("2").__class__)'
<type 'int'>
如果您将input
替换为raw_input
,那么您的代码将适用于Python 2,而eval
不会var response = {
"statusCode": 200,
"data": {
"Response": "R00=00&R01=Balance Added. &R02=59.00&R03=1.00",
"TokenStatus": "Used"
}
};
var retVal = response.data.Response.split('&').reduce(function(acc, ele) {
var x = ele.split('=');
acc[x[0]] = x[1];
return acc;
}, {});
console.log(retVal);
。
答案 2 :(得分:0)
我建议异常处理。 &#34; -10&#34; .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
答案 3 :(得分: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()