简体   繁体   中英

Multiple inputs in while loop, along with try-except block in Python

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 (eg 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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM