尝试使用 Python 为旅行计划创建 While 语句

Trying to use Python to create a While statement for a Travel Program

#Program to calculate cost of gas on a trip
#Created by Sylvia McCoy, March 31, 2015
#Created in Python
#Declare Variables

Trip_Destination = 0
Number_Miles = 0
Current_MPG = 0.0
Gallon_Cost = 0.0
Total_Gallons = 0.0
Total_Cost = 0.0

#Loop to enter destinations

while True:
    Trip_Destination = input("Enter where you would like to travel:  ")
    Number_Miles = float(input("Enter how many miles to your destination:  "))
    Gallon_Cost = float(input("Enter how much a gallon of gas costs:  "))
    Current_MPG = float(Number_Miles / Gallon_Cost)
    print("Your trip to: " + Trip_Destination)
    print("Your total miles: " + Number_Miles)
    print("Your MPG:  " + Current_MPG)

第 20 行和第 21 行中的错误...前面提到为浮动,如何让它们打印出来?必须在 Python 完成工作。谢谢!

看看这个

while True:
    Trip_Destination = input("Enter where you would like to travel:  ")
    Number_Miles = float(input("Enter how many miles to your destination:  "))
    Gallon_Cost = float(input("Enter how much a gallon of gas costs:  "))
    Current_MPG = float(Number_Miles / Gallon_Cost)
    print("Your trip to: " + Trip_Destination)
    print("Your total miles:{}".format(Number_Miles))
    print("Your MPG:{}".format(Current_MPG))

打印("your string {}".格式(x))

它称为字符串格式

串联

您正在尝试添加一个字符串和一个浮点数,在 Python 中,这两个不会被自动转换。

print("Your total miles: " + str(Number_Miles)) # same for miles per gallon

字符串格式

否则,您也可以使用字符串格式来插入所需的变量。

print("Your total miles: {0}".format(Number_Miles)) # same miles per gallon

您不能使用 + 运算符将 stringfloat 组合起来。

它只能用于组合两个单一类型(例如 2 个字符串、2 个浮点数等)

话虽如此,要获得所需的输出,您可以将所需的所有转换简化为一行,如下所示:

Trip_Destination = 0
Number_Miles = 0
Current_MPG = 0.0
Gallon_Cost = 0.0
Total_Gallons = 0.0
Total_Cost = 0.0

#Loop to enter destinations

while True:
    Trip_Destination = input("Enter where you would like to travel:  ")
    Number_Miles = input("Enter how many miles to your destination:  ")
    Gallon_Cost = input("Enter how much a gallon of gas costs:  ")
    Current_MPG = str(float(Number_Miles) / float(Gallon_Cost))
    print("Your trip to: " + Trip_Destination)
    print("Your total miles: " + Number_Miles)
    print("Your MPG:  " + Current_MPG)

单独使用 input() 函数可以让您从用户那里得到一个值(已经是 string 的形式)。这样,您以后就不必 format/convert 它了。