Python添加If语句答案

时间:2020-03-18 21:08:01

标签: python-3.x

我正在学习python并被卡在if语句中。如果我对所有3个问题输入“是”,我将尝试总计输入语句的答案,但我得到的是“是”,而不是0.60。下面的代码:

Question_1=input("Did you look at the OCC strategy in the line chart? ")
if Question_1=="Yes":
    print (0.2)
else:
    print (0) 

Question_2=input("Are you trading in the same direction as the 20 day moving average? ")
if Question_2=="Yes":
    print (0.2)
else:
    print (0) 

Question_3=input("Are you trading in the same direction as the 50 day moving average? ")
if Question_3=="Yes":
    print(0.2)
else:
    print(0) 

Total=(Question_1 + Question_2+Question_3)
print(Total)

1 个答案:

答案 0 :(得分:1)

这是一个可能的解决方案:

question_1 = input("Did you look at the OCC strategy in the line chart? ")
result_1 = 0
if question_1.lower().strip()=="yes":
    result_1 = 0.2

question_2 = input("Are you trading in the same direction as the 20 day moving average? ")
result_2 = 0
if question_2.lower().strip()=="yes":
    result_2 = 0.2

question_3 = input("Are you trading in the same direction as the 50 day moving average? ")
result_3 = 0
if question_3.lower().strip()=="yes":
    result_3 = 0.2

total = result_1 + result_2 + result_3
print(total)

主要问题是,您仅打印结果值,而不将结果存储在变量中,并且总共只打印了question_x的内容(用户输入的内容)。

我解决了这个问题,也删除了else_presset_result_x的值设置为0。

作为补充,我使用.lower()(使文本大写)和.strip()(以消除开头/结尾的多余空格)来确保用户插入空格还是使用YES /是/等等在任何情况下都可以使用。

在编写变量名时,也请尝试使用Python style guide,这将使您的代码更易被他人阅读,并且使用Python语言。