【问题标题】:Why won't my python code add in my += if's? [duplicate]为什么我的 python 代码不添加到我的 += if 中? [复制]
【发布时间】:2023-02-03 20:42:39
【问题描述】:

我对编码很陌生。我似乎被困在 if/elif/else 和 += 运算符上。当我运行我的代码时,它部分起作用。我没有收到任何错误,但如果两个或一个为“Y”,它不会在我的代码中添加 Island 和 Heater。

我根据自己遇到的问题自己编造了这个。我模仿了练习题的解决方案,但没有得到相同的结果。有人可以帮我看看我做错了什么吗?

Size = int(input("What size camper do you want? Size in feet. \n"))
Island = input("Do you want and Island? y or n \n")
Heater = input("Do you want tankless water heater? y or n \n")

price = 0

if Size <= 30:
  price += 50000
elif Size <= 40:
  price += 60000
else:
  price += 80000

if Island == "Y or y":
  if Size <=30:
    price += 500
  else:
    price += 800

if Heater == "Y or y":
  if Size <=30:
    price += 1000
  else:
    price += 1500

print(f"Your total for a new camper will be ${price}!")

我尝试更改缩进,但我最初没有加热器和岛的其他选项。

【问题讨论】:

  • Island == "Y or y":并没有按照你的想法去做。
  • 作为旁注,最好尽可能发布完整包含的示例。您可以对Size 等的值进行硬编码,而不是我们猜测输入...

标签: python algorithm operators addition


【解决方案1】:

问题是if Island == "Y or y": 检查输入是否确实是字符串"Y or y"。请改用if Island.lower() == "y":。另一个选项是if Island in ("Y", "y"):

【讨论】:

  • 谢谢你的帮助。我还没有了解这些东西,但它确实解决了我遇到的问题。祈祷我能弄清楚这些东西。
猜你喜欢
  • 2021-10-28
  • 1970-01-01
  • 2021-01-12
  • 2014-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-20
  • 1970-01-01
相关资源
最近更新 更多