def printWelcome():
print ('Welcome to the Miles per Gallon program')
def getMiles():
miles = float(input('Enter the miles you have drove: '))
return miles
def getGallons():
gallons = float(input('Enter the gallons of gas you used: '))
return gallons
def printMpg(milespergallon):
print ('Your MPG is: ',str(milespergallon))
def calcMpg(miles,gallons):
mpg = miles / gallons
return mpg
def rateMpg(mpg):
if mpg < 12:
print ("Poor mpg")
elif mpg < 19:
print ("Fair mpg")
elif mpg < 26:
print ("Good mpg")
else:
print ("Excellent mpg")
if __name__ == '__main__':
printWelcome()
print('\n')
miles = getMiles()
if miles <= 0:
print('The number of miles cannot be negative or zero. Enter a positive number')
miles = getMiles()
gallons = getGallons()
if gallons <= 0:
print('The gallons of gas used has to be positive')
gallons = getGallons()
print('\n')
mpg = calcMpg(miles,gallons)
printMpg(mpg)
print('\n')
rateMpg(mpg)
重复上述过程的循环可以放在main()函数开始的地方。它将要求为n辆汽车输入n次,并为所有输入计算,评分和mpg
,
如果要从用户那里获取输入,然后重试输入是否未经验证,就像声明一个初始无效值并循环直到用户输入一个有效值一样简单:
milesDrove = -1
while milesDrove <= 0:
try:
milesDrove = float( input( "How many miles were driven?" ) )
if milesDrove <= 0:
print("Please enter a number greater then 0")
except:
print("Please enter a number greater then 0")
给出您问题的基本水平,我假设您刚刚在学院/学校开始了python课程。在上面的示例中,我使用了异常处理,因为如果输入的内容不是数字,则对float()的调用会引发异常(永远无法信任用户,但取决于您对验证的满意程度)。>
循环N次:
for i in range(4):
print("Calculate the MPG for car #%d" % i + 1)
milesDrove = float( input( "How many miles were driven?" ) )
gallonsOfGasUsed = float(input( "How many gallons of gas were used?" ) )
milesPerGallon = milesDrove / gallonsOfGasUsed
print ('\n')
print("The MPG is: " + str(milesPerGallon) )
if milesPerGallon < 12:
print ("Poor mpg")
elif milesPerGallon < 19:
print ("Fair mpg")
elif milesPerGallon < 26:
print ("Good mpg")
else:
print ("Excellent mpg.")\
最后,关于您对函数的问题,拥有可以一齐完成所有工作的函数实在是太过分了。在您的情况下,大多数将只返回一个值。通常,尽管python解释器即使不在函数内(这不是c或java,我们实际上并不需要主要函数)也可以运行您的代码,但通常人们会按如下方式声明其脚本的起点:>
if __name__ == "__main__":
do_stuff()
初学者很难决定何时声明一个函数。通常,只要该代码段在代码的其他部分被多次调用,或者该函数完成的工作定义得非常好(例如,计算斐波那契总和的函数),就应该声明一个函数。 / p>
本文链接:https://www.f2er.com/3127430.html