【问题标题】:Having Trouble With Discount Calculator折扣计算器有问题
【发布时间】:2023-03-08 05:25:01
【问题描述】:

无法理解我的代码有什么问题。无论student_status 的输入如何,它都会不断打印出additional_discount 值。 seen here is the code

def discount(x):
    return x * .9

def additional_discount(x):
    return discount(x) * .95

og_price = float(input("Please enter your current price in dolalrs: "))
student_status = str(input("Are you a student? "))

if student_status == "Yes" or "yes"
    print("Your price is ", additional_discount(og_price))
elif student_status == "No" or "no":
    print("Your price is ", discount(og_price))
else:
    print("I'm sorry, that is an invalid response")

谢谢!

【问题讨论】:

  • Stackoverflow 鼓励包含代码而不是代码链接,以便其他人可以轻松进行实验。
  • 您的问题是您错误地将一个值与多个值进行比较(即 student_status == "Yes" 或 "yes" 不正确)。如果 student_status == "YES" 或 student_status == "yes" 则使用。或者更简单地说:如果 student_status.lower() == "yes"
  • 快速浏览了您的代码后,您只指定了 or 语句的一半 - “or ‘yes’’而不是 or x == ‘yes’。 Just or ‘yes’ 将始终评估为 true。

标签: python if-statement


【解决方案1】:

你应该改变你的 if 条件:

if student_status in ['Yes', 'yes']:
  do something
elif student_status in ['No', 'no']:
  do

您使用的语句是if student_status == 'Yes' or 'yes'。这意味着student_status == 'Yes''yes''yes' 的布尔值是 True,因此条件始终成立。

python对象的布尔值可以参考here

【讨论】:

  • 感谢您的好评。我还不知道这些类,但想问为什么“是”的布尔值是 true。是不是因为一切都有一个默认值 true 除非它违背了指定的条件?
  • 字符串对象为真,除非它是空字符串''
猜你喜欢
  • 2020-03-13
  • 1970-01-01
  • 2021-11-05
  • 2016-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多