I want the following program to ask to enter again without ending if entered value is not a integer. please help.
x=input('ENTER SUM')
try:
p=float(x)
except:
print('Error! Try again')
quit()
y=input('ENTER RATE PER ANNUM')
try:
r=float(y)
except:
print('Error! Try again')
quit()
z=input('ENTER TIME IN MONTH')
try:
fz=float(z)
except:
print('Error! Try again')
quit()
t=(fz/12)
print('Interest=Rs',p*t*r/100,'\nAmount to pay=Rs',p+p*t*r/100)
Please help us help you by using proper tags in order to understand your code.
Probably, you have noticed that you have a lot of repeating code. This screams - define a function.
So first step would be to define a function that will take prompt and maybe conversion function and will return the user input converted using this conversion function.
In order to keep asking until you get valid input - ask inside infinite loop and return/breakout of the loop when user input is valid.
[quote='buran' pid='123035' dateline='1597216916']
Probably, you have noticed that you have a lot of repeating code. This screams - define a function.
So first step would be to define a function that will take prompt and maybe conversion function and will return the user input converted using this conversion function.
In order to keep asking until you get valid input - ask inside infinite loop and return/breakout of the loop when user input is valid.
[/quo
Thank you!
def input_float(prompt):
while True:
try:
return float(input(prompt))
except:
pass
p = input_float('ENTER SUM ')
r = input_float('ENTER RATE PER ANNUM ')
t = input_float('ENTER TIME IN MONTH ') / 12
print('Interest=Rs',p*t*r/100,'\nAmount to pay=Rs',p+p*t*r/100)
EDIT: ninjad by deanhystad
As suggested by buran - one option is to create validation function and call it three times:
def validate(request):
while True:
answer = input(request)
try:
return float(answer)
except ValueError:
print(f'Expected float but {answer!r} was entered')
total = validate('Enter sum: ')
rate = validate('Enter rate per annum: ')
time = validate('Enter time in month: ')
# or alternatively:
total, rate, time = (validate(f'Enter {item}: ') for item in ('sum', 'rate per annum', 'time'))