1

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)
Tom Carrick
  • 6,349
  • 13
  • 54
  • 78
  • Hello and welcome to Stackoverflow. You should move the Investment variable outside of the loop. You can put it in another block to avoid inputs in other formats. – Mathemagician May 09 '20 at 08:16
  • 2
    Does this answer your question? [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – Tomerikoo May 09 '20 at 08:29

1 Answers1

4

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.

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69