正在尝试为作业编写一些代码。希望我们打印出每小时最快英里数的汽车品牌名称。但是为了找出最快的速度,老师希望我们做一个大型的if语句来找出它
class carspeed:
def __init__ (self,distance,time):
self.distance=distance
self.time=time
def cspeed(self):
return (self.distance)//(self.time)
Ford=carspeed(120,1.75)
Ferrari=carspeed(100,1.20)
BMW=carspeed(205,2.35)
Porsche=carspeed(155,1.85)
Audi=carspeed(190,2.10)
Jaguar=carspeed(255,2.45)
print("Ford speed in MPH:", Ford.cspeed())
print("Ferrari speed in MPH:", Ferrari.cspeed())
print("BMW speed in MPH:", BMW.cspeed())
print("Porsche speed in MPH:", Porsche.cspeed())
print("Audi speed in MPH:", Audi.cspeed())
print("Jaguar speed in MPH:", Jaguar.cspeed())
a=Ford.cspeed()
b=Ferrari.cspeed()
c=BMW.cspeed()
d=Porsche.cspeed()
e=Audi.cspeed()
f=Jaguar.cspeed()
def max_of_speed (a,b,c,d,e,f):
fastest=a
if fastest<b:
fastest=b
if fastest<c:
fastest=c
if fastest<d:
fastest=d
if fastest<e:
fastest=e
if fastest<f:
fastest=f
return fastest
print("The brand with the highest MPH is:", fastest)
#(输出)
Ford speed in MPH: 68.0
Ferrari speed in MPH: 83.0
BMW speed in MPH: 87.0
Porsche speed in MPH: 83.0
Audi speed in MPH: 90.0
Jaguar speed in MPH: 104.0
The brand with the highest MPH is: 68.0
#期望输出
Ford speed in MPH: 68.0
Ferrari speed in MPH: 83.0
BMW speed in MPH: 87.0
Porsche speed in MPH: 83.0
Audi speed in MPH: 90.0
Jaguar speed in MPH: 104.0
The brand with the highest MPH is: Jaguar
你本可以用更好的方式来做,但是不需要改变很多代码,你也可以这样做,但是请注意,这不是最好的方式
将新属性
name
添加到carspeed
,而不是为变量命名:输出:
你会遇到一些问题,因为你把所有的车速放在一堆独立的变量中,而不是放在某个集合中。我建议买本字典。以下是您的代码的外观:
这将打印出:
我试图避免在上面的代码中使用太复杂的东西,但是这里是
max_of_speed
函数的一行版本,如果您愿意,可以使用它相关问题 更多 >
编程相关推荐