SyntaxError无效语法python

2024-03-28 08:46:30 发布

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

def convert():
    choice = input("Wybierz kierunek wymiany waluty \n1) PLN>USD \n2) USD>PLN \n3) PLN>EURO \n4) EURO>PLN")
    print(choice)

    if choice == 1:
        print ("choice=1")

    else choice == 2:
        print("Choice=2")

    else choice == 3:
        print("Choice=3")

    else choice == 4:
        print("Choice=4")

convert()

为什么会有SyntaxError: invalid syntax


Tags: convertinputdefelseusdprintchoiceeuro
3条回答

而修复代码的传统方法是将所有else替换为elif,如下所示:

def convert():
    choice = input("Wybierz kierunek wymiany waluty \n1) PLN>USD \n2) USD>PLN \n3) PLN>EURO \n4) EURO>PLN")
    print(choice)
    if choice == "1":
        print("choice=1")
    elif choice == "2":
        print("Choice=2")
    elif choice == "3":
        print("Choice=3")
    elif choice == "4":
        print("Choice=4")

convert()

然而,对于您的特殊情况,即使不需要其他。你可以选择:

def convert():
        choice = input("Wybierz kierunek wymiany waluty \n1) PLN>USD \n2) USD>PLN \n3) PLN>EURO \n4) EURO>PLN")
        print(choice)
        print("choice=", choice)

convert()

python中有这样三个组件:ifelifelse。只有一个else,因为,只要想想它的实际含义:只有在所有其他条件都没有通过的情况下才做一些事情

def convert():
    choice = input("Wybierz kierunek wymiany waluty \n1) PLN>USD \n2) USD>PLN \n3) PLN>EURO \n4) EURO>PLN")
    print(choice)

    if choice == 1:
        print ("choice=1")

    elif choice == 2:
        print("Choice=2")

    elif choice == 3:
        print("Choice=3")

    elif choice == 4:
        print("Choice=4")

convert()

您可能是指elif-python中没有else <cond>

def convert():
    choice = input("Wybierz kierunek wymiany waluty \n1) PLN>USD \n2) USD>PLN \n3) PLN>EURO \n4) EURO>PLN")
    print(choice)
    if choice == "1":
        print("choice=1")
    elif choice == "2":
        print("Choice=2")
    elif choice == "3":
        print("Choice=3")
    elif choice == "4":
        print("Choice=4")

convert()

有关如何使用if-elif-else的信息,请参见docs

相关问题 更多 >