python3.5中带圆括号的条目只有在两次按下Enter键时才继续

2024-04-25 10:13:50 发布

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

我试图解决一个简单的练习,以确定公式中使用的括号是否正确,但当我尝试输入这样的公式a+(b*c)-2-a时, 我得按两次回车键。这只发生在EOF块内部。 有什么问题吗?非常感谢你!你知道吗

while True:
    try:
        x = input()
        z = []
        for y in x:
            if y == '(':
                z.append(y)
            elif y == ')':
                z.append(y)
        q = ''.join(z)
        d = 0
        while d == 0:
            if q.count('()') != 0:
                q = q.replace('()', '')
            else:
                if q.count('(') >= 1 or q.count(')') >= 1:
                    print('incorrect')
                else:
                    print('correct')
            d = 1
    except:
        break

Tags: intrueforinputifcountelse括号
1条回答
网友
1楼 · 发布于 2024-04-25 10:13:50

您有两个while True循环。第一次输入while d == 0:时,括号中有一个有效的余数,表示if q.count('()') != 0:True。这个while循环随后中断,因为d被加1。但是print语句要求if q.count('()') != 0:False。因此,由于第一次while True:,您再次启动整个循环,按enter键(对于您的算法来说,这实际上是一个无效的输入),这样您就可以得到:

else:
    if q.count('(') >= 1 or q.count(')') >= 1:
        print('incorrect')
    else:
        print('correct')

相关问题 更多 >