Syntax. If the Boolean expression evaluates to true, then the if block will be executed, otherwise, the else block will be executed. C programming language assumes any non-zero and non-null values as true, and if it is either zero or null, then it is assumed as false value.
The elif is short for else if. It allows us to check for multiple expressions. If the condition for if is False , it checks the condition of the next elif block and so on. If all the conditions are False , the body of else is executed.
elseif , as its name suggests, is a combination of if and else . Like else , it extends an if statement to execute a different statement in case the original if expression evaluates to false .
If / Else / Else If conditional statements are conditional statements that have more than one condition. If the first condition is false, only then will the second condition will be checked. If the second one is also false, then the app will default to else or it will do nothing. Check out the diagram below.
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).
So your code should read:
def function(a):
if a == '1':
print('1a')
elif a == '2':
print('2a')
else:
print('3a')
function(input('input:'))
Do you mean elif
?
def function(a):
if a == '1':
print ('1a')
elif a == '2':
print ('2a')
else:
print ('3a')
since olden times, the correct syntax for if/else if
in Python is elif
. By the way, you can use dictionary if you have alot of if/else
.eg
d={"1":"1a","2":"2a"}
if not a in d: print("3a")
else: print (d[a])
For msw, example of executing functions using dictionary.
def print_one(arg=None):
print "one"
def print_two(num):
print "two %s" % num
execfunctions = { 1 : (print_one, ['**arg'] ) , 2 : (print_two , ['**arg'] )}
try:
execfunctions[1][0]()
except KeyError,e:
print "Invalid option: ",e
try:
execfunctions[2][0]("test")
except KeyError,e:
print "Invalid option: ",e
else:
sys.exit()
Here is a little refactoring of your function (it does not use "else" or "elif"):
def function(a):
if a not in (1, 2):
a = 3
print(str(a) + "a")
@ghostdog74: Python 3 requires parentheses for "print".
def function(a):
if a == '1':
print ('1a')
else if a == '2'
print ('2a')
else print ('3a')
Should be corrected to:
def function(a):
if a == '1':
print('1a')
elif a == '2':
print('2a')
else:
print('3a')
As you can see, else if should be changed to elif, there should be colons after '2' and else, there should be a new line after the else statement, and close the space between print and the parentheses.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With