我是Python 3.6新手,在Python IDLE上使用3.6。我为学校编写了一个程序,可以根据速度和时间计算行进距离。我能够使该程序显示很大的距离数值,但是我希望它在数值之后还显示“ miles”,从而显示测量单位。这是我的代码:
def main():
#variable for speed
speed = 60
#variables for time
time1 = 5
time2 = 8
time3 = 12
#variables for distance
distance1 = time1 * speed
distance2 = time2 * speed
distance3 = time3 * speed
#display the distance equations
print ("The distance the car will travel in 5 hours is ", distance1 + " miles")
print ("The distance the car will travel in 8 hours is ", distance2 + "miles")
print ("The distance the car will travel in 12 hours is ", distance3 + "miles")
您可以看到我试图在哪里连接第一个字符串,变量和第二个字符串。这破坏了我的代码。任何帮助表示赞赏!
答案 0 :(得分:1)
我建议使用Python中实现的最新最酷的格式设置选项,即formatted string literals:
print(f"The distance the car will travel in 5 hours is {distance1} miles")
但是您也可以执行以下任何操作:
print("The distance the car will travel in 5 hours is {} miles".format(distance1))
print("The distance the car will travel in 5 hours is %s miles" % distance1)
print("The distance the car will travel in 5 hours is", distance1, "miles")
print("The distance the car will travel in 5 hours is" + str(distance1) + " miles")