Reputation: 13
I'm trying to create an ROI calculator. I want to accept the input in only int
format. I've created a try-except
block to avoid inputs in other formats. However, my logic fails if any user enters an incorrect input (e.g. str
) in either Rent
or Loss
.
If they do that, the while loop starts asking for the input from Investment
again. I want to bypass that, and let the code ask for the input from that respective variable itself, be it Rent
or Loss
. Any suggestions, please?
print('This is a ROI calculator. Please enter below details:')
while True:
try:
Investment=int(input('Investment:'))
Rent=int(input('Rent/month:'))
Loss=int(input('Loss/year:'))
if Loss:
break
except ValueError:
print('Please enter in a number format only')
def ROI(Investment,Rent,Loss):
Net_profit=int((Rent*12) - Loss)
ROI=((Net_profit/Investment)*100)
ROI=round(ROI,2)
print(f'Your Return on Investment is: {ROI}')
ROI(Investment,Rent,Loss)
Upvotes: 1
Views: 674
Reputation: 51643
Use the power of functions:
def inputInt(text):
"""Ask with 'text' for an input and returns it as int(). Asks until int given."""
while True:
try:
what = int(input(text))
return what # only ever returns a number
except ValueError:
print('Please enter in a number format only')
while True:
Investment = inputInt('Investment:')
Rent = inputInt('Rent/month:')
Loss = inputInt('Loss/year:')
if Loss: # this will break as soon as Loos is != 0 ?
break
# etc
so you always handle numeric input down below and keep the looping for input gathering as well as error handling in a specific function that always returns an integer.
Upvotes: 4