Reputation: 11
Python 2.7. I am new to Python and I am stuck with while True loop. Simple program to calculate salary. When 'standard' entered as a letter, it catches the error and jumps again to the line 'Enter your rate'. I want it to be repeated only where the error was captured and not starting to input all info all over again. Can someone help please?
while True:
try:
rate = float(raw_input("Enter your rate: "))
error = float(rate)
standard = float(raw_input("Enter total standard hours 100%: "))
error = float(standart)
except:
print 'Not a number'
continue
else:
sum = standard * rate
print sum
Thank you in advance.
Upvotes: 1
Views: 362
Reputation: 1
while True:
try:
rate = float(raw_input("Enter your rate: "))
standard = float(raw_input("Enter total standard hours 100%: "))
except ValueError:
print( 'Not a number' )
else:
sum = standard * rate
print(sum)
break
Upvotes: -1
Reputation: 510
while True:
try:
rate = float(raw_input("Enter your rate: "))
standard = float(raw_input("Enter total standard hours 100%: "))
except ValueError:
print 'Not a number'
else:
sum = standard * rate
print sum
break
You need to add a break at the end. Also you dont need to write error = float(..)
when you are already trying to typecaste it in the input step.
Also, there is a typo in the line error = float(standart)
. This will cause it to give exceptions forever.
Another good practice is to specify the type of error you expect ( ValueError ). This would help prevent things like typos.
Upvotes: 2
Reputation: 31011
In your code continue
instruction is not needed, as else
instruction is executed only if no exception has been thrown.
But to exit the loop in the "positive" case, add break
instruction
after print sum
.
And one more remark: Change standart
to standard
.
Upvotes: 0
Reputation: 31
Try splitting standard and rate out of the same loop, like so.
def get_input(text):
while 1:
try:
value = float(raw_input(text))
break
except:
print 'Not a Number'
return value
rate = get_input("Enter your rate: ")
standard = get_input("Enter total standard hours 100%: ")
sum = standard * rate
print(sum)
This way only the value that failed will be re-queried.
Upvotes: 0