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

2024-09-20 03:44:21 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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())的最有帮助的答案,它基本上解决了我的问题)。你知道吗


Tags: ofthe答案代码inreadlinethatis
1条回答
网友
1楼 · 发布于 2024-09-20 03:44:21

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

x = file.readline().strip()

相关问题 更多 >