I am trying to make a program in which if I enter a positive number then it executes further but if I enter a negative number or a letter it should print 'House price must be a positive number' and it should ask for the input again. This is what I've done so far but when I enter an number I get an AttributeError
and when I enter a letter I get a 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')
If you are using Python 2, whose input
function does an eval(..)
on the user input, and eval("2")
returns an int
, not a str
.
python2 -c 'print(eval("2").__class__)'
<type 'int'>
Your code will work on Python 2 if you replace input
with raw_input
, which doesnt do an eval
.
If you want to keep your loop running until you receive a positive integer, you can just test for negative integers / non digit values entered and then continue to the next iteration. Otherwise you can just break from your loop
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
I recommend exception handling. "-10".isdigit() returns 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
Here is a different method:
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))
Basically, until the user has given a valid home price, the loop will ask him for one, and try to convert his input to a number. If it fails, it's probably because the input is not a number. If it's smaller than 1, it raises another error. So you're covered.
BTW, this works in python 3 only. For python 2, swap input()
for raw_input()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.