Проблема Python с def, ошибка с переменной внутри def, переменная не работает в операторе if - PullRequest
0 голосов
/ 19 октября 2018

Я сделал def roomidea(test) со входами внутри, я думаю, что сделал return правильно.Теперь под первым оператором if у меня есть sBedsize, sRoomview, sVehicle, iRoomnum, iNights = roomidea(test), поэтому он читает функцию.Проблема в том, что когда я запускаю код, он отображает

sBedsize не определено

, хотя у меня все это в выражении if.Почему это не работает?

Я работал над этим проектом некоторое время, теперь я думаю, что мой второй def price(test2) работает, но я еще не уверен, так как первый def является основной проблемойДо сих пор я был бы признателен за любые советы или помощь или что-нибудь, что может помочь мне решить или узнать, как решить эту проблему.

Теперь у меня также есть большая проблема, что я использую много переменных во второй def, то есть я использую переменные для решения других переменных, таких как dTotalqav и имеющих dPrice1, dPrice5, dResortfee1 и dResortfee2 внутри одного и того же def.Из-за этого это будет правильно или просто создаст другую ошибку?

Я запускаю это в PyCharm, на случай, если это уместно.

import time
def roomidea(test):
    sBedsize = input("For your room do you want a queen-size bed or a king-size bed? Type Queen for queen-size or King for king-size:\t")
    sRoomview = input("For your room do you want the standard view or the atrium view? Type Standard for standard-view or Atrium for atrium-view:\t")
    sVehicle = input("Will you be parking at our hotel? Type Yes if you are, or No if you are not:\t")
    iRoomnum = int(input("Please enter the amount of rooms you wish to check out:\t"))
    iNights = int(input("Please enter the amount of nights you wish to stay:\t"))
    return sBedsize, sRoomview, sVehicle, iRoomnum, iNights

def price(test2):
    dPrice1 = iNights * 280
    dPrice2 = iNights * 320
    dPrice3 = iNights * 295.50
    dPrice4 = iNights * 335.50
    dPrice5 = iNights * 15.75
    dResortfee1 = iNights * 20
    dResortfee2 = iRoomnum * 20
    dTotalqs = dPrice1 + dPrice5 + dResortfee1 + dResortfee2
    dTotalqa = dPrice2 + dPrice5 + dResortfee1 + dResortfee2
    dTotalqsv = dPrice1 + dResortfee1 + dResortfee2
    dTotalqav = dPrice2 + dResortfee1 + dResortfee2
    dTotalks = dPrice3 + dPrice5 + dResortfee1 + dResortfee2
    dTotalka = dPrice4 + dPrice5 + dResortfee1 + dResortfee2
    dTotalksv = dPrice3 + dResortfee1 + dResortfee2
    dTotalkav = dPrice4 + dResortfee1 + dResortfee2
    dTaxqs = dTotalqs * 0.15
    dTaxqa = dTotalqa * 0.15
    dTaxqsv = dTotalqsv * 0.15
    dTaxqav = dTotalqav * 0.15
    dTaxks = dTotalks * 0.15
    dTaxka = dTotalka * 0.15
    dTaxksv = dTotalksv * 0.15
    dTaxkav = dTotalkav * 0.15
    dOverallqs = dTotalqs + dTaxqs
    dOverallqa = dTotalqa + dTaxqs
    dOverallqsv = dTotalqsv + dTaxqs
    dOverallqav = dTotalqav + dTaxqs
    dOverallks = dTotalks + dTaxqs
    dOverallka = dTotalka + dTaxqs
    dOverallksv = dTotalksv + dTaxqs
    dOverallkav = dTotalkav + dTaxqs
    return dPrice1, dPrice2, dPrice3, dPrice4, dPrice5, dResortfee1, dResortfee2, dTotalqs, dTotalqa, dTotalqsv, dTotalqav, dTotalks, dTotalka, dTotalksv, dTotalkav, dTaxqs, dTaxqa, dTaxqsv, dTaxqav, dTaxks, dTaxka, dTaxksv, dTaxkav, dOverallqs, dOverallqa, dOverallqsv, dOverallqav, dOverallks, dOverallka, dOverallksv, dOverallkav



if  sBedsize == "Queen" and sRoomview == "Standard" and sVehicle == "Yes":
    sBedsize, sRoomview, sVehicle, iRoomnum, iNights = roomidea(test)
    print("The price for a Queen-Size bed with the Standard view and you are parking a vehicle, this comes to the total of $%.2f" % dTotalqs + " If this is how you want your room, type Yes, if you want to pick another option, type No.")
elif sBedsize == "Queen" and sRoomview == "Atrium" and sVehicle == "Yes":
    sBedsize, sRoomview, sVehicle, iRoomnum, iNights = roomidea()
    print("The price of Queen-Size bed with the Atrium view and you are parking a vehicle, this comes to the total of $%.2f" % dTotalqa + " If this is how you want your room, type Yes, if you want to pick another option, type No.")
elif sBedsize == "Queen" and sRoomview == "Standard" and sVehicle == "No":
    sBedsize, sRoomview, sVehicle, iRoomnum, iNights = roomidea()
    print("The price for a Queen-Size bed with the Standard view and you are not parking a vehicle, this comes to the total of $%.2f" % dTotalqsv + " If this is how you want your room, type Yes, if you want to pick another option, type No.")
elif sBedsize == "Queen" and sRoomview == "Atrium" and sVehicle == "No":
    sBedsize, sRoomview, sVehicle, iRoomnum, iNights = roomidea()
    print("The price for a Queen-Size bed with the Atrium view and you are not parking a vehicle, this comes to the total of $%.2f" % dTotalqav + " If this is how you want your room, type Yes, if you want to pick another option, type No.")
elif sBedsize == "King" and sRoomview == "Standard" and sVehicle == "Yes":
    sBedsize, sRoomview, sVehicle, iRoomnum, iNights = roomidea()
    print("The price for a King-Size bed with the Standard view and you are parking a vehicle, this comes to the total of $%.2f" % dTotalks + " If this is how you want your room, type Yes, if you want to pick another option, type No.")
elif sBedsize == "King" and sRoomview == "Atrium" and sVehicle == "Yes":
    sBedsize, sRoomview, sVehicle, iRoomnum, iNights = roomidea()
    print("The price for a King-Size bed with the Atrium view and you are parking a vehicle, this comes to the total of $%.2f" % dTotalka + " If this is how you want your room, type Yes, if you want to pick another option, type No.")
elif sBedsize == "King" and sRoomview == "Standard" and sVehicle == "No":
    sBedsize, sRoomview, sVehicle, iRoomnum, iNights = roomidea()
    print("The price for a King-Size bed with the Standard view and you are not parking a vehicle, this comes to the total of $%.2f" % dTotalksv + " If this is how you want your room, type Yes, if you want to pick another option, type No.")
elif sBedsize == "King" and sRoomview == "Atrium" and sVehicle == "No":
    sBedsize, sRoomview, sVehicle, iRoomnum, iNights = roomidea()
    print("The price for a King-Size bed with the Standard view and you are not parking a vehicle, this comes to the total of $%.2f" % dTotalkav + " If this is how you want your room, type Yes, if you want to pick another option, type No.")
else:
    print("You did not enter the information correctly")
time.sleep(5)
feedback = input("Would you like to change your room choices? Type Yes or No for the options").upper()
if feedback == "YES":
    print("Thank you for picking a room with us, I hope you enjoy your room and we are hoping to see you back again!")
elif feedback == "NO":
    print("We are sorry that the room you picked isn't how you wanted it, please retype how you want your room, if you want to leave just type quit")
    time.sleep(5)
    print(test)

Также, наконец, для времени импорта, а затемtime.sleep (5), затем print (test) потом, я использую его, чтобы он перепечатывал исходные данные, чтобы они могли изменить свои входы и, возможно, если они выбрали «Queen Standard Yes 1 1», но они допустили ошибку, которую ониможете набрать no и изменить их ввод на что-то вроде «King Standard Yes 1 1». В любом случае, извините за этот быстрый вопрос, но это основные проблемы, с которыми я сталкиваюсь.

1 Ответ

0 голосов
/ 19 октября 2018

Вам нужно вызвать функцию и присвоить эти переменные до , вы можете запросить их в своем выражении if.

Вот упрощенный пример:

def foo():
    # These variables only exist inside the function
    one = 1
    two = 2
    three = 3

    # This doesn't cause them to exist outside of the function; it "gives them"
    # as a result of calling the function later
    return one, two, three

# a, b, and c don't exist yet so I can't use them in an if statement here

# This is where we run the code contained in the function foo and bind the
# returned values to variables (they can be named differently, here we use a,
# b, and c)
a, b, c = foo()

# a, b, and c now exist as variables in the main program and they hold the values
# that were returned from the function. Now we can use them in an `if` statement, e.g.
if a or b or c:
    print('Success')
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...