jeudi 23 juin 2016

Python 3.5.1, How to ask for input 3 times in a function

I have a basic main() function that starts by asking for input (miles information). I have to leave the input statement in the main function (required) and then proceed on to the milesToKM() function.
The goal is:

1) If input is >=0, then print results and move to the next conversion (gallons)

2) If input is <0, state that the input is incorrect and ask for input again 2 more times (3 total chances). After 3 incorrect attempts the program needs to TERMINATE.

I am not allowed to use import sys (sys.exit) or "break" in this program.
Program needs to remain simple. What is the easiest way to update this code to get the results needed?

def main():
    #Get miles to be converted to kilometers
    miles = float(input('How many miles would you like converted to kilometers?\n'))
    milesToKm(miles)

    #Obtain the amount of gallons to convert
    gallons = float(input('Please give me the amount of gallons you would like to convert to liters.\n'))
    gallonsToLiter (gallons)

def milesToKm(value):
    if value >= 0:
        milesToKm = value * 1.6  # Calculation to convert miles to kilometers
        print (value, 'miles is', format(milesToKm, ',.1f'), 'kilometers.\n') # Display kilometers
    else:
        print ('That is an incorrect value.  Please try again.')

def gallonsToLiter(value):
    if value >= 0:
        gallonsToLiter = value * 3.9 # C0nvert gallons into liters
        print (value, 'gallons is', format(gallonsToLiter, '.1f'), 'liters.\n') # Display liters
    else:
        print ('That is an incorrect value.  Please try again.')

#Call the main function
main()

Aucun commentaire:

Enregistrer un commentaire