Python Keywords and Identifiers
Python Keywords
Keywords are predefined, reserved words used in Python programming that
have special meanings to the compiler.
We cannot use a keyword as a variable name, function name, or any other
identifier. They are used to define the syntax and structure of the Python
language.
All the keywords except True, False and None are in lowercase and they must
be written as they are. The list of all the keywords is given below.
Python
Keywords List
False await else import pass
None break except in raise
True class finally is return
and continue for lambda try
as def from nonlocal while
asser
del global not with
t
asyn
elif if or yield
c
Python Identifiers
Identifiers are the name given to variables, classes, methods, etc. For example,
language = 'Python'
Here, language is a variable (an identifier) which holds the value 'Python'.
We cannot use keywords as variable names as they are reserved names that are
built-in to Python. For example,
continue = 'Python'
The above code is wrong because we have used continue as a variable name. To
learn more about variables, visit Python Variables.
Rules for Naming an Identifier
Identifiers cannot be a keyword.
Identifiers are case-sensitive.
It can have a sequence of letters and digits. However, it must begin with a letter
or _. The first letter of an identifier cannot be a digit.
It's a convention to start an identifier with a letter rather _.
Whitespaces are not allowed.
We cannot use special symbols like !, @, #, $, and so on.
Some Valid and Invalid Identifiers in Python
Valid Identifiers Invalid Identifiers
score @core
return_value return
highest_score highest score
name1 1name
convert_to_string convert to_string
Things to Remember
Python is a case-sensitive language. This means, Variable and variable are not
the same.
Always give the identifiers a name that makes sense. While c = 10 is a valid
name, writing count = 10 would make more sense, and it would be easier to
figure out what it represents when you look at your code after a long gap.
Multiple words can be separated using an underscore,
like this_is_a_long_variable.
Python Operators
Operators are special symbols that perform operations on variables and values
print(5 + 6) # 11
11
Types of Python Operators
Here's a list of different types of Python operators that we will learn in this
tutorial.
1. Arithmetic operators
2. Assignment Operators
3. Comparison Operators
4. Logical Operators
5. Bitwise Operators
6. Special Operators
1. Python Arithmetic Operators
Arithmetic operators are used to perform mathematical operations like addition,
subtraction, multiplication, etc. For example,
sub = 10 - 5 # 5
Here, - is an arithmetic operator that subtracts two values or variables.
Operator Operation Example
+ Addition 5+2=7
- Subtraction 4-2=2
* Multiplication 2*3=6
/ Division 4/2=2
// Floor Division 10 // 3 = 3
% Modulo 5%2=1
** Power 4 ** 2 = 16
Example 1: Arithmetic Operators in Python
a=7
b=2
# addition
print ('Sum: ', a + b)
# subtraction
print ('Subtraction: ', a - b)
# multiplication
print ('Multiplication: ', a * b)
# division
print ('Division: ', a / b)
# floor division
print ('Floor Division: ', a // b)
# modulo
print ('Modulo: ', a % b)
# a to the power b
print ('Power: ', a ** b)
Output
Sum: 9
Subtraction: 5
Multiplication: 14
Division: 3.5
Floor Division: 3
Modulo: 1
Power: 49
In the above example, we have used multiple arithmetic operators,
+ to add a and b
- to subtract b from a
* to multiply a and b
/ to divide a by b
// to floor divide a by b
% to get the remainder
** to get a to the power b
2. Python Assignment Operators
Assignment operators are used to assign values to variables. For example,
# assign 5 to x
var x = 5
Here, = is an assignment operator that assigns 5 to x.
Here's a list of different assignment operators available in Python.
Operator Name Example
= Assignment Operator a=7
+= Addition Assignment a += 1 # a = a + 1
-= Subtraction Assignment a -= 3 # a = a - 3
*= Multiplication Assignment a *= 4 # a = a * 4
/= Division Assignment a /= 3 # a = a / 3
%= Remainder Assignment a %= 10 # a = a % 10
**= Exponent Assignment a **= 10 # a = a ** 10
Example 2: Assignment Operators
# assign 10 to a
a = 10
# assign 5 to b
b=5
# assign the sum of a and b to a
a += b #a=a+b
print(a)
# Output: 15
Here, we have used the += operator to assign the sum of a and b to a.
Similarly, we can use any other assignment operators according to the need.
3. Python Comparison Operators
Comparison operators compare two values/variables and return a boolean
result: True or False. For example,
a=5
b =2
print (a > b) # True
Here, the > comparison operator is used to compare whether a is greater
than b or not.
Operator Meaning Example
3 == 5 gives us
== Is Equal To
False
3 != 5 gives us
!= Not Equal To
True
> Greater Than 3 > 5 gives us False
< Less Than 3 < 5 gives us True
Greater Than or Equal 3 >= 5 give us
>=
To False
3 <= 5 gives us
<= Less Than or Equal To
True
Example 3: Comparison Operators
a=5
b=2
# equal to operator
print('a == b =', a == b)
# not equal to operator
print('a != b =', a != b)
# greater than operator
print('a > b =', a > b)
# less than operator
print('a < b =', a < b)
# greater than or equal to operator
print('a >= b =', a >= b)
# less than or equal to operator
print('a <= b =', a <= b)
Run Code
Output
a == b = False
a != b = True
a > b = True
a < b = False
a >= b = True
a <= b = False
Note: Comparison operators are used in decision-making and loops. We'll
discuss more of the comparison operator and decision-making in later tutorials.
4. Python Logical Operators
Logical operators are used to check whether an expression is True or False.
They are used in decision-making. For example,
a=5
b=6
print((a > 2) and (b >= 6)) # True
Here, and is the logical operator AND. Since both a > 2 and b >= 6 are True, the
result is True.
Operator Example Meaning
Logical AND:
and a and b
True only if both the operands are True
Logical OR:
or a or b
True if at least one of the operands is True
not not a Logical NOT:
True if the operand is False and vice-versa.
Example 4: Logical Operators
# logical AND
print(True and True) # True
print(True and False) # False
# logical OR
print(True or False) # True
# logical NOT
print(not True) # False
Run Code
Note: Here is the truth table for these logical operators.
5. Python Bitwise operators
Bitwise operators act on operands as if they were strings of binary digits. They
operate bit by bit, hence the name.
For example, 2 is 10 in binary and 7 is 111.
In the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in
binary)
Operator Meaning Example
& Bitwise AND x & y = 0 (0000 0000)
| Bitwise OR x | y = 14 (0000 1110)
~ Bitwise NOT ~x = -11 (1111 0101)
^ Bitwise XOR x ^ y = 14 (0000 1110)
>> Bitwise right shift x >> 2 = 2 (0000 0010)
<< Bitwise left shift x << 2 = 40 (0010 1000)
6. Python Special operators
Python language offers some special types of operators like the identity operator
and the membership operator. They are described below with examples.
Identity operators
In Python, is and is not are used to check if two values are located on the same
part of the memory. Two variables that are equal does not imply that they are
identical.
Operator Meaning Example
True if the operands are identical (refer to the
is x is True
same object)
True if the operands are not identical (do not x is not
is not
refer to the same object) True
Example 4: Identity operators in Python
x1 = 5
y1 = 5
x2 = 'Hello'
y2 = 'Hello'
x3 = [1,2,3]
y3 = [1,2,3]
print(x1 is not y1) # prints False
print(x2 is y2) # prints True
print(x3 is y3) # prints False
Here, we see that x1 and y1 are integers of the same values, so they are equal as
well as identical. Same is the case with x2 and y2 (strings).
But x3 and y3 are lists. They are equal but not identical. It is because the
interpreter locates them separately in memory although they are equal.
Membership operators
In Python, in and not in are the membership operators. They are used to test
whether a value or variable is found in a sequence
(string, list, tuple, set and dictionary).
In a dictionary we can only test for presence of key, not the value.
Operator Meaning Example
True if value/variable is found in the
in 5 in x
sequence
True if value/variable is not found in the 5 not in
not in
sequence x
Example 5: Membership operators in Python
x = 'Hello world'
y = {1:'a', 2:'b'}
# check if 'H' is present in x string
print('H' in x) # prints True
# check if 'hello' is present in x string
print('hello' not in x) # prints True
# check if '1' key is present in y
print(1 in y) # prints True
# check if 'a' key is present in y
print('a' in y) # prints False
Run Code
Output
True
True
True
False
Here, 'H' is in x but 'hello' is not present in x (remember, Python is case
sensitive).
Similarly, 1 is key and 'a' is the value in dictionary y. Hence, 'a' in
y returns False.
Control statements:
In Python, there are three forms of the if...else statement.
1. if statement
2. if...else statement
3. if...elif...else statement
1. Python if statement
The syntax of if statement in Python is:
if condition:
# body of if statement
The if statement evaluates condition.
If condition is evaluated to True, the code inside the body of if is executed.
If condition is evaluated to False, the code inside the body of if is skipped.
Working of if Statement
Example 1: Python if Statement
number = 10
# check if number is greater than 0
if number > 0:
print('Number is positive.')
print('The if statement is easy')
Output
Number is positive.
The if statement is easy
In the above example, we have created a variable named number. Notice the test
condition,
number > 0
Here, since number is greater than 0, the condition evaluates True.
If we change the value of variable to a negative integer. Let's say -5.
number = -5
Now, when we run the program, the output will be:
The if statement is easy
This is because the value of number is less than 0. Hence, the condition
evaluates to False. And, the body of if block is skipped.
2. Python if...else Statement
An if statement can have an optional else clause.
The syntax of if...else statement is:
if condition:
# block of code if condition is True
else:
# block of code if condition is False
The if...else statement evaluates the given condition:
If the condition evaluates to True,
the code inside if is executed
the code inside else is skipped
If the condition evaluates to False,
the code inside else is executed
the code inside if is skipped
Working of if...else Statement:
Example 2. Python if...else Statement
number = 10
if number > 0:
print('Positive number')
else:
print('Negative number')
print('This statement is always executed')
Run Code
Output
Positive number
This statement is always executed
In the above example, we have created a variable named number. Notice the test
condition,
number > 0
Since the value of number is 10, the test condition evaluates to True. Hence
code inside the body of if is executed.
If we change the value of variable to a negative integer. Let's say -5.
number = -5
Now if we run the program, the output will be:
Number is negative.
This statement is always executed.
Here, the test condition evaluates to False. Hence code inside the body of else is
executed.
3. Python if...elif...else Statement
The if...else statement is used to execute a block of code among two
alternatives.
However, if we need to make a choice between more than two alternatives, then
we use the if...elif...else statement.
The syntax of the if...elif...else statement is:
if condition1:
# code block 1
elif condition2:
# code block 2
else:
# code block 3
Here,
If condition1 evaluates to true, code block 1 is executed.
If condition1 evaluates to false, then condition2 is evaluated.
If condition2 is true, code block 2 is executed.
If condition2 is false, code block 3 is executed.
Working of if...elif Statement :
Example 3: Python if...elif...else Statement
number = 0
if number > 0:
print("Positive number")
elif number == 0:
print('Zero')
else:
print('Negative number')
print('This statement is always executed')
Output
Zero
This statement is always executed
In the above example, we have created a variable named number with the
value 0. Here, we have two condition expressions:
Here, both the conditions evaluate to False. Hence the statement inside the body
of else is executed.
Python Nested if statements:
We can also use an if statement inside of an if statement. This is known as
a nested if statement.
The syntax of nested if statement is:
# outer if statement
if condition1:
# statement(s)
# inner if statement
if condition2:
# statement(s)
Notes:
We can add else and elif statements to the inner if statement as required.
We can also insert inner if statement inside the outer else or elif statements(if
they exist)
We can nest multiple layers of if statements.
Example 4: Python Nested if Statement
number = 5
# outer if statement
if (number >= 0):
# inner if statement
if number == 0:
print('Number is 0')
# inner else statement
else:
print('Number is positive')
# outer else statement
else:
print('Number is negative')
# Output: Number is positive
In the above example, we have used a nested if statement to check whether the
given number is positive, negative, or 0.
Python for Loop
In computer programming, loops are used to repeat a block of code.
For example, if we want to show a message 100 times, then we can use a loop.
It's just a simple example; you can achieve much more with loops.
There are 2 types of loops in Python:
for loop
while loop
Python for Loop
In Python, a for loop is used to iterate over sequences such
as lists, tuples, string, etc. For example,
languages = ['Swift', 'Python', 'Go', 'JavaScript']
# run a loop for each item of the list
for language in languages:
print(language)
Run Code
Output
Swift
Python
Go
JavaScript
In the above example, we have created a list called languages.
Initially, the value of language is set to the first element of the array,i.e. Swift,
so the print statement inside the loop is executed.
language is updated with the next element of the list, and the print statement is
executed again. This way, the loop runs until the last element of the list is
accessed.
for Loop Syntax
The syntax of a for loop is:
for val in sequence:
# statement(s)
Here, val accesses each item of sequence on each iteration. The loop continues
until we reach the last item in the sequence.
Flowchart of Python for Loop
Working of Python for loop:
Example: Loop Through a String
for x in 'Python':
print(x)
Run Code
Output
P
y
t
h
o
n
Python for Loop with Python range()
A range is a series of values between two numeric intervals.
We use Python's built-in function range() to define a range of values. For
example,
values = range(4)
Here, 4 inside range() defines a range containing values 0, 1, 2, 3.
In Python, we can use for loop to iterate over a range. For example,
# use of range() to define a range of values
values = range(4)
# iterate from i = 0 to i = 3
for i in values:
print(i)
Run Code
Output
0
1
2
3
In the above example, we have used the for loop to iterate over a range
from 0 to 3.
The value of i is set to 0 and it is updated to the next number of the range on
each iteration. This process continues until 3 is reached.
Iteration Condition Action
1st True 0 is printed. i is increased to 1.
2nd True 1 is printed. i is increased to 2.
3rd True 2 is printed. i is increased to 3.
4th True 3 is printed. i is increased to 4.
5th False The loop is terminated
Note: To learn more about the use of for loop with range, visit Python range().
Using a for Loop Without Accessing Items:
It is not mandatory to use items of a sequence within a for loop. For example,
languages = ['Swift', 'Python', 'Go']
for language in languages:
print('Hello')
print('Hi')
Run Code
Output
Hello
Hi
Hello
Hi
Hello
Hi
Here, the loop runs three times because our list has three items. In each
iteration, the loop body prints 'Hello' and 'Hi'. The items of the list are not used
within the loop.
If we do not intend to use items of a sequence within the loop, we can write the
loop like this:
languages = ['Swift', 'Python', 'Go']
for _ in languages:
print('Hello')
print('Hi')
Run Code
The _ symbol is used to denote that the elements of a sequence will not be used
within the loop body.
Python for loop with else
A for loop can have an optional else block. The else part is executed when the
loop is exhausted (after the loop iterates through every item of a sequence). For
example,
digits = [0, 1, 5]
for i in digits:
print(i)
else:
print("No items left.")
Run Code
Output
0
1
5
No items left.
Here, the for loop prints all the items of the digits list. When the loop finishes, it
executes the else block and prints No items left.
Python while Loop
Python while loop is used to run a block code until a certain condition is met.
The syntax of while loop is:
while condition:
# body of while loop
Here,
A while loop evaluates the condition
If the condition evaluates to True, the code inside the while loop is executed.
condition is evaluated again.
This process continues until the condition is False.
When condition evaluates to False, the loop stops.
Flowchart of Python while Loop
5Example: Python while Loop
# program to display numbers from 1 to 5
# initialize the variable
i=1
n=5
# while loop from i = 1 to 5
while i <= n:
print(i)
i=i+1
Run Code
Output
1
2
3
4
5
Here's how the program works:
Variable Condition: i <= n Action
i=1
True 1 is printed. i is increased to 2.
n=5
i=2
True 2 is printed. i is increased to 3.
n=5
i=3
True 3 is printed. i is increased to 4.
n=5
i=4
True 4 is printed. i is increased to 5.
n=5
i=5
True 5 is printed. i is increased to 6.
n=5
i=6
False The loop is terminated.
n=5
Example 2: Python while Loop
# program to calculate the sum of numbers
# until the user enters zero
total = 0
number = int(input('Enter a number: '))
# add numbers until number is zero
while number != 0:
total += number # total = total + number
# take integer input again
number = int(input('Enter a number: '))
print('total =', total)
Run Code
Output
Enter a number: 12
Enter a number: 4
Enter a number: -5
Enter a number: 0
total = 11
In the above example, the while iterates until the user enters zero. When the
user enters zero, the test condition evaluates to False and the loop ends.
Infinite while Loop in Python
If the condition of a loop is always True, the loop runs for infinite times (until
the memory is full). For example,
age = 32
# the test condition is always True
while age > 18:
print('You can vote')
Run Code
In the above example, the condition always evaluates to True. Hence, the loop
body will run for infinite times.
Python While loop with else
In Python, a while loop may have an optional else block.
Here, the else part is executed after the condition of the loop evaluates to False.
counter = 0
while counter < 3:
print('Inside loop')
counter = counter + 1
else:
print('Inside else')
Run Code
Output
Inside loop
Inside loop
Inside loop
Inside else
Note: The else block will not execute if the while loop is terminated by
a break statement.
counter = 0
while counter < 3:
# loop ends because of break
# the else part is not executed
if counter == 1:
break
print('Inside loop')
counter = counter + 1
else:
print('Inside else')
Run Code
Output
Inside loop
Inside else
Python for Vs while loops
The for loop is usually used when the number of iterations is known. For
example,
# this loop is iterated 4 times (0 to 3)
for i in range(4):
print(i)
Run Code
The while loop is usually used when the number of iterations is unknown. For
example,
while condition:
# run code until the condition evaluates to False
Python break and continue
Python break Statement
The break statement is used to terminate the loop immediately when it is
encountered.
The syntax of the break statement is:
break
Working of Python break Statement
Working of the break statement
The working of break statement in for loop and while loop is shown above.
Python break Statement with for Loop
We can use the break statement with the for loop to terminate the loop when a
certain condition is met. For example,
for i in range(5):
if i == 3:
break
print(i)
Run Code
Output
0
1
2
In the above example, we have used the for loop to print the value of i. Notice
the use of the break statement,
if i == 3:
break
Here, when i is equal to 3, the break statement terminates the loop. Hence, the
output doesn't include values after 2.
Note: The break statement is almost always used with decision-making
statements.
Python break Statement with while Loop
We can also terminate the while loop using the break statement. For example,
# program to find first 5 multiples of 6
i=1
while i <= 10:
print('6 * ',(i), '=',6 * i)
if i >= 5:
break
i=i+1
Run Code
Output
6* 1=6
6 * 2 = 12
6 * 3 = 18
6 * 4 = 24
6 * 5 = 30
In the above example, we have used the while loop to find the first 5 multiples
of 6. Here notice the line,
if i >= 5:
break
This means when i is greater than or equal to 5, the while loop is terminated.
Python continue Statement
The continue statement is used to skip the current iteration of the loop and the
control flow of the program goes to the next iteration.
The syntax of the continue statement is:
continue
Working of Python continue Statement
How continue statement works in python
The working of the continue statement in for and while loop is shown above.
Python continue Statement with for Loop
We can use the continue statement with the for loop to skip the current iteration
of the loop. Then the control of the program jumps to the next iteration. For
example,
for i in range(5):
if i == 3:
continue
print(i)
Run Code
Output
0
1
2
4
In the above example, we have used the for loop to print the value of i. Notice
the use of the continue statement,
if i == 3:
continue
Here, when i is equal to 3, the continue statement is executed. Hence, the
value 3 is not printed to the output.
Python continue Statement with while Loop
In Python, we can also skip the current iteration of the while loop using the
continue statement. For example,
# program to print odd numbers from 1 to 10
num = 0
while num < 10:
num += 1
if (num % 2) == 0:
continue
print(num)
Run Code
Output
1
3
5
7
9
In the above example, we have used the while loop to print the odd numbers
between 1 to 10. Notice the line,
if (num % 2) == 0:
continue
Here, when the number is even, the continue statement skips the current
iteration and starts the next iteration.
Python Functions
A function is a block of code that performs a specific task.
Types of function
There are two types of function in Python programming:
Standard library functions - These are built-in functions in Python that are
available to use.
User-defined functions - We can create our own functions based on our
requirements.
Python Function Declaration
The syntax to declare a function is:
def function_name(arguments):
# function body
return
Here,
def - keyword used to declare a function
function_name - any name given to the function
arguments - any value passed to function
return (optional) - returns value from a function
Let's see an example,
def greet():
print('Hello World!')
Here, we have created a function named greet(). It simply prints the text Hello
World!.
This function doesn't have any arguments and doesn't return any values. We will
learn about arguments and return statements later in this tutorial.
Calling a Function in Python
In the above example, we have declared a function named greet().
def greet():
print('Hello World!')
Now, to use this function, we need to call it.
Here's how we can call the greet() function in Python.
# call the function
greet()
Example: Python Function
def greet():
print('Hello World!')
# call the function
greet()
print('Outside function')
Run Code
Output
Hello World!
Outside function
In the above example, we have created a function named greet(). Here's how the
program works:
Working of Python Function
Here,
When the function is called, the control of the program goes to the function
definition.
All codes inside the function are executed.
The control of the program jumps to the next statement after the function call.
Python Function Arguments
As mentioned earlier, a function can also have arguments. An argument is a
value that is accepted by a function. For example,
# function with two arguments
def add_numbers(num1, num2):
sum = num1 + num2
print('Sum: ',sum)
# function with no argument
def add_numbers():
# code
If we create a function with arguments, we need to pass the corresponding
values while calling them. For example,
# function call with two values
add_numbers(5, 4)
# function call with no value
add_numbers()
Here, add_numbers(5, 4) specifies that arguments num1 and num2 will get
values 5 and 4 respectively.
Example 1: Python Function Arguments
# function with two arguments
def add_numbers(num1, num2):
sum = num1 + num2
print("Sum: ",sum)
# function call with two values
add_numbers(5, 4)
# Output: Sum: 9
Run Code
In the above example, we have created a function named add_numbers() with
arguments: num1 and num2.
Python Function with Arguments
We can also call the function by mentioning the argument name as:
add_numbers(num1 = 5, num2 = 4)
In Python, we call it Keyword Argument (or named argument). The code above
is equivalent to
add_numbers(5, 4)
The return Statement in Python
A Python function may or may not return a value. If we want our function to
return some value to a function call, we use the return statement. For example,
def add_numbers():
...
return sum
Here, we are returning the variable sum to the function call.
Note: The return statement also denotes that the function has ended. Any code
after return is not executed.
Example 2: Function return Type
# function definition
def find_square(num):
result = num * num
return result
# function call
square = find_square(3)
print('Square:',square)
# Output: Square: 9
Run Code
In the above example, we have created a function named find_square(). The
function accepts a number and returns the square of the number.
Working of functions in Python
Example 3: Add Two Numbers
# function that adds two numbers
def add_numbers(num1, num2):
sum = num1 + num2
return sum
# calling function with two values
result = add_numbers(5, 4)
print('Sum: ', result)
# Output: Sum: 9
Run Code
Python Library Functions
In Python, standard library functions are the built-in functions that can be used
directly in our program. For example,
print() - prints the string inside the quotation marks
sqrt() - returns the square root of a number
pow() - returns the power of a number
These library functions are defined inside the module. And, to use them we
must include the module inside our program.
For example, sqrt() is defined inside the math module.
Example 4: Python Library Function
import math
# sqrt computes the square root
square_root = math.sqrt(4)
print("Square Root of 4 is",square_root)
# pow() comptes the power
power = pow(2, 3)
print("2 to the power 3 is",power)
Run Code
Output
Square Root of 4 is 2.0
2 to the power 3 is 8
In the above example, we have used
math.sqrt(4) - to compute the square root of 4
pow(2, 3) - computes the power of a number i.e. 23
Here, notice the statement,
import math
Since sqrt() is defined inside the math module, we need to include it in our
program.
Benefits of Using Functions
1. Code Reusable - We can use the same function multiple times in our
program which makes our code reusable. For example,
# function definition
def get_square(num):
return num * num
for i in [1,2,3]:
# function call
result = get_square(i)
print('Square of',i, '=',result)
Run Code
Output
Square of 1 = 1
Square of 2 = 4
Square of 3 = 9
In the above example, we have created the function named get_square() to
calculate the square of a number. Here, the function is used to calculate the
square of numbers from 1 to 3.
Hence, the same method is used again and again.
2. Code Readability - Functions help us break our code into chunks to make our
program readable and easy to understand.
Python Recursion
Recursion is the process of defining something in terms of itself.
Python Recursive Function
In Python, we know that a function can call other functions. It is even possible
for the function to call itself. These types of construct are termed as recursive
functions.
Following is an example of a recursive function to find the factorial of an
integer.
Factorial of a number is the product of all the integers from 1 to that number.
For example, the factorial of 6 (denoted as 6!) is 1*2*3*4*5*6 = 720.
Example of a recursive function
def factorial(x):
"""This is a recursive function
to find the factorial of an integer"""
if x == 1:
return 1
else:
return (x * factorial(x-1))
num = 3
print("The factorial of", num, "is", factorial(num))
Run Code
Output
The factorial of 3 is 6
In the above example, factorial() is a recursive function as it calls itself.
When we call this function with a positive integer, it will recursively call itself
by decreasing the number.
Each function multiplies the number with the factorial of the number below it
until it is equal to one. This recursive call can be explained in the following
steps.
factorial(3) # 1st call with 3
3 * factorial(2) # 2nd call with 2
3 * 2 * factorial(1) # 3rd call with 1
3*2*1 # return from 3rd call as number=1
3*2 # return from 2nd call
6 # return from 1st call
Python Comments :
In computer programming, comments are hints that we use to make our code
more understandable.
Comments are completely ignored by the interpreter. They are meant for fellow
programmers. For example,
# declare and initialize two variables
num1 = 6
num2 = 9
# print the output
print('This is output')
Here, we have used the following comments,
declare and initialize two variables
print the output
Types of Comments in Python
In Python, there are two types of comments:
1. single-line comment
2. multi-line comment
Single-line Comment in Python
A single-line comment starts and ends in the same line. We use the # symbol to
write a single-line comment. For example,
# create a variable
name = 'xxx'
# print the value
print(name)
Run Code
Output
xxx
Here, we have created two single-line comments:
# create a variable
# print the value
We can also use the single-line comment along with the code.
name = 'xxx' # name is a string
Here, code before # are executed and code after # are ignored by the interpreter.
Multi-line Comment in Python
Python doesn't offer a separate way to write multiline comments. However,
there are other ways to get around this issue.
We can use # at the beginning of each line of comment on multiple lines. For
example,
# This is a long comment
# and it extends
# to multiple lines
Here, each line is treated as a single comment, and all of them are ignored.
Another way of doing this is to use triple quotes, either ''' or """.
These triple quotes are generally used for multi-line strings. But if we do not
assign it to any variable or function, we can use it as a comment.
The interpreter ignores the string that is not assigned to any variable or function.
Let's see an example,
''' This is also a
perfect example of
multi-line comments '''
Here, the multiline string isn't assigned to any variable, so it is ignored by the
interpreter. Even though it is not technically a multiline comment, it can be used
as one.