'else if' 的正确语法是什么?

2022-01-31 00:00:00 python python-3.x

问题描述

我是一名新的 Python 程序员,正在从 2.6.4 飞跃到 3.1.1.在我尝试使用else if"语句之前,一切都很好.解释器在else if"中的if"之后给了我一个语法错误,原因我似乎无法弄清楚.

I'm a new Python programmer who is making the leap from 2.6.4 to 3.1.1. Everything has gone fine until I tried to use the 'else if' statement. The interpreter gives me a syntax error after the 'if' in 'else if' for a reason I can't seem to figure out.

def function(a):
    if a == '1':
        print ('1a')
    else if a == '2'
        print ('2a')
    else print ('3a')

function(input('input:'))

我可能遗漏了一些非常简单的东西;但是,我自己无法找到答案.

I'm probably missing something very simple; however, I haven't been able to find the answer on my own.


解决方案

在python中else if"拼写为elif".
此外,您需要在 elifelse 之后使用冒号.

In python "else if" is spelled "elif".
Also, you need a colon after the elif and the else.

简单问题的简单答案.当我第一次开始时(在过去几周内),我遇到了同样的问题.

Simple answer to a simple question. I had the same problem, when I first started (in the last couple of weeks).

所以你的代码应该是:

def function(a):
    if a == '1':
        print('1a')
    elif a == '2':
        print('2a')
    else:
        print('3a')

function(input('input:'))

相关文章