Using elif statement Part 1

Lesson Details:
June 29, 2020


I: Introduction

Python is a high-level, general purpose programming language for writing different kinds of programs. It features simple, easy to learn syntax and uses English keywords frequently. Python was created by Guido van Rossum in 1991. It is an open source language and has a huge support community which makes it easy to find solutions to any problems encountered while learning Python.

The code snippet below shows python code for the factorial function:

def fact(n):

if n == 0:

return 1

else:

return n * fact(n-1)

print(fact(5)) #prints 120

II: Body

The above Python code defines the function fact(). Function is a unit of program that does one specific task. The interpreter reads this code and follows the instructions step by step. First, it executes the if statement. If the condition is true, then it executes the statements within the block {}. The body of the if statement contains the return statement which returns the value of n * fact(n-1). This value is printed on the screen by the print() function. The value printed on the screen is 120.

The elif statement allows us to add conditions after checking for a specific condition. Here we check if n is equal to zero and if so we return 1, otherwise we increment n by one and recheck whether it is equal to zero. We keep doing this until we reach a number which is not equal to zero. For example:

def fact(n):

if n == 0:

return 1

elif n == 1:

return 1

elif n == 2:

return 2

elif n == 3:

return 6

elif n == 4:

return 24

elif n == 5:

return 120





loader
Course content