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

标签 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”,但由于某种原因,即使条件似乎为真,Python也不会执行下面的if语句。条件表明userAnswer(存储用户输入的位置)等于变量x语句“你有权利应该打印”但是这并没有发生,并且该语句似乎评估为 false,因为如果我在其下面放置 else 语句,它会将 else 语句评估为 true 并执行其下的代码。我会如果有人能帮我解决这个问题,我真的很感激。

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

最佳答案

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

x = file.readline().strip()

关于python - 为什么 "B"不等于 "B"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48813300/

相关文章:

Python Spacy 初学者 : similarities function

python - 如何在Python中使用while循环模拟玩家之间的回合

java - 不带括号的嵌套 if 语句

python - 从 xpath 中删除信息?

java - Eclipse:内联断点

.net - 使用 Windows 调试工具调试 .NET 2.0 Winforms 应用程序

android - 服务断点不起作用

if-statement - 如何在 if 语句中使用 expr?

C if语句字符串条件

python - 如何仅通过相互比较来对图像进行排名?