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

2024-10-02 06:30:11 发布

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

我刚开始用python,这是我第一个程序的一部分。结尾的if语句总是打印“Please try again”,即使字符串是相同的,并且应该输出“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')

即使当correctans和userans完全相等时,它仍然打印,请在打印完成后再试一次


Tags: oftheinifanswersfailstripquestion
1条回答
网友
1楼 · 发布于 2024-10-02 06:30:11

您的.strip()调用返回字符串的剥离版本,但您不会将它们赋给任何对象

你可以试试这个

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

相关问题 更多 >

    热门问题