Вернуть несколько значений в функцию - PullRequest
0 голосов
/ 18 января 2020

Я делаю университетский проект по созданию программы заказа билетов на план, пока что вот что я сделал:

Во-первых, это функция поиска типа места:

def choosingFare():
    print("Please choose the type of fare. Fees are displayed below and are in addtion to the basic fare.")
    print("Please note choosing Frugal fare means you will not be offered a seat choice, it will be assigned to the ticketholder at travel time.")
    listofType = [""] * (3)

    listofType[0] = "Business: +$275"
    listofType[1] = "Economy: +$25"
    listofType[2] = "Frugal: $0"
    print("(0)Business +$275")
    print("(1)Economy +$25")
    print("(2)Frugal: $0")
    type = int(input())
    while type > 2:
        print("Invalid choice, please try again")
        type = int(input())
    print("Your choosing type of fare is: " + listofType[type])
    if type == 0:
        price1 = 275
    else:
        if type == 1:
            price1 = 25
        else:
            price1 = 0

    return price1, listofType[type]

А это функция поиска пункта назначения:

def destination():
    print("Please choose a destination and trip length")
    print("(money currency is in: Australian Dollars: AUD)")
    print("Is this a Return trip(R) or One Way trip(O)?")
    direction = input()
    while direction != "R" and direction != "O":
        print("Invalid, please choose again!")
        direction = input()
        print("Is this a Return trip(R) or One Way trip(O)?")
    if direction == "O":
        print("(0)Cairns oneway: $250")
        print("(2)Sydney One Way: $420")
        print("(4)Perth One Way: $510")
    else:
        print("(1)Cairns Return: $400")
        print("(3)Sydney Return: $575")
        print("(5)Perth Return: $700")
    typeofTrip = [""] * (6)

    typeofTrip[0] = "Cairns One Way: $250"
    typeofTrip[1] = "Cairns Return: $400"
    typeofTrip[2] = "Sydney One Way: $420"
    typeofTrip[3] = "Sydney Return: $575"
    typeofTrip[4] = "Perth One Way: $510"
    typeofTrip[5] = "Perth Return: $700"
    trip = int(input())
    while trip > 5:
        print("Invalid, please choose again")
        trip = int(input())
    if trip == 0:
        price = 250
    else:
        if trip == 1:
            price = 400
        else:
            if trip == 2:
                price = 420
            else:
                if trip == 3:
                    price = 574
                else:
                    if trip == 4:
                        price = 510
                    else:
                        price = 700
    print("Your choice of destination and trip length is: " + typeofTrip[trip])

    return price, typeofTrip[trip]

А это функция, вычисляющая общую стоимость:

def sumprice():
    price = destination()
    price1 = choosingFare()
    price2 = choosingseat()
    sumprice = price1 + price2 + price
    print("How old is the person travelling?(Travellers under 16 years old will receive a 50% discount for the child fare.)")
    age = float(input())
    if age < 16 and age > 0:
        sumprice = sumprice / 2
    else:
        sumprice = sumprice

    return sumprice

У меня ошибка:

line 163, in <module> main()
line 145, in main sumprice = sumprice()
line 124, in sumprice
sumprice = price1 + price2 + price
TypeError: can only concatenate tuple (not "int") to tuple

Может кто-нибудь мне помочь? Я действительно застрял.

Я не могу вернуть все

Ответы [ 2 ]

0 голосов
/ 18 января 2020

Эти функции возвращают по 2 значения каждое: destination (), choiceFare (), choiceseat ().

Возврат нескольких значений одновременно возвращает кортеж из этих значений: Например:

 return price, typeofTrip[trip] # returns (price, typeofTrip[trip])

Таким образом, при расчете суммы всех цен вам необходимо получить доступ к цене, цене1, цене2 из кортежей:

sumprice = price1[0] + price2[0] + price3[0]

Альтернативно: вы можете отредактировать код для возврата списка / словаря или какой-либо другой структуры данных согласно вашему удобству.

0 голосов
/ 18 января 2020
  • Сначала позвольте мне объяснить, что происходит, когда вы пишете. return price, typeofTrip[trip].
  • Приведенная выше строка вернет кортеж из двух значений.
  • Теперь для sumprice я думаю, что вы хотите получить сумму всех цен. Итак, вы просто хотите суммировать первый элемент возвращаемых значений.
  • Это должно работать для вашего случая.
sumprice = price1[0] + price2[0] + price3[0]
...