条件语句无法显示两个字符串是否相等。 (基本python)

时间:2019-04-04 21:24:15

标签: python

我刚开始使用python,这是我的第一个程序的一部分。即使字符串相同,结尾处的if语句也始终显示“请重试”,并应输出“ Well done”。

我添加了print(usranswer) print(correctans)以确保两个字符串相等,我也添加了usranswer.strip() correctans.strip()以删除任何不存在的空格,并且代码仍未输出正确的结果

任何其他建议都会有所帮助,谢谢。

fail = 0
Qnumber = 1

while fail != 2:

    import random

    q = random.randint(1,5)

    with open("answers.txt", "r") as answers:
        for _ in range(q):
            answer = answers.readline()

    with open("questions.txt", "r") as initials:
        for _ in range(q):
            question = initials.readline()

    print("question number")
    print(str(Qnumber))

    print('Please guess the name of this song, the name of the artist and the first letter in each word of the song title are below')

    print(question)

    usranswer = str(input())
    correctans = str(answer)

    usranswer.strip()
    correctans.strip()

    print(usranswer)
    print(correctans)

    if correctans == usranswer:
        print('Well done')
        score = score + 3
    else:
        fail = fail + 1
        print('Please try again')

即使正确答案和用户答案完全相同,它仍然会打印。请在应打印效果良好时重试

1 个答案:

答案 0 :(得分:1)

您的.strip()调用返回字符串的剥离版本,但您没有将它们分配给任何内容

您可以尝试

usranswer = input().strip()
correctans = answer.strip()