简体   繁体   中英

python 3 - limiting invalid inputs

I am trying to limit the number of invalid inputs before the program closes. So I need the program to loop back to the original input question if the input is invalid. My limit of attempts will be 3.

I am not sure what syntax to use or how I should structure it.

heres an example of my code:

min_mile = 0

def main():

    print('hello',name,', today we will be doing some standard to metric conversions.')
    print('The first conversion will be to convert miles to kilometers.')
    MileToKm()


def MileToKm():
    mile = float(input('What is the number of miles that you would like to convert? ')
    mile_conv = mile * 1.6

    if mile_conv > min_mile :
        print ('The result would be', format(mile_conv,'.2f'),'kilometers.')
    else:
        exit(print('invalid input'))

main()

So right now if the input after the conversion comes out as negative its considered invalid. I need to modify it so the user has three attempts to input a valid number before the program closes.

How would I go about this?

I am in python 3.3.3

Change the exit paths of MileToKm to look like this:

if mile_conv > min_mile :
    print ('The result would be', format(mile_conv,'.2f'),'kilometers.')
    return True

else:
    return False

Then wrap your function to handle retries:

def TryMileToKm():
    attempts = 0

    while attempts < 3:
        attempts += 1
        if MileToKm(): break

    if attempts >= 3:
        print 'Invalid input'
        exit(1)

This is not the most idiomatic way of doing this, but I tried to keep the intent obvious.

EDIT very well, here it is:

def miles_to_km(miles):
    return miles * 1.6

def read_miles(prompt):
    miles = float(input(prompt))
    if miles < 0: raise ValueError()
    return miles

def read_miles_retry(prompt, retries = 3):
    while retries > 0:
        try:
            return read_miles(prompt)
        except:
            retries -= 1
            print('Invalid input')

    raise ValueError()

def main():
    try:
        kms = miles_to_km(read_miles_retry('Miles? '))
        print(kms)
    except:
        exit(1)

main()

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