为什么说粗体的 = 是无效语法?

Why is it saying that the = in bold is an invalid syntax?

print('Select operation')
print('Choose from:')
print('+')
print('-')
print('*')
print('/')

choice=input('Enter choice (+,-,*,/):')

num1=int(input('Enter first number:'))
num2=int(input('Enter second number:'))

if choice== '+':
print(num1,'+',num1,'=', (num1+num2))
while restart **=** input('Do you want to restart the calculator y/n'):
    if restart == 'y':t
        print('restart')
        else restart == 'n':
            print('Thanks for using my program')
            break

 elif choice== '-':
print(num1,'-',num2,'=', (num1-num2))

elif choice== '*':
print(num1,'*',num2,'=', (num1*num2))

elif choice== '/':
print(num1,'/',num2,'=',(num1/num2))

else:
print('Invalid input')

粗体=有什么问题?我不明白它有什么问题?有人请回答我的问题。

谢谢, 夏洛特

您尝试过将赋值语句用作布尔值;这在几个方面都失败了。最重要的是,您将 restart 逻辑分布在多行代码中,并混淆了解析器。

您可能想要这样的东西:

restart = input('Do you want to restart the calculator y/n')
while restart.lower() == 'y':
    ...
    restart = input('Do you want to restart the calculator y/n')

这里有多个问题:

  1. input到变量的赋值不能在while循环中检查,你应该把它拆分成赋值并检查。

  2. else 不能包含条件

  3. 你在打印结果时也有错误 - 你打印了两次 num1

  4. 缩进在 Python 中是有意义的 - 请确保 post 下次正确缩进

以上问题的修复:

def calc():
    print('Select operation')
    print('Choose from:')
    print('+')
    print('-')
    print('*')
    print('/')

    choice=input('Enter choice (+,-,*,/):')

    num1=int(input('Enter first number:'))
    num2=int(input('Enter second number:'))
    if choice == '+':
        print("{}+{}={}".format(num1, num2, num1+num2))

    elif choice == '-':
        print("{}-{}={}".format(num1, num2, num1-num2))

    elif choice == '*':
        print("{}*{}={}".format(num1, num2, num1*num2))

    elif choice == '/':
        print("{}/{}={}".format(num1, num2, num1/num2))
    else:
        print('Invalid input')


if __name__ == '__main__':
    restart = 'y'
    while restart:
        if restart == 'y':
            print('restart')
            calc()
            restart = input('Do you want to restart the calculator y/n')    
        elif restart == 'n':
            print('Thanks for using my program')
            break