Python 3.x Python Add If语句回答

Python 3.x Python Add If语句回答,python-3.x,Python 3.x,我正在学习python,但被if语句卡住了。如果我对所有3个问题都输入Yes,我会尝试对输入语句的答案进行合计,但结果是yesyes,而不是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

我正在学习python,但被if语句卡住了。如果我对所有3个问题都输入Yes,我会尝试对输入语句的答案进行合计,但结果是yesyes,而不是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)

下面是一个可能的解决方案:

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)
主要的问题是,您只是打印结果值,而不是将结果存储在变量中,总体而言,您只打印问题x(用户输入)的内容

我解决了这个问题,还删除了将result_x的值设置为0的else pre_

作为补充,我使用了.lower()和.strip()(删除开头/结尾的多余空格),以确保如果用户插入空格或使用YES/YES/etc,在任何情况下都能正常工作


当您编写变量名时,请尝试使用它,这将使您的代码更容易被其他人阅读,更具python风格。

Question\u 1
Question\u 2
Question\u 3
都是字符串,因此对它们使用
+
将导致字符串串联。假设
Question\u 1
“是”
问题2
“是”
问题3
“是”
(您已经专门检查了这些值)很难理解为什么
“是”
对于
问题1+问题2+问题3将是一个意外的输出。您需要将每个问题的分数存储在某个地方或保留一个运行总数<代码>总计=0
。然后
如果问题1==“是”:总计+=0.2
等。非常感谢您的帮助。我一定会阅读Python风格指南。