Я не могу понять, как добавить эти элементы, сложность цикла sum / while? - PullRequest
0 голосов
/ 08 мая 2019

По сути, я пытаюсь получить приблизительную сумму здесь на основе заданных входных данных.Я не знаю, почему я не могу получить его, чтобы добавить, несмотря на использование суммы.Я попытался поместить все это в цикл while и определить его как sumTotal, и это ничего не дало.В конечном итоге я хочу, чтобы он отображал итоговое значение: «Это ваш недисконтированный итог: (введите итоговое значение здесь).

В настоящее время он запускается, и общее значение отображается как AAyes. Это смешно, но не то, что яэто нужно сделать. Есть предложения?

holidayInn = 120
showBoat = 230
mollyPitcher = 180
rideshare = 20
A = 180
B = 230
C = 120

# Declare variables
rooms = 0
hotel = 0
rideshare = "yes"
MOLLYP = "A" 
SHOWB = "B"
HOLIDAY = "C"


# Greet the user
print("Hello, and welcome to our program!" + \
      " Follow the prompts below to begin" + \
      " planning your vacation.")

# Ask about the number of guests
party = int(input("With how many people will you be traveling?" + \
                  "(Larger groups may qualify for a discount!): "))

# Display discount
if 5 < party <= 8:
    print("Cool! Your selection qualifies for a 10% discount" + \
          "that will be applied at the end.")
elif party >= 9:
    print("Cool! Your selection qualifies for a 30% discount" + \
          "that will be applied at the end.")
elif party < 5:
    print("Sorry, your purchase does not qualify for a discount.")

# -----------------------------------------------------------------

# Ask about the number of rooms
rooms = int(input("How many rooms will you be booking? " + \
                  "(please limit to 10 per transaction): ") )

# Ask about the number of nights
nights = int(input("For how many nights will you be staying? "))

# Display Hotels
print("Here are our available hotels:")
print("A. Holiday Inn: $120/night")
print("B. Showboat: $230/night")
print("C. Molly Pitcher Inn: $180/night")

# Ask which hotel
select1 = input("At which hotel will you be staying? " + \
                 "(Enter the capital letter that corresponds.)")

# Check validity of first selection
if select1 != MOLLYP and select1 != SHOWB and select1 != HOLIDAY:
    print("Error: Enter your selection as a capital letter.")

# Ask about ridesharing
select2 = input("Will you be ultizing our ride-sharing services on your travels?" + \
                 " (If so, 'yes' or hit any key for no.) ")
while select2 == "yes":
    print("This adds a $20 additional cost per day.")
    break
sum = ((select1 * rooms * nights) + (nights * rideshare))
print(format(sum))

Ответы [ 6 ]

1 голос
/ 08 мая 2019

, поэтому вход для select1 может быть либо A B, либо C, которые все объявлены как константы выше с числами. Это часть того, что смущает меня.

select1 - это строка со значением "A", "B" или "C". У вас также есть переменные с именами A, B и C. Между этими двумя вещами нет никакой связи. select1 магическим образом не принимает значение соответствующей буквенной переменной.

Если вы хотите сделать это, используйте словарь:

hotels = {
    "A": 120,  # Holiday Inn
    "B": 230,  # Showboat
    "C": 180   # Molly Pitcher Inn
}

choice = input("Enter hotel letter: ")
if choice in hotels:
    hotel_cost = hotels["choice"]
else:
    print("I don't recognize that hotel")

Или, поскольку есть только три варианта, его можно использовать так же просто, если / else:

choice = input("Enter hotel letter: ")
if choice == "A":
    hotel_cost = 120
elif choice == "B":
    hotel_cost = 230
elif choice == "C":
    hotel_cost = 180
else:
    print("I don't recognize that hotel")
0 голосов
/ 08 мая 2019

Переменная select1 содержит строку. Когда вы умножаете строку на целое число n, вы повторяете строку n раз. Пример ("A" * 4 = "AAAA").

Вам необходимо сопоставить введенную строку с соответствующей переменной (A, B или C). Рекомендую создать словарь с ценами отеля:

#Get rid of these:
#A = 180
#B = 230
#C = 120

#Use this instead:
hotel_prices = {
    'A': 180,
    'B': 230,
    'C': 120
}

После того, как вы подтвердите ввод, вы можете получить цену int, используя словарь:

# Check validity of first selection
if select1 != MOLLYP and select1 != SHOWB and select1 != HOLIDAY:
    print("Error: Enter your selection as a capital letter.")

select1 = hotel_prices[select1]

У вас та же проблема с переменной rideshare. Сначала вы задаете для него значение int (rideshare = 20), а затем меняете его на строку (rideshare = 'yes'). Избавьтесь от второго объявления, если не будете его использовать. Вы можете проверить опцию rideshare, используя оператор if:

if select2 == "yes":
    print("This adds a $20 additional cost per day.")
else:
    rideshare = 0

Есть и другие улучшения, которые можно сделать здесь, но, надеюсь, это решит проблему, с которой вы столкнулись. Вот полный код:

#holidayInn = 120
#showBoat = 230
#mollyPitcher = 180
#rideshare = 20
#Get rid of these
#A = 180
#B = 230
#C = 120
hotel_prices = {
    'A': 180,
    'B': 230,
    'C': 120
}

# Declare variables
rooms = 0
hotel = 0
#rideshare = "yes"
MOLLYP = "A" 
SHOWB = "B"
HOLIDAY = "C"


# Greet the user
print("Hello, and welcome to our program!" + \
      " Follow the prompts below to begin" + \
      " planning your vacation.")

# Ask about the number of guests
party = int(input("With how many people will you be traveling?" + \
                  "(Larger groups may qualify for a discount!): "))

# Display discount
if 5 < party <= 8:
    print("Cool! Your selection qualifies for a 10% discount" + \
          "that will be applied at the end.")
elif party >= 9:
    print("Cool! Your selection qualifies for a 30% discount" + \
          "that will be applied at the end.")
elif party < 5:
    print("Sorry, your purchase does not qualify for a discount.")

# -----------------------------------------------------------------

# Ask about the number of rooms
rooms = int(input("How many rooms will you be booking? " + \
                  "(please limit to 10 per transaction): ") )

# Ask about the number of nights
nights = int(input("For how many nights will you be staying? "))

# Display Hotels
print("Here are our available hotels:")
print("A. Holiday Inn: $120/night")
print("B. Showboat: $230/night")
print("C. Molly Pitcher Inn: $180/night")

# Ask which hotel
select1 = input("At which hotel will you be staying? " + \
                 "(Enter the capital letter that corresponds.)")

# Check validity of first selection
if select1 != MOLLYP and select1 != SHOWB and select1 != HOLIDAY:
    print("Error: Enter your selection as a capital letter.")

select1 = hotel_prices[select1]

# Ask about ridesharing
select2 = input("Will you be ultizing our ride-sharing services on your travels?" + \
                 " (If so, 'yes' or hit any key for no.) ")
# While statement is not necessary here:
#while select2 == "yes":
#    print("This adds a $20 additional cost per day.")
#    break
#
# Use an if statement:
if select2 == "yes":
    print("This adds a $20 additional cost per day.")
else:
    rideshare = 0

sum = ((select1 * rooms * nights) + (nights * rideshare))
print(format(sum))
0 голосов
/ 08 мая 2019

Основной проблемой, с которой вы сталкиваетесь, является ввод, который вы получаете от пользователя, и то, как вы его обрабатываете.

В этой строке:

# Ask which hotel
select1 = input("At which hotel will you be staying? " + \
                 "(Enter the capital letter that corresponds.)")

Вы являетесьпопросить пользователя ввести заглавную букву.Затем внизу:

sum = ((select1 * rooms * nights) + (nights * rideshare))

Вы берете переменную, select1, которая равна некоторой букве, назовите ее A и умножите ее на целочисленные значения rooms и nights.Когда строка умножается на целое число c, она возвращает эту строку c раз.Вот почему вы получаете AA в начале вашего возвращения.

Именно поэтому вы получаете yes после AA.Переменная rideshare сохраняется как «да».Затем вы умножаете его на некоторое целое число, хранящееся в nights.Если вы вернетесь назад и введете 2 для этого значения, вы увидите, что оно возвращает yesyes в конце вашего вывода.

Я бы рекомендовал хранить переменные, которые вы объявили в верхней части скрипта, всловарь для удобства чтения и полезности.Я также проверил бы, чтобы входные данные пользователя были целыми числами, когда это необходимо.Если вы хотите получить дополнительные разъяснения или хотите, чтобы я помог вам переписать код, не стесняйтесь спрашивать.

Надеюсь, это поможет вам начать работу!

0 голосов
/ 08 мая 2019

Некоторые комментарии к вашему коду:

1) select1 - это строка, поэтому вам нужно преобразовать ее на основе ответа (если select1 = 'A', то 180 ... и так далее

2) rideshare инициализируется 2x.Сначала как целое число, а затем как строка

3) используйте условие "если", если ответ на rideshare - да

  rideshare=0
  if select2 == "yes":
      print("This adds a $20 additional cost per day.")
      rideshare=20

4) Ваша плата за отель взимается за ночь и за номер.Очень дорого.Я скорее использую airbnb.

Ниже рабочий код:

#holidayInn = 120
#showBoat = 230
#mollyPitcher = 180
rideshare = 0
A = 180
B = 230
C = 120

# Declare variables
rooms = 0
hotel = 0
#rideshare = "yes"
MOLLYP = "A" 
SHOWB = "B"
HOLIDAY = "C"


# Greet the user
print("Hello, and welcome to our program!" + \
      " Follow the prompts below to begin" + \
      " planning your vacation.")

# Ask about the number of guests
party = int(input("With how many people will you be traveling?" + \
                  "(Larger groups may qualify for a discount!): "))

# Display discount
if 5 < party <= 8:
    print("Cool! Your selection qualifies for a 10% discount" + \
          "that will be applied at the end.")
elif party >= 9:
    print("Cool! Your selection qualifies for a 30% discount" + \
          "that will be applied at the end.")
elif party < 5:
    print("Sorry, your purchase does not qualify for a discount.")

# -----------------------------------------------------------------

# Ask about the number of rooms
rooms = int(input("How many rooms will you be booking? " + \
                  "(please limit to 10 per transaction): ") )

# Ask about the number of nights
nights = int(input("For how many nights will you be staying? "))

# Display Hotels
print("Here are our available hotels:")
print("A. Holiday Inn: $120/night")
print("B. Showboat: $230/night")
print("C. Molly Pitcher Inn: $180/night")

# Ask which hotel
select1 = input("At which hotel will you be staying? " + \
                 "(Enter the capital letter that corresponds.)")

# Check validity of first selection
if select1 != MOLLYP and select1 != SHOWB and select1 != HOLIDAY:
    print("Error: Enter your selection as a capital letter.")
if select1 == 'A':
    select1 = A
elif select1 == 'B':
    select1 = B
elif select1 == 'C':
    select1 = C
# Ask about ridesharing
select2 = input("Will you be ultizing our ride-sharing services on your travels?" + \
                 " (If so, 'yes' or hit any key for no.) ")
if select2 == "yes":
    print("This adds a $20 additional cost per day.")
    rideshare=20
sum1 = ((select1 * rooms * nights) + (nights * rideshare))
print(format(sum1))
0 голосов
/ 08 мая 2019

select1 и rideshare являются строками, а не числами.select1 содержит название отеля, введенное пользователем, но вместо этого вы хотите указать тариф соответствующего отеля.Вы можете использовать словарь для хранения числового тарифа для каждого отеля:

hotels = {"HOLIDAY": 180,
          "SHOWB": 230,
          "MOLLYP": 180}

А вот как вы можете получить ставку из пользовательского ввода:

while select1 not in hotels:
    # Ask which hotel
    select1 = input("At which hotel will you be staying? " + \
                     "(Enter the capital letter that corresponds.)")

rate = hotels[select1] # get rate of hotel from dictionary

Для rideshare,вам нужно установить его на 0 или 20 в зависимости от ввода пользователя:

# Ask about ridesharing
select2 = input("Will you be ultizing our ride-sharing services on your travels?" + \
                 " (If so, 'yes' or hit any key for no.) ")
if select2 == "yes":
    print("This adds a $20 additional cost per day.")
    rideshare = rideshare_rate
else: rideshare = 0

Вот рабочая реализация:

rideshare_rate = 20

# Declare variables
rooms = 0
hotel = 0
select1 = ""

hotels = {"HOLIDAY": 180,
          "SHOWB": 230,
          "MOLLYP": 180}

# Greet the user
print("Hello, and welcome to our program!" + \
      " Follow the prompts below to begin" + \
      " planning your vacation.")

# Ask about the number of guests
party = int(input("With how many people will you be traveling?" + \
                  "(Larger groups may qualify for a discount!): "))

# Display discount
if 5 < party <= 8:
    print("Cool! Your selection qualifies for a 10% discount" + \
          "that will be applied at the end.")
elif party >= 9:
    print("Cool! Your selection qualifies for a 30% discount" + \
          "that will be applied at the end.")
elif party < 5:
    print("Sorry, your purchase does not qualify for a discount.")

# -----------------------------------------------------------------

# Ask about the number of rooms
rooms = int(input("How many rooms will you be booking? " + \
                  "(please limit to 10 per transaction): ") )

# Ask about the number of nights
nights = int(input("For how many nights will you be staying? "))

# Display Hotels
print("Here are our available hotels:")
print("A. Holiday Inn: $120/night")
print("B. Showboat: $230/night")
print("C. Molly Pitcher Inn: $180/night")

while select1 not in hotels:
    # Ask which hotel
    select1 = input("At which hotel will you be staying? " + \
                     "(Enter the capital letter that corresponds.)")

rate = hotels[select1] # get rate of hotel from dictionary

# Ask about ridesharing
select2 = input("Will you be ultizing our ride-sharing services on your travels?" + \
                 " (If so, 'yes' or hit any key for no.) ")
if select2 == "yes":
    print("This adds a $20 additional cost per day.")
    rideshare = rideshare_rate
else: rideshare = 0

sum = (rooms * nights) + (nights * rideshare)
print(format(sum))
0 голосов
/ 08 мая 2019

в rideshare вы объявляете строку "да" в MOLLYP вы объявляете строку "A"

holidayInn = 120
showBoat = 230
mollyPitcher = 180
rideshare = 20
A = 180
B = 230
C = 120

# Declare variables
rooms = 0
hotel = 0
rideshare = "yes" # because of that you have yes in your result
MOLLYP = "A" # declare string A in variable MOLLYP (A in your result) 
SHOWB = "B"
HOLIDAY = "C"

вероятно, вы хотите объявить как:

rideshare = 20 # 20
MOLLYP = A  # 180
SHOWB = B  # 230
HOLIDAY = C #120
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...