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)
2
  • 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. Commented May 9, 2020 at 8:16
  • 2
    Does this answer your question? Asking the user for input until they give a valid response Commented May 9, 2020 at 8:29

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.