为什么" B"不等于" B"?

时间:2018-02-15 17:43:00

标签: python debugging if-statement logic

我在python中创建了一个小程序,它应该以文本文件的形式读取问题,回答ABCD,并检查用户是否输入了正确的答案。下面是我为此做的代码

import time

file = open("Questions.txt", "r")


def askQuestion():
    print(file.readline())
    for counter in range(4):
        print(file.readline())
    x = file.readline()
    userAnswer = input("Please input a letter that corresponds to the correct answer")
    print("The answer is", userAnswer)
    print("The X is", x)
    if userAnswer.upper() == x:
        print("You got that right")


for counter in range(10):
    time.sleep(1)
    askQuestion()


file.close()

这里是一个带有问题和答案的文本文件,事先我只是想说我不确定这是不是我应该如何格式化文件中的文本所以如果它不是,我很抱歉在堆栈溢出时正确的方法。

1) What was the name of the atomic bomb dropped on Hiroshima in 1945?
A)Fat Man
B)Little Boy
C)Annihilator
D)Heisenberg
B
2)How many stars is there on the American Flag?
A)48
B)47
C)50
D)52
C
3)How many countries is there in Europe?
A)52
B)38
C)12
D)28
D
4)What is the capital city of Poland?
A)Warsaw
B)Krakow
C)Kijew
D)Moscow
A
5)What are the colors on the polish flag?
A)RED-WHITE
B)WHITE-RED
C)WHITE-GREEN
D)YELLOW-BLUE
B
6)What does 2+2*2 evaluate to?
A)8
B)10
C)6
D)20
C
7)What year do we have?
A)3920
B)120
C)20018
D)2018
D
8)When did WW2 end?
A)1945
B)1919
C)1905
D)1834
A
9)When was Python 3 realesed?
A)2000
B)2012
C)2010
D)2014
C
10)Who is the president of USA?
A)Micheele Obama
B)Barack Obama
C)George Washington
D)Donald Trump
D

我的问题是,让我们对第一个问题说答案是" B"保存在变量x中(为了确保x实际上是" B"我在代码中看到它打印出来。然后我打印了用户输入,也是" B&#34 ;,但是对于某些原因python不执行下面的if语句,即使条件似乎为True。条件指出userAnswer(存储用户输入的位置)等于变量x语句"你得到了right应该打印"然而这并没有发生,并且语句似乎评估为false,因为如果我在它下面放一个else语句,它会将else语句计算为true并执行它下面的代码。我真的很感激如果任何人都可以帮我解决这个问题。

编辑:我正在编辑,因为问题被标记为可能重复,我不认为它是重复的,因为似乎类似的问题是关于为什么readline()没有读取空行,我的问题是为什么" B"似乎不等于" B" (问题是我不知道print()并没有准确地告诉你变量是什么,这要归功于我选择的评论和答案,因为我学到了关于print的最有帮助(repr()这基本上解决了我的问题)。

1 个答案:

答案 0 :(得分:3)

您将换行符包含在从文件中读取的字符串中。你想要

x = file.readline().strip()