需要变量来添加,而不是连接Python

时间:2018-10-31 17:38:53

标签: python concatenation addition

这是我完成的编码:

from math import *
from time import sleep

def vacation():
    print("Time to plan for a vacation.")

    sleep(1)

    dates = input("Let's start with the dates. What day are you getting there, and what day are you leaving? For formatting, you can use month/day-month/day.")

    sleep(1)

    location = input("Now where are you traveling to?")

    sleep(1)

    ticketCost = input("What is the cost of a two-way ticket to " + location + " and back?")

    sleep(1)

    dayOne = input("What is the cost for at least two meals on the first day?")
    dayTwo = input("What is the cost for at least two meals on the second day?")

    sleep(1)

    hotel = input("What is the name of the hotel you are staying at?")
    hotelCost = input("What is the cost for one night at (the) " + hotel + "?")

    sleep(1)

    print("Vacation! Going to " + location + " for " + dates + ".")
    print("-------------------------------")
    print("Total cost of the trip:")
    print("-------------------------------")

    sleep(1)

    print("Plane Ticket: " + ticketCost)

    sleep(1)

    print("Estimate Cost of Meals (Day One): " + dayOne + ".")
    sleep(1)
    print("Estimate Cost of Meals (Day Two): " + dayTwo + ".")
    sleep(1)
    print("One Night at (the) " + hotel + ": " + hotelCost + ".")
    sleep(1)
    **total = hotelCost + dayOne + dayTwo + ticketCost**
    **totalExtra = total + 50
    print("The total is: " + total + ".")**
    sleep(1)
    print("Make sure you leave some room for souvenirs, pay tolls, and other expenses. Additional $50 is added for this, and that total is: " + totalExtra + ".")
    print("-------------------------------")
    sleep(1)
    print("Enjoy your vacation!")

vacation()

问题区域以粗体显示。我不知道该怎么办,我尝试在多个地方使用int(),str()等。总数不应是乱码(即“ 843290842”)。我想念什么吗?

1 个答案:

答案 0 :(得分:0)

input函数返回一个字符串,而不是整数。只需将它们投射到任何地方即可:

dates = int(input("Let's start with the dates. What day are you getting there, and what day are you leaving? For formatting, you can use month/day-month/day."))

等...

其他几点

如果以后将所有这些都加在一起,请考虑将它们放在一个集合中,而不是一堆松散的变量。字典可以让您保留名称:

costs = {}
costs['dates'] = int(input("Let's start with the dates. What day are you getting there, and what day are you leaving? For formatting, you can use month/day-month/day."))

最后,您只需遍历字典即可轻松获得总数

total = sum(costs.values())

请记住,不要使用像hotel这样的字符串,而应该将其替换为hotel_name

最后,您应该尝试进行字符串插值(这取决于您的Python版本,但适用于3.6以上版本):

"What is the cost for one night at (the) " + hotel + "?"

成为

f"What is the cost for one night at (the) {hotel}?"