代码之家  ›  专栏  ›  技术社区  ›  Cheryl Lamb

为什么“B”不等于“B”?

  •  1
  • Cheryl Lamb  · 技术社区  · 7 年前

    我正在用python编写一个小程序,它应该以给定问题、答案的格式读取文本文件中的问题,并检查用户是否输入了正确的答案。下面是我为此编写的代码

    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”,但由于某种原因,python不执行下面的if语句,即使条件似乎是真的。条件表明userAnswer(这是存储用户输入的地方)等于变量x语句“You got that right should print”但这并没有发生,该语句的计算结果似乎为false,因为如果我在下面放一个else语句,它会将else语句计算为true并执行下面的代码。如果有人能帮我解决这个问题,我将非常感激。

    编辑:我正在编辑,因为这个问题被标记为可能的重复,我不认为它是重复的,因为类似的问题问为什么readline()没有读取空行,我的问题是为什么“B”似乎不等于“B”(问题是我不知道print()没有告诉你变量的确切内容,多亏了一条评论和我选择的最有帮助的答案,我学会了打印(repr()),它基本上解决了我的问题)。

    1 回复  |  直到 7 年前
        1
  •  3
  •   Personman    7 年前

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

    x = file.readline().strip()