我的Python列表代码产生的总和与预期不符。

huangapple go评论61阅读模式
英文:

My list python code is producing a sum other than what is intended. Python

问题

我正在尝试编写一个程序,该程序接受用户输入的订单并将其转换为一个列表,然后根据列表中每个单词的数量生成一个总和。然而,我的代码一直产生一个不正确的总和。例如,如果我输入“Water Nachos Water Cheeseburger”,预期总和应为24,但我的代码得出答案为39。这是为什么,以及有可能的修复方法是什么?

x = input("What are your orders?")
orders = list(x.split())
sum = 0
for i in orders:
    if i == "Nachos":
        sum += 6
    if i == "Pizza":
        sum += 6
    if i == "Water":
        sum += 4
    if i == "Cheeseburger":
        sum += 10
    else:
        sum += 5
print(sum)

我期望得到总和为24,但实际得到的总和为39。

英文:

I am trying to code a program that take user input of orders and converts it to a list that I can then produce a sum based on the number of each word in the list. However, my code keeps producing a a sum that is not correct for the provided list. For example, if I enter Water Nachos Water Cheeseburger the intended sum is 24, but my code is producing 39 as the answer. Why is this and what is a potential fix?

x = input("What are your orders?")
orders = list(x.split())
sum = 0
for i in orders:
      if i == "Nachos":
       sum+=6
      if i == "Pizza":
       sum+=6
      if i == "Water":
       sum+=4
      if i == "Cheeseburger":
       sum+=10
      else:
        sum+=5
print(sum)

I expected a sum of 24, but got a sum of 39.

答案1

得分: 1

最后的else部分仅适用于条件i == "Cheeseburger"。所以对于所有其他条件,sum+=5都会执行。
你可以使用if else if简化:

x = input("你想要点什么?")
orders = list(x.split())
sum = 0
for i in orders:
    if i == "Nachos":
        sum += 6
    elif i == "Pizza":
        sum += 6
    elif i == "Water":
        sum += 4
    elif i == "Cheeseburger":
        sum += 10
    else:
        sum += 5
print(sum)
英文:

The last else part is only for the if condition i == "Cheeseburger"
So `sum+=5 will gets executed for all the other conditions.
You can just use if else if

x = input("What are your orders?")
orders = list(x.split())
sum = 0
for i in orders:
      if i == "Nachos":
       sum+=6
      elif i == "Pizza":
       sum+=6
      elif i == "Water":
       sum+=4
      elif i == "Cheeseburger":
       sum+=10
      else:
        sum+=5
print(sum)

huangapple
  • 本文由 发表于 2023年2月8日 10:40:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/75380911.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定