【问题标题】:I cannot figure out how to add these elements, sum/while loop difficulty?我不知道如何添加这些元素,sum/while 循环难度?
【发布时间】:2019-05-08 18:33:04
【问题描述】:

基本上,我试图根据给定的输入在这里得到一个粗略的总数。我不知道为什么我不能让它添加,尽管使用 sum。我尝试将整个事情放入一个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))

【问题讨论】:

  • 你在循环中放了什么? whilebreak 不在条件中与 if 相同。该循环只会运行一次。
  • sum = ((select1 * rooms * nights) + (nights * rideshare)) 你有 strint 变量在这里混合在一起,所以这不会给你你正在寻找的值。考虑使用调试器单步执行代码并验证所有类型和值在每一行执行时是否符合预期。
  • select1rideshare 是字符串。将一个字符串乘以一个数字只会重复该字符串多次,即"hello" * 2 得到hellohello
  • 查看这个可爱的debug 博客寻求帮助。显示变量值和类型的基本print 语句将突出显示问题。
  • 所以 select1 的输入可以是 A B 或 C,它们都被声明为上面带有数字的常量。这是让我感到困惑的部分原因。然后rideshare也被声明为一个常数。我该怎么做才能修复它们?

标签: python variables while-loop sum constants


【解决方案1】:

所以 select1 的输入可以是 A B 或 C,它们都被声明为上面带有数字的常量。这是让我感到困惑的部分原因。

select1 是一个值为"A""B""C" 的字符串。您还有名为ABC 的变量。这两件事之间没有任何联系。 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")

或者,因为只有三个选项,所以使用 if/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")

【讨论】:

    【解决方案2】:

    在拼车中,您声明字符串“是” 在 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
    

    【讨论】:

      【解决方案3】:

      select1rideshare 是字符串,而不是数字。 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))
      

      【讨论】:

        【解决方案4】:

        您的代码中有一些 cmets:

        1) select1 是一个字符串,因此您需要根据响应对其进行转换(如果 select1='A' 则为 180... 以此类推

        2) Rideshare 被初始化 2x。首先是整数,然后是字符串

        3) 当拼车响应为“是”时,使用“如果条件”

          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))
        

        【讨论】:

          【解决方案5】:

          您遇到的主要问题是您从用户那里收到的输入以及您如何处理它。

          在这一行:

          # 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 并将其乘以 roomsnights 的整数值。当字符串乘以整数c 时,它会返回该字符串c 次。这就是您在退货开始时收到AA 的原因。

          这也是您在AA 之后收到yes 的原因。变量rideshare 存储为“是”。然后将它乘以存储在nights 中的某个整数。如果您返回并为该值输入 2,您会看到它在输出末尾返回 yesyes

          为了可读性和实用性,我建议将您在脚本顶部声明的变量存储到字典中。我还会检查以确保用户的输入在需要时是整数。如果您需要更多说明,或者希望我帮助您进一步重写代码,请随时提出。

          希望这可以帮助您入门!

          【讨论】:

            【解决方案6】:

            变量 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')。摆脱第二个声明,如果你不会使用它。您可以使用 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))
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2015-07-13
              • 1970-01-01
              • 2019-07-05
              • 2022-12-13
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多