Can I shorten this code with the python "continue" construct. I'm thinking that
continue will eliminate having to repeat the prompt to re-enter the miles driven and gallons used - everything from "if choice == yes" on
# welcome message
print("The Miles Per Gallon Program")
print()
# get input from the user
miles_driven = float(input("Enter miles driven: "))
gallons_used = float(input("Enter gallons of gas used: "))
# verify input
if miles_driven <= 0:
print("Miles driven must be greater than zero. Please try again.")
elif gallons_used <= 0:
print("Gallons used must be greater than zero. Please try again.")
else:
# calculate and display miles per gallon
mpg = round((miles_driven / gallons_used), 2)
print("Miles Per Gallon: ", mpg)
# lower() returns lower case character
choice = "y"while choice.lower() == "y":
choice = input("\nI can calculate mpg for the next leg of your travels! (y/n): ")
if choice == "y":
miles_driven = float(input("Enter miles driven: "))
gallons_used = float(input("Enter gallons of gas used: "))
mpg = round((miles_driven / gallons_used), 2)
print("Miles Per Gallon: ", mpg)
else:
print()
print("Okay, bye!")
Is there a do-while loop in Python?
It's perhaps the simpler workaround to avoid asking the user the same question twice. If there isn't, as I suspect, you can try something like this:
(BTW, using a user-friendly programming language should not encourage you to keep your code untidy: splitting it into functions is yet advisable)
#
def getMilesAndGallons() :
miles_driven = 0;
while miles_driven <= 0 :
miles_driven = float(input("Enter miles driven: "))
if miles_driven <= 0 :
print("Miles driven must be greater than zero. Please try again.")
gallons_used = 0;
while gallons_used <= 0 :
gallons_used = float(input("Enter gallons of gas used: "))
if gallons_used <= 0:
print("Gallons used must be greater than zero. Please try again.")
return (miles_driven, gallons_used)
def calculateMpg(*mgdata) :
return round((mgdata[0] / mgdata[1]), 2)
# welcome message
print("The Miles Per Gallon Program")
print()
# lower() returns lower case character
choice = "y"while choice.lower() != "n":
# get input from the user
mgdata = getMilesAndGallons()
# calculate and display miles per gallon
mpg = calculateMpg(*mgdata)
print("Miles Per Gallon: ", mpg)
choice = input("\nI can calculate mpg for the next leg of your travels! (y/n): ")
if choice != "y":
break;
print("Okay, bye!")
(I don't want to appear unwelcoming, but this is supposed to be a C++ forum)