Python For Beginner
Python For Beginner
PROGRAMMING
In This Book You Will Learn Explanation with Diagramme and
Working Exercises with Successful Execution of Exercises with Output
Readymade Solution With Step By Step Explanation
AMIT K
Contents
Beginners Guide to Learn Python Programming Step by Step
Introduction …………………………………………………………………..…. 27
Chapter 1 : Introduction …………………………………………………... 28
1 What is Python ………………………………………………………… 28
2 Important Terms You Should Know with Python ……… 29
3 Why learn Python ………………………………………………….… 31
4 Java vs Python Program ………………………………….……..… 33
5 Where can we use Python ……………………………………..… 34
6 Popular Frameworks and Libraries of Python …………… 35
Chapter 2 : Python Basic …………………..………………………………. 36
1 Tokens …………………………………………………………………..… 37
1 Example 1 …………………………………………………………….. 38
2 Reserved Keywords …………………………………….…………… 41
Description of Keywords in Python with Examples ……. 43
1 Example 1 : True ………………………………………………….… 43
2 Example 2 : Checking the Value of true …………………. 44
3 Example 1 : False ………………………………………………….. 44
4 Example 1 : None Keyword ……………………………………. 46
5 Example 1 : and ………………………………………………….…. 47
6 Example 1 : or ……………………………………………………..… 48
7 Example 1 : not ……………………………………………………… 49
8 Example 1 : in ………………………………………………………… 50
9 Example 2 : traverse over a sequence in a for loop ... 51
10 Example 1 : is ……………………………………………………..… 51
11 Example 1 : for ……………………………………………………… 52
12 Example 1 : while ……………………………………………….... 52
13 Example 1 : break …………………………………………………. 53
14 Example 1 : continue ………………………..……………….…. 54
15 Example 1 : elif …………………………………………………..… 55
16 Example 1 : def …………………………………………………..… 56
17 Example 1 : return ………………………………………………… 57
18 Example 1 : yield …………………………………………………… 58
19 Example 1 : import ……………………………………………..… 59
20 Example 1 : from …………………………………………………… 60
21 Example 1 : del ……………………………………………………… 61
22 Example 1 : global ……………………………………………….… 62
23 Example 1 : nonlocal …………………………………………..… 63
24 Example 1 : not using the nonlocal ……………………….. 65
25 Example 1 : try, except, raise, and finally ……………… 66
26 Example 1 : assert ………………………………………………… 67
27 Example 1 : pass an error message with assert …..… 68
3 Identifiers …………………………………………………………………… 69
1 Five Rules for writing Identifiers in Python …………..… 69
4 Literals ………………………………………………………………………… 71
1 Example 1 : Literals ………………………………………………… 71
2 Types of Literals in Python Language ……………………… 72
3 String Literals ……………………………………………………….… 73
4 Example 1 : Adding a black slash (\) ……………………..… 74
5 Example 1 : Multi-line string literal ………………………… 74
6 Numeric literals ……………………………………………………… 75
7 Boolean literals ……………………………………………………… 76
8 Example 1 : Boolean literals …………………………………… 76
9 Special literals ………………………………………..……………… 77
10 Example 1 : Special literals ……………………………………. 77
11 Collection literals ………………………………………………….. 78
12 Example 1 : List literals …………………………………………. 78
13 Example 2 : Printing 10 natural numbers ……………… 79
14 Dictionary Literals ………………………………………………… 79
15 Example 1 : Dictionary Literals ……………………………... 80
16 Tuple Literals ………………………………………………………… 80
17 Example 1 : Tuple Literals ……………………………………… 80
18 Set Literals …………………………………………….……………… 81
19 Example 1 : Set Literals ……………………………………….… 81
5 Delimiters …………………………………………………………………… 82
1 Delimiters ……………………………………………………….……… 82
2 Example 1 : Delimiters …………………………………….…….. 83
6 Escape Sequence …………………………………………….……….… 84
1 Escape Sequence ………………………………………………….… 85
2 Example 1 : Escape Sequence \ ………………………………. 86
3 Example 2 : Escape Sequence \t …………………………….. 86
7 Variables ………………………………………………………………..…… 87
1 Variables ………………………………………………………………… 87
2 Example 1 : Creating integer and assigning value …… 87
3 Memory Location of a Variable ……………………………… 88
4 Example 1 : Memory Location of a Variable …………… 88
5 Example 2 : Creating variable and assigning value …. 90
6 Example 3 : Creating percentage ………………………….… 91
7 Example 4 : Initializing values to different variables … 92
8 Built-in Data Types …………………………………………………… 93
1 Types of Built-in Data types in Python …………………. 94
2 Number Data types in Python ……………………………… 95
3 Int Data type ……………………………………………………..… 95
4 Example 1 : Int Data type ………………………………..…… 97
5 Example 2 : Adding two integer variables ………….… 97
6 Float Data type ……………………………………………….…… 98
7 Example 1 : Assign a float value …………………………… 98
8 Complex Data type …………………………………….………… 99
9 Example 1 : Complex Data type ……………………….…… 99
10 Boolean Data type ……………………………………………… 100
11 Example 1 : Boolean Data type …………………………… 100
12 Sequence Data type ……………………………………….…… 101
13 String Data type ……………………………………………….…. 101
14 Example 1 : String Data type ……………………………..… 101
15 List Data type …………………………………………….………… 102
16 Example 1 : List Data type ………………………….………… 102
17 Example 2 : Updating elements in the list …….……… 103
18 Tuple Data type ……………………………………….…………… 104
19 Example 1 : Tuple Data type ……………………..…….…… 104
20 Set Data type …………………………………………………….… 105
11 Example 1 : Set Data type ……………………………….…… 105
9 Global and Local Variables ………………………………………… 106
1 Global Variables ………………………………….………………… 106
2 Example 1 : Global Variables …………………………….…… 107
3 Example 2 : Global Variables …………………………….…… 108
4 Example 3 : Global Variables …………………………….…… 109
5 Example 4 : Global Variables ………………….………...…… 110
6 Local Variable …………………………………..…………………… 112
7 Example 1 : Local Variable …………………………………..… 112
10 Memory Management ……………………………………………… 114
1 Memory Management ………………………………………..… 114
2 How Python Managing Memory ………………….………… 115
3 Example 1 : Assigning value to a variable …….………… 117
4 Example 2 : Two objects with non-overlapping …..... 118
5 Example 3 : Two objects with non-overlapping …….. 119
6 Example 4 : Two objects with non-overlapping …….. 120
7 Stack and Heap Memory in RAM …………………………… 122
8 Example 1 : Stack and Heap Memory …………....……… 122
Introduction
Learning Python Programming step by step.
Python is a powerful language.It is also the easiest language to learn.Python has found preference in a variety of technology fields like Machine Learning,Deep Learning, and Data Science.With the rate at which
Python is finding preference among many technological fields, it's the best time to learn the language.
We want to make it easy to start that journey, no matter what your skills and knowledge arenite does not matter if you know nothing about programming as a whole.
Each chapter of this book builds on the previous chapters in an easy to understand step-by-step process.You will learn theory and also practice what you learn.
Chapter 1 :
Introduction
Here, you will learn all the fundamental concepts of Python step by step.
And at last, you will be comfortable in creating projects in Python.
If you are a beginner to learn Python, In this book you will learn easily.
In each Python topic, you will get programming exercises to test your understanding.
Even if you have no prior knowledge of any programming language, you won’t face any difficulty understanding these topics.
1 What is Python
Python is a simple, general purpose, dynamic, high level, interactive, interpreted, and object-oriented programming language. It is one of the most popular computer programming languages in the world.
1. Python is a general-purpose language, which means we can use it for building a wide variety of application softwares across a multitude of hardware configurations and operating systems.
A general purpose language is a programming language that is the ability to build all kinds of programs. For example, Python is a good example of a general-purpose programming language.
2. Python is a high-level language, which means it enables the programmer to write programs that are not specific to a particular type of computer or designed for a specific task.
A high-level language is easier to understand. It is closer to human language and far to machine language. Some examples of high-level languages are BASIC, C, C++, COBOL, FORTRAN, Java, Pascal, Perl,
PHP, Python, Ruby, and Visual Basic.
3. Python is a dynamically typed language. This means that the Python interpreter does type checking of variable at the runtime. Interpreter assigns the type of variable based on the value of variable at the
runtime.
4. Python is really interactive. This means that we can write the program directly on the Python prompt and interact with the interpreter to generate immediate output.
5. Python is both compiled and interpreted language. Python is an interpreted language because interpreter converts codes into machine-readable byte codes before it can execute them.
It is also a compiled language because bytecode compiler automatically compiles the codes into byte code (to .pyc) when modules imported. But, we can also compile codes explicitly.
6. Python is an object-oriented programming language. This means that it emphasizes the use of objects over functions, in contrast with procedure-oriented languages.
Everything is done through classes and objects. It supports user-defined classes and objects, constructors, encapsulation, inheritance, multiple inheritance, abstraction, polymorphism as well as methods binding at
runtime.
Python Program
On the other hand, we can perform the same task this using one statement in Python.
print("Hello World")
As you can see that both programs are printing the same result, but Python takes only one statement without using a semicolon or curly braces.
5 Where can we use Python
Python is a simple and popular high-level general-purpose programming language. We can use it in the almost every technical field.
For example, we can use Python on a server to create web applications, to connect to database systems, and to handle big data and perform complex mathematics.
Various areas of Python use are as below:
Data Science
Date Mining
Desktop Applications
Console-based Applications
Mobile Applications
Software Development
Artificial Intelligence
Web Applications
Enterprise Applications
3D CAD Applications
Machine Learning
Computer Vision or Image Processing Applications.
Speech Recognitions
Video games
Mathematics
Science
Business
Media, etc.
Chapter 2 :
Python Basic
1 Tokens
2 Reserved Keywords
3 Identifiers
4 Literals
5 Delimiters
6 Escape Sequence
7 Variables
8 Built-in Data Types
9 Global and Local Variables
10 Memory Management
1 Tokens
Tokens are the various elements in the Python program that are identified by Python interpreter.
A token is the smallest individual unit, or element in the Python program, which is identified by interpreter. They are building blocks of the source code.
Python language supports the different types of tokens that are as follows:
Keywords (Reserved words) : True, False, None, class, continue, break, if, elif, else, from, or, def, del, import, etc.
Python interpreter scans written text in the program source code and converts it into tokens during the conversion of source code into machine code.
Output
Explained in Detail
Let us consider the first statement, which consists of nine tokens that are as follows:
x
=
int
(
input
(
“Enter your first number = “
)
)
The second statement in the above code contains the following tokens that are as:
y
=
int
(
input
(
“Enter your second number = “
)
)
Tokens in the third statement in the above code is as:
sub
=
x
–
y
Note that the Python interpreter ignores # comment symbol and text follows it. Interpreter uses the tokens to detect errors, mainly syntax errors.
2 Reserved Keywords
Keywords in Python are unique reserved words that Python reserves for defining the syntax and structure of Python language.
We can’t use these keywords as an ordinary identifier in a Python program while naming variables, functions, objects, classes, and similar items.
import keyword
print(keyword.kwlist)
print( 5 == 5 )
print( 10 > 9 )
print( True or False )
print( 9 <= 28 )
Output
True
True
True
True
Explained in Detail
Since all statements in the above code are true, the interpreter returns True value. In Python, the boolean value “True” is equivalent to 1.
print( True == 1 )
print( True + True + True)
Output
True
3
False: This keyword represents a false boolean value. If a statement is false, interpreter returns “False” value.
Example 1 :
Output
False
False
False
True
1
Explained in Detail
Since the first, second, and third statements are false, interpreter returns “False” boolean value.
While the fourth statement is true, the result of comparison is “True” value.
In Python, False is equivalent to 0 value, the last statement is 1 because 0 + 0 + 1 = 1.
Note : that both “True” and “False” boolean values are the results of comparison operations or logical (Boolean) operations in Python.
None Keyword
This is a special constant in Python used to represent a null value or void (that means nothing). It has own data type. We consider “None” as nil, null, or undefined in different programming languages.
None is not equivalent to False, 0, or empty string, etc. If we compare “None” to anything other than “None” will always return False.
Example 1 :
print(None == False)
print( None == 0 )
print( None == " " )
Output
False
False
False
Example 1 :
Output
True
False
1
b) or: It is a logical operator in Python that returns “True” value if any of the operands are True.
The truth table for or operator is as follows:
Example 1 :
print(True or True)
print(False or False or True)
print(True or False)
print(True or 1)
Output
True
True
True
True
c) not: This is a logical operator that inverts the truth value. The truth table for not operator is as follows:
Example 1 :
print(not True)
print(not False)
Output
False
True
d) in: This is an operator used to check if a value exists in a sequence or not. It evaluates True if the value is present in the sequence otherwise; it returns False.
Example 1 :
Output
True
False
for i in 'keyword':
print(i)
Output
k
e
y
w
o
r
d
e) is: This keyword is an operator used to test object identity. It returns True if both objects point to the same memory location, i.e. if two variables point to the same object.
Output
True
False
True
True
Python Iteration Keywords – for, while, break, continue
a) for: We use this keyword for looping. Generally, we use “for loop” in the program when we know exactly how many times we want to run a block of code.
Example 1 :
Output
abd, Dhanbad
abd, Dhanbad
abd, Dhanbad
b) while: We use while keyword for looping in Python. A statement or group of statements inside a while loop continue to execute until the test condition for the while loop evaluates to False or encounters
a break statement.
Example 1 :
count = 0
while(count < 3):
print("The current count is: ", count)
count = count + 1
print("While loop ended!")
Output
c) break: The break keyword in Python is used to end the loop statement and transfer the control of execution to the statement following immediately after the end of loop.
Example 1 :
Output
1
2
d) continue: This is another useful keyword for loops in Python. When we use continue keyword, the rest of the loop after the keyword is skipped for that iteration and immediately re-evaluates its
condition prior to reiterating the loop.
Example 1 :
Output
1
2
3
5
i = 10
if (i == 5):
print ("Hello")
elif (i == 10):
print ("Python keywords")
else:
print ("Hello Python")
Output
Python keywords
def keyword
We use def keyword for declaring a user-defined function in Python. A user-defined function is a block of code that performs together some specific tasks.
Example 1 :
Output
Inside Function
def func_no_return():
y = 50
print(func_return())
print(func_no_return())
Output
20
None
b) yield: We use yield keyword inside a function like a return statement but yield returns a generator object to the caller rather than a data value.
Example 1 :
# Yield Keyword
def func():
x=0
for i in range(5):
x += i
yield x
for i in func():
print(i)
Output
0
1
3
6
10
class Keyword
We use class keyword to declare a user-defined class in Python. In any programming language, a class is a collection of as many as objects.
A class is basically a user-defined data type that consists of data members, functions, etc. According to OOPs, a class is a template of an object that provides state and behaviour for an object.
We can define a class anywhere in a Python program. But it is a good practice to declare a single class in a module.
class ClassExample:
def func1(parameters):
....
def func2(parameters):
....
import Keyword
The import keyword is used to import all attributes of a module in the current program.
import math
print(math.sqrt(25))
Output
5.0
from Keyword
Generally, we use from keyword with the import statement to include only a specific attribute from the module.
Example 1 :
del Keyword
Everything is an object in the real world of Python. We use del keyword to delete a reference to an object. We can delete any variable or list value from memory location using del keyword. Example 1 :
my_var1 = 200
my_var2 = "abd"
Output
200
abd
NameError: name 'my_var1' is not defined
global Keyword
In Python, global keyword allows the programmer to declare a global variable outside the function globally. A variable defined outside the function or in global scope is called global variable.
It is necessary to write the global keyword to use global variable inside the function. But, there is no need to use global keyword outside the function.
Example 1 :
g_var = 50
def func_read():
print(g_var)
def func_write():
global g_var
g_var = 100
func_read()
func_write()
func_read()
Output
50
100
Explained in Detail
In this example, the func_read() function is just reading the value of g_var variable. Therefore, we do not need to declare it as global.
But the func_write() function is modifying the value of the variable, so we need to declare the variable with a global keyword. You can observe in the output that the modification took place (50 is changed to
100).
nonlocal Keyword
The nonlocal keyword functions similarly to the global keyword. Generally, we use nonlocal keyword to declare a variable inside a nested function (function inside a function) which is not local to it.
It means that the scope lies in the outer inclosing function. To modify the value of a nonlocal variable inside a nested function, we must declare it with a nonlocal keyword.
Else, a local variable with that name will define inside the nested function.
Example 1 :
def outer_func():
x = 50
def inner_func():
nonlocal x
x = 100
print("Inner function: ",x)
inner_func()
print("Outer function: ",x)
outer_func()
Output
Explained in Detail
In this example, the inner_func() is nested inside the outer_func(). The variable x is in the outer_func(). So, if we modify it in the inner_func(), we must declare it as nonlocal. Note that here, x is not a global
variable.
You can observe in the output that we have successfully modified the value of variable inside the nested inner_func() function.
outer_func()
Output
finally:
# this block always gets executed regardless of exception produced.
print('finally block always gets executed')
Output
assert Keyword
In Python, we use assert keyword for debugging purpose. Sometimes, we need to debug the internal state of some assumptions.
In this case, assert keyword helps us to find bugs more conveniently. assert is followed by a condition. If the condition evaluates to true, nothing happens.
But if the condition evaluates to false, AssertionError is raised.
Example 1 :
x = 10
assert x >= 10
assert x < 10
Output
We can also pass an error message with assert to be displayed with AssertionError.
Example 1 :
x = 10
assert x < 10, "x is not less than 10"
Output
3 Identifiers
An identifier in Python is the user-defined name given to identify a variable, function, class, string, list, dictionary, module, or another object.
It helps to differentiate one entity (or object) from another.
In Python programming language, an identifier starts with an alphabetic uppercase letter (A to Z) or lowercase letter (a to z) or an underscore (_) followed by zero or more letters, underscores and
digits (0 to 9).
Python does not allow us to use special characters, such as @, $, /, and % within identifiers.
Five Rules for writing Identifiers in Python
There are following rules for writing identifiers in Python programming language that should keep in mind. They are:
1. Identifiers can be a combination of alphabetic letters in uppercase (A to Z) or lowercase (a to z), or digits (0 to 9) or an underscore (_). Here are some valid identifier examples in Python.
C
c
myClass
my_variable,
my_var1
UPPERCASE
lowercase
CollegeName
schoolName
UPPERCASE_WITH_UNDERSCORES
lowercase_with_underscores
max_marks
2. An identifier cannot start with a numeric digit. For example, 1person is invalid, but person1 is a valid name.
3. We cannot use keywords as identifiers.
4. Identifier may not include special symbols like !, @, #, $, % etc.
5. An Identifier can be of any length in Python.
4 Literals
A literal in Python is a way to represent a fixed value or raw data in the source code. It directly appears in the program and does not change during the execution of a program.
Literals can be either numbers, text, boolean, or any other form of data.
In Python program, we use literals to create fixed values that are assigned to variables, constants, used in expressions, or passed to functions.
Example 1 :
Suppose we want to setting a variable with a specific value in a Python program.
x = 10
Explained in Detail
This statement creates an integer object containing a literal value 10. Literal means simply a value.
String literals
Numeric literals
Boolean literals
Literal Collections
Special Literals
Let’s look at the following diagrammatic representation of the classification of Python literals.
String Literals
A string literal in Python is a consecutive sequence of characters used to store and represent messages, heading, and other text-based information.
It is enclosed within a pair of double quotation marks and single quotation marks. Both are applicable to define the string literals.
“Hello”, ‘World’, “123”, ‘The area of rectangle is: ‘, etc are some examples of string literals. We use quotation marks to start and end the string.
Strings in Python are immutable, meaning that when we perform an operation on strings, the Python interpreter always creates a new string object in the memory, rather than mutating an existing string object.
Types of Strings
Python language supports two types of string objects.
1) Single-line String: A string created in a single line is called single-line string. An example of a single-line string object is as below:
single_line_string = ‘abd # Here, literal is abd.
2) Multi-line String: A piece of statement written in multiple lines is called multiple lines string. In Python, there are two ways to create multi-line string objects.
a) Adding a black slash (\) at the end of each line.
Example 1 :
multi_line_string = 'Welcome \
to \
Python'
print(multi_line_string)
Output
Welcome to Python
b) We can also create a multi-line string literal using triple quotation marks.
Example 1 :
multi_line_string = '''Welcome \
to \
Python, \
Dhanbad'''
print(multi_line_string)
Output
Welcome to Python, Dhanbad
Numeric literals
Numeric literals in Python consists of numbers or digits from 0 to 9. They may be preceded by a positive (+) or negative (-) sign.
All numeric literals in Python are immutable (unchangeable) objects, meaning that when we perform an operation on a number object, the Python interpreter always creates a new number object.
Operation performed on numbers are called arithmetic operations.We can classify numeric literals in Python into three types that are as follows:
Integer literals
Floating point literals
Complex literals
Boolean literals
A boolean literal is a logical value that can have any of the two values: True or False. True represents the value 1 whereas False represents the value 0.
We use boolean literal in certain operations in which need a boolean value. We use boolean value to test whether a condition is true or false.
Example 1 :
# boolean literals
a = (9 == 9)
b = (5 == False)
c = True + 5
d = False + 5
print("a is ", a)
print("b is ", b)
print("c is ", c)
print("d is ", d)
Output
a is True
b is False
c is 6
d is 5
Special literals
Python language contains only one special literal, i.e., None. It is a special constant in Python that specifies the null value or the absence of a value. We use None to specify a field that is not constructed. We also
use None at the end of lists in Python.
Example 1 :
# Special literals
a = None
print(a)
Output
None
Collection literals
A collection literal is a syntactic representation that is used to work with more than one value. Python language provides the four types of collection literal tokens, such as List, Tuple, Dictionary, and Set.
List literals
A list is a collection of mutable data or values of different types. To create a list in Python, place data or values in within square brackets ([ ]) and separating them by commas (,).
You can consider the Python lists similar to arrays in C, C++, or Java.
<name of list> = [ <value1>, <value2>, <value3>, . . . . ]
Example 1 :
# List literals
address = ['Python, 'Joraphatak Road', 'Dhanbad']
print(address)
Output
['Python', 'Joraphatak Road', 'Dhanbad']
Example 1 :
Printing 10 natural numbers and print the numbers in a list called num.
Output
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Dictionary Literals
Python dictionary is a collection of data that stores value in a key-value pairs. They are enclosed in curly braces ({ }) and separated by the commas (,).
Dictionary literals in Python are mutable (changeable) and can also contain different types of data or values.
Example 1 :
# Dictionary literals
fruits_dict = {'a': 'apple',
'o': 'orange',
'b': 'banana'}
print(fruits_dict)
Output
{'a': 'apple', 'o': 'orange', 'b': 'banana'}
Tuple Literals
Tuple in Python is a collection of different data-type, similar to a list. It is immutable, which means we cannot change it after creation. It performs the same operation as a list does.
The parentheses ( ( ) ) enclose it and the comma separates each element of tuples.
Example 1 :
# tuple literals
even_numbers = (2, 4, 6, 8, 10, 12)
vowels = ('a','e','i','o','u')
direction = ('North', 'South', 'East', 'West')
print(even_numbers)
print(vowels)
print(direction)
Output
Set Literals
Set literals in Python are a well-defined collection of unordered data that cannot be changed. The elements of a set are enclosed within curly brackets separated by commas (,).
Example 1 :
# Set literals
fruits = {'Apple', 'Mango', 'Banana', 'Orange', 'Grape'}
print(fruits)
Output
{'Orange', 'Apple', 'Grape', 'Banana', 'Mango'}
5 Delimiters
A delimiter in Python is a sequence of one or more characters that specifies the boundary between various sections in plain text or other data streams.
Python uses symbols and combinations of symbols as delimiters in expressions, literals, tuples, lists, dictionaries, strings, and various parts of a statement.
print(msg)
print(num)
print(fruits)
print(emp_profile)
Output
6 Escape Sequence
An escape sequence in Python is a group or sequence of characters that does not represent its own literal meaning when used inside a character or string.
It starts with a single backslash (\) followed by some characters that have some specific tasks to do.
In Python, the backslash (\) is known as escape character. It tells the Python interpreter to interpret the next character(s) in a specific way and ignores its usual meaning.
# \': Used for printing the text string with a single quotation mark.
print('Good Morning \'Python\'')
Output
Good Morning 'Python'
Example 2 :
Program based on the escape sequence \t:
Output
Welcome to Python
7 Variables
Variables in Python are nothing but the reserved memory locations to store values, such as numbers, some text string, objects, or anything.
Basically, a variable is a symbolic name given to a physical location in the computer’s memory and that memory location contains a value or data.
It tells the computer to store some data in the memory location or to retrieve that data from that memory location.
In simple words, whenever we create a variable in the Python program, we are allocating some space in the memory to store data values.
Example 1 :
we are creating an integer variable and assigning a value to it.
num = 20 # an integer variable.
Explained in Detail
Here, num = 20 will store the value 20 in the computer’s memory location named num, as shown in the below figure. We have used an assignment operator (=) to assign a value to the variable.
num = 20
print(id(num))
Output
1449404138320
Explained in Detail
The id() function generates a unique identification number for the integer object 20. This unique identification number is an integer value which will remain unique and constant for the Python object during its
lifespan, as shown in the below figure. The id for integer object 20 is 1449404138320.
So, a variable is simply a reference to a value stored in the particular memory location. The size of memory reserved by the variable depends the type of value it is going to store. However, its value may vary
during the time of execution, but at a time, only one value can be stored in it.
Example 2 :
Creating variable and assigning value
# Integer assignments.
x = 20
y = 50
z = 100
# Print the values of variables on the console.
print(x)
print(y)
print(z)
Output
20
50
100
Example 3 :
Create a program where we will add marks of three subjects: physics, chemistry, and maths and print the marks obtained and percentage.
phy = 89
chem = 86
maths = 90
# Adding the marks of three subjects.
marks_obtained = phy + chem + maths
Output
Example 4 :
Initializing different values to different variables.
x = 80 # an integer assignment.
y = 99.99 # a floating point assignment.
name = 'Radhika' # a string assignment.
print(x); print(y); print(name);
Output
80
99.99
Radhika
Number
Boolean
None
String
List
Tuple
Dictionary
Set
These data types are further categorized into fundamental, sequence, and set data types.
Fundamental data types or native data types: int, float, and complex.
Sequence data types: string, list, and tuple.
Mapping data type: dictionary
Example 1 :
num1 = 10
percentage = 80.50
Explained in Detail
From the above assignment,
By default, Python will treat num1 as an integer because we have assigned one integer value to a variable num1.
Python will treat percentage as float because we have assigned one float value to a variable percentage.
Output
10
20
30
Example 1 :
Adding two integer variables and assign the result of them in an integer variable.
num1 = 100
num2 = 200
result = num1 + num2
print(result)
Output
300
num1 = 10.555
num2 = 20.99
result = num1 + num2
print(result)
Output
31.544999999999998
num1 = 2 + 5j
num2 = 3.5 + 7.5j
result = num1 + num2
print(result)
Output
(5.5+12.5j)
a = (10 >= 4)
b = (25 == 5 * 5)
c = (18 != 2 * 9)
# Use the print function to see values stored in each variable.
print(a, b, c)
Output
True True False
String
List
Tuple
Set
Dictionary
Output
Hello Python
Happy birthday to you
<class 'str'>
Output
Example 2 :
Updating elements in the list.
Output
Output
Output
Global variable
Local variable
Example 1 :
Creating a Python program in which we will create a global variable in the main code, and access it inside the function and outside the function.
x = 20 # a global variable.
# Creating a user-defined function named my_function.
def my_function():
# Accessing the global variable inside the function.
print("Inside function: ", x)
Output
Inside function: 20
Outside function: 20
Explained in Detail
In the above code, we have created a global variable x in the main code area and assigned it with a value 20. After that, we have defined a function named mu_function(). Inside the function, we have accessed
the global variable to print the value of x.
Outside the function, we again accessed the global variable x and called the function. You can see that a global variable can be accessed successfully inside a function and outside the function.
If we create a variable with the same name as the name of global variable inside a function, Python interpreter will treat this variable as local.
In this case, we can only access it inside the function, not outside the function. However, the global variable will remain with the same name and the original value as it is.
Example 2 :
Creating a variable inside a function with the same name as the global variable.
x = 20 # a global variable.
def my_function():
# Creating a variable with the same name as the name of global variable.
x = 20 * 30 # Here, interpreter will treat as a local variable.
print("Inside function: ", x)
Output
Explained in Detail
Here, Python creates a new local variable with the same name as a global variable name inside the function. That’s why when we accessed it from inside and outside the function, we gained two different values,
as you can see in the output.
Output
Explained in Detail
As you can see in the output, the preceding code printed the changed value of global variable name, which is defined inside the function, and accessed inside functions and also outside function.
Example 4 :
Output
Output
10 Memory Management
Memory management in Python is the process by which the computer system reserves a part or complete section of memory for the process and execution of programs.
It allows the application programs to read and write data. We know that there is an enormous size of memory in the computer system.
It is essential to allocate some free space in the memory and make it available for the execution of the program.
This way of allocating (i.e. providing) memory for the execution of a program is called memory allocation.
Also, when data is no longer in use, must be removed or erased from the memory after being execution of code. Knowledge of memory management helps developers to write the efficient code.
However, Python handles memory allocation and de-allocation at runtime automatically. We do not need to allocate while creating objects or de-allocate memory when deleting objects.
Python interpreter is the responsible for dynamically allocation and de-allocation of the memory. In other words, the Python interpreter takes care of memory management.
In Python, everything is considered as an object. For example, numbers, strings, functions, dictionary, lists, modules, and user-defined classes are considered objects in Python.
We can access them with the help of identifier. Python’s memory manager allocates the memory to the objects as per requirement. It uses a private heap space for memory management, which is not accessible by
the programmer.
All the Python objects and data structures are allocated in this heap space. The memory manager through Python API functions internally manages this private heap space for Python objects.
Python has also an in-built garbage collector, which recycles all the unused memory so that free space is available in heap memory.
Example 1 :
Suppose we assign a value of 10 to a variable x:
x = 10
print(id(x))
Output
2248409678352
Explained in Detail
In this example, the id() function generates a unique identification number for an object. This unique identification number is an integer value which will remain unique and constant for the Python object during its
lifespan, as shown in the below figure. The id for integer object 10 is 2248409678352.
Example 2 :
Two objects with non-overlapping lifetimes can have the identical id value.
x = 10
print(id(x))
y = 10
print(id(y))
Output
2070047162896
2070047162896
Explained in Detail
As you can observe in the output, both reference variables x and y are pointing to the same integer object 10 because of the same unique identification number. Look at the below figure that x and y have
reference to the same object.
Example 3 :
x = 10
print(id(x))
y = 10
print(id(y))
z=y
print(id(z))
Output
2070047162896
2070047162896
2070047162896
Explained in Detail
As you can see in the output, the id() function generated the same identification number for the integer object 10. Therefore, z is also pointing to the same object.
Example 4 :
x = 10
print(id(x))
y = 10
print(id(y))
z=y
print(id(z))
x=x+1
print(id(x))
Output
1887578292752
1887578292752
1887578292752
1887578292784
Explained in Detail
Now, as you can see in the output, the id() function has generated the different identification number for this operation x = x + 1. Therefore, x is not equal to 11 and now refers to the different integer object 11.
Example 1 :
def func(x):
value = (x + 5) * 10
return value
x = 10
final_value = func(x)
print("Final value = ", final_value)
Output
Final value = 150
Explained in Detail
The execution of program code begins from the main which in this case is:
x = 10
final_value = func(x)
print("Final value = ", final_value)
Step 1: Execute x = 10
This statement creates an integer object 10 in the heap memory and the reference variable x is created in the main stack memory that is pointing to this integer object, as shown in the below figure.
def func(x):
value = (x + 5) * 10
return value
In order to execute func(x), Python interpreter adds a new stack frame in the memory. Till the time, func(x) is being executed, the interpreter put on hold the value 10 referenced by x of the lower stack frame.
The integer value 10 is passed as an argument to this function.
Now, value = (x + 5) * 10 = (10 + 5) * 10 = 150 (refer below figure). The func() function assigns the value of 150 to the value.
Now, the func() function will return the value 150, and the interpreter will assign it to the final_value in the main stack memory. Look at the following figure below.
Chapter 3 :
Operators
1 Arithmetic Operators
2 Assignment Operators
3 Comparison (Relational) Operators
4 Logical Operators
5 Bitwise Operators
6 Special Operators
1 Identity Operators
2 Membership Operators
Like other programming languages such as C++ or Java, Python also offers a rich set of many operators for working with and comparing types of data or information.
The definition of an operator is simply a special symbol that tells the interpreter to perform a specific operation or action, usually on numbers (operands).
For example, when we add two values, e.g. (10 + 20 = 30). Here, 10 and 20 are numbers also called operands. The plus (+) sign is an arithmetic operator and (10 + 20) is a numeric expression.
The operand in the expression can be a literal, variable, or any expression that has to be calculated.
Programmers extensively use operators in Python program to perform some sort of calculation, comparison, or assignment on one or more values.
1 Arithmetic Operators
Operators that are used to perform the most common mathematical calculations or arithmetic operations are called arithmetic operators in Python.
All arithmetic operators are binary operators because they do operations on two operands (two or more values). Python supports seven types of arithmetic operators. They are:
Addition (+)
Subtraction (-)
Multiplication (*)
Division (/)
Modulus (%)
Floor division (//)
Exponential (**)
Example 1 :
To add two numbers using (+) operator and display its result.
Output
Sum: 50
Example 2 :
Concatenating two strings using + operator.
firstName = "John"
lastName = "Michael"
fullName = firstName + lastName # Joining two strings with + operator.
print("Full name: ", fullName) # Displaying the result.
Output
Full name: John Michael
Example 3 :
Concatenate two lists using + operator.
x = [1, 2, 3, 4]
y = [5, 6, 7, 8]
result = x + y # Adding the lists x and y.
print(result)
Output
[1, 2, 3, 4, 5, 6, 7, 8]
Output
Subtraction: -10.600000000000001
x = 20
y = 20.20
result = x * y # Two variables multiplied using multiplication operator.
print("Multiplication: ", result)
Output
Multiplication: 404.0
2 Assignment Operators
An operator that is used to store/assign a value to a variable is called assignment operator in Python.
The most common assignment operator is equal operator “=”, which assigns the right-hand value to the left-hand variable.
Simple assignment
Compound assignment
Assignment as expression
Simple assignment
Example 1 :
Adding numbers.
x = 20
y = 50
z=x+y+2
print("Result = ", z)
Output
Result = 72
x = 20
y=5
z = 10
x += y
print("Result of (x = x + y) = ", x)
z += x + y
print("Result = ", z)
Output
Result of (x = x + y) = 25
Result = 40
x = 20
y=5
z = 10
x -= y
print("Result of (x = x - y) = ", x)
z -= x + y
print("Result = ", z)
Output
Result of (x = x - y) = 15
Result = -10
x=2
y=5
z=3
x *= y
print("Result of (x = x * y) = ", x)
z *= x * y
print("Result = ", z)
Output
Result of (x = x * y) = 10
Result = 150
x = 20
y=5
z = 100
x /= y
print("Result of (x = x / y) = ", x)
z /= x * y
print("Result = ", z)
Output
Result of (x = x / y) = 4.0
Result = 5.0
x = 211
y=5
z = 100
x %= y
print("Result of (x = x % y) = ", x)
z %= x + y
print("Result = ", z)
Output
Result of (x = x % y) = 1
Result = 4
x = 211
y=5
z = 100
x //= y
print("Result of (x = x // y) = ", x)
z //= x + y
print("Result = ", z)
Output
Result of (x = x // y) = 42
Result = 2
7. Exponent and Assignment Operator (**=)
This operator performs exponential (i.e. power) calculation on the operands and assigns the result to the left side operand.
Example 7 :
x=2
y=5
z=2
x **= y
print("Result of (x = x ** y) = ", x)
z **= x + y - 30
print("Result = ", z)
Output
Result of (x = x ** y) = 32
Result = 128
x = 20
y=5
x &= y
print("Result of (x = x & y) = ", x)
Output
Result of (x = x & y) = 4
Output
Result of (x = x | y) = 15
x = 20
y = 10
x ^= y
print("Result of (x = x ^ y) = ", x)
Output
Result of (x = x ^ y) = 30
Output
Result of (x = x >> y) = 1
Assignment as Expression
In Python, we can also treat an assignment operation as an expression because the operation has a result. The outcome (or result) of an expression is a value that stored in a variable.
Example 12 :
a, b, c = 19, 31, 50
a += 1
b -= 1
c *= 2
x = (10 + a)
y = x + 100
z=x+y+c
print("Value of a: ", a)
print("Value of b: ", b)
print("Value of c: ", c)
print("Value of x: ", x)
print("Value of y: ", y)
print("Value of z: ", z)
Output
Value of a: 20
Value of b: 30
Value of c: 100
Value of x: 30
Value of y: 130
Value of z: 260
Explained in Detail
The following steps involved to evaluate the above expressions of the Python program.
1. Evaluation of expression: a += 1
a=a+1
a = 19 + 1
a = 20
2. Evaluation of expression: b -= 1
b=b–1
b = 31 – 1
b = 30
3. Evaluation of expression: c *= 2
c=c*2
c = 50 * 2
c = 100
4. Evaluation of x = (10 + a)
5. Evaluation of y = x + 100
6. Evaluation of z = x + y + c
Equal (==)
Not equal (!=)
Greater than (>)
Less than (<)
Greater than or equal to (>=)
Less than or equal to (<=)
1. Equal to (==)
This operator evaluates that the value of left and right operands is equal or not. If the left operand’s value is equal to the right operand’s value, the condition becomes true, i.e. the equality operator returns
true. Otherwise, returns false.
In other words, the equality operator compares and returns true if two objects are equal to each other.
Example 1 :
Output
Returned value of (x == y): True
Returned value of (p == q): True
Returned value of (r == s): False
Returned value of (t == u): False
Returned value of (List1 = List2): True
Explained in Detail
a) In the above code, the string “Text” is not equal to the string “text” because they are not exactly the same; one starts with uppercase letter ‘T’ and the other with lowercase letter ‘t’. Therefore, both reference
variables r and s are pointing to different objects ‘Text’ and ‘text’.
b) The statement (t == u) returned False because both reference variables t and u are pointing to different lists.
c) The statement (List1 == List2) returned True because both reference variables List1 and List2 are pointing to the same object.
x = 50
y = 90
print("Returned value of (x != y): ", x != y)
p = False
q=0
print("Returned value of (p != q): ", p != q)
r = '50'
s = 50
print("Returned value of (r !=s ): ", r != s)
Output
num1 = 60
num2 = 50
print(num1 > num2)
print(num1 + 20 - 20 > num2 + 20)
n1 = 20
n2 = n1
print(n1 > n2)
Output
True
False
False
exp1 = 20 * 20 % 20
exp2 = 20 + 20 / 20
print(exp2 < exp1)
Output
True
False
num1 = 20.20
num2 = 20.0200
print(num1 >= num2)
x = True + 2
y = False + False + False
print(x >= y)
p = 'abcd'
q = 'abcde'
print(p >= q)
Output
True
True
False
num1 = 40.40
num2 = 40.400
print(num1 <= num2)
x = True + 2
y = False + False + False
print(x <= y)
p = 'A'
q = 'B'
print(p <= q)
Output
True
False
True
4 Logical Operators
Logical operators in Python are binary operators which are used to combine two or more simple conditions or relational expressions.
In other words, logical operators combine one or more comparison into one condition group.
It is useful when we want to check more than one condition at a time and use the result.
A simple example of a logical operator that combines two relational expressions, or conditions.
Explained in Detail
From the above statements, it is clear that the logical and operator returns true only if all the expressions (or operands) are true. Otherwise, it returns false value.
Example 1 :
x, y = 10, 5
result = (x == 10 and y == 5)
print(result)
Output
True
False
False
Explained in Detail
a) In the first result statement, there are two conditions or relational expressions; (x == 10) and (y == 5). The result of both conditions are true. Therefore, the logical and operator returns true value.
b) In the second result statement, the condition (x == 10) is true, but the condition (y > x) is false. Therefore, the logical and operator returns false value.
c) In the third result statement, both conditions (x < y) and (y > x) are false. Therefore, the logical and operator returns false value.
Example 2 :
x, y, z = 20, 10, 25
# Use of logical and operator in the if statement.
if(x > y and y > z):
print("Hello")
Output
Python
Explained in Detail
a) In the first if statement, there are two conditions: x > y and y > z. The condition x > y is true, but y > z is not true. Therefore, the statement “Hello” is not displayed on the console.
b) In the second if statement, both conditions z > y and y < x are true. Therefore, the statement “Python” is displayed on the console.
c) In the third if statement, both conditions are false. Therefore, the statement “Hello Python” is also not displayed.
Example 3 :
Output
x: True
y: False
z: False
Explained in Detail
a) In the preceding example code, x returns true because comparison on both sides is true. 15 is less than 20 and the string pen is less than pencil on the basis of ASCII values.
b) Similarly, y returns false because the condition (“Big” < “bigger”) is true, but the condition (True != 1) is false.
c) While, z returns false because the comparison on the right side is false.
print((4 < 2) or (2 == 1)) # It will return false because both comparisons are false.
print((3 != 3) or (3 >= 9)) # It will return false because both comparisons are true.
Explained in Detail
From the above example codes, it is clear the logical or operator returns true only if at least one expression (or operand) is true.
Example 1 :
x, y, z = 20, 10, 5
if(x > y or y > z):
print("Python")
Output
Python
JavaScript
Explained in Detail
a) In the first if statement, both conditions are true. Therefore, the interpreter displays ‘Python’ on the console.
b) In the second if statement, one condition on the right side of or operator is true. Therefore, the interpreter displays ‘JavaScript’ on the console.
c) In the third if statement, both conditions are false. Therefore, the interpreter does not display ‘Java’ on the console.
Example 2 :
x, y, z = 10, 5, 20
if((x > y) or ( y == z)):
print("One")
if((x == y) or (y < z )):
print("Two")
if((x != y) or (y != z)):
print("Three")
if((x < y) or (y > z)):
print("Four")
Output
One
Two
Three
Example 3 :
c = "a" or D
print("c: ", c)
d = ("ABc" > "abC") or False
print("d: ", d)
Output
a: True
b: True
c: a
d: False
Output
a: False
b: True
c: True
d: True
5 Bitwise Operators
Bitwise operators in Python are binary operators that work on the bits comprising ones and zeros (i.e., binary numbers) rather than decimals or hexadecimals.
Here, the term bitwise means to operate on a binary number (0 or 1). Python bitwise operator works on each bit of number.
They operate in the following steps:
1. When we use bitwise operators on the operands (i.e. integer numbers), they firstly convert operands to bits, perform the operation on each bit directly.
2. Then, bitwise operators convert binary output to a decimal number, and give the output in the decimal number.
In bitwise operations, the Python interpreter internally converts the integer numbers into the binary number system that is represented by two digits, 0 or 1.
Bitwise operators may be binary operators or unary operators that work on two operands or one operand.
We listed the truth table for this operator in the below table:
Example 1 :
A= 2
B= 6
result = A & B
print("Result of (2 & 6): ", result)
Output
Result of (2 & 6): 2
Explained in Detail
In this example, the binary conversion of 2 is 0010 and that of 6 is 0110. Bitwise AND operator will take each bit of both binary numbers and perform AND operation as follows in the below figure.
A| B
A= 2
B= 6
result = A | B
print("Result of (2 | 6): ", result)
Output
Result of (2 | 6): 6
Explained in Detail
In this example, the binary conversion of 2 is 0010 and that of 6 is 0110. Bitwise OR operator will take each bit of both binary numbers and perform OR operation as follows in the below figure.
Example 1 :
A = 25
B = 45
result = A | B
print("Result of (25 | 45): ", result)
Output
Result of (25 | 45): 61
Explained in Detail
In this example, the binary conversion of 25 is 011001 and that of 45 is 101101. Bitwise OR operator will take each bit of both binary numbers and perform OR operation as follows below:
25 & 45 => 011001 & 101101 => 111101 => 61 (in decimal number system).
A= 2
B= 6
result = A ^ B
print("Result of (A ^ B): ", result)
Output
Result of (A ^ B): 4
Explained in Detail
In the preceding example, the binary conversion of 2 is 0010 and that of 6 is 0110. Bitwise XOR operator will take each bit of both binary numbers and perform XOR operation as follows below:
2 ^ 6 => 0010 & 0110 => 0100 => 4. The decimal conversion of 0100 is 4.
Example 1 :
A = ~3
print("Result of (~3): ", A)
Output
Result of (~3): -4
Explained in Detail
The bitwise NOT operator will take each bit of binary number and convert all 1s to 0s and all 0s to 1s. The NOT operator also reverses the sign bit of binary number.
Thus, the positive number becomes negative and the negative number becomes positive. Therefore, the signed binary number of 3 is 0011.
~3 => ~0011 => 1100 => -4. The decimal conversion of 0011 is -4.
Example 1 :
A= 3
B= 1
result = A << B
print("Result of (A << B): ", result)
X=3
Y= 2
result = X << Y
print("Result of (X << Y): ", result)
Output
Explained in Detail
a) The working of bitwise left shift operator to shift one bit of 3 to the left side is as follows:
3 << 1 => 0011 << 1=> 0110 => 6 (shifted all bits by 1 position to the left and filled the rightmost one bit by 0).
b) The working of bitwise left shift operator to shift two bits of 3 to the left side is as follows:
3 << 2 => 0011 << 2 => 1100 => 12 (shifted all bits by 2 positions to the left and filled the rightmost two bits by 0).
Bitwise Right Shift Operator (>>)
The bitwise right shift is a binary operator that shifts the number of bits to its right position. It shifts all bits to the right according to the values specified on the right-hand side of the operator.
After performing the right shift operation on the bits, the operator fills the leftmost bits by 0. The general syntax to use bitwise right shift operator is as:
A >> B
Example 1 :
A= 6
B= 1
result = A >> B
print("Result of (A >> B): ", result)
X=6
Y= 2
result = X >> Y
print("Result of (X >> Y): ", result)
Output
Explained in Detail
a) The working of bitwise right shift operator to shift one bit of 6 to the right side is as follows:
6 >> 1 => 0110 >> 1 => 0011 => 3 (shifted all bits by 1 position to the right and filled the leftmost one bit by 0).
b) The working of bitwise right shift operator to shift two bits of 6 to the right side is as follows:
6 >> 2 => 0110 >> 2 => 0001 => 1 (shifted all bits by 2 position to the right and filled the leftmost two bits by 0).
The conversion of 0011 in decimal number system is 3 and that of 0001 is 1.
Chapter 4 :
Conditional Statements in Python ( Control Flow )
1. Conditional Statements
2. If Statement
3. If-else Statement
4. If- elif-else Statement
5. Nested If-else Statement
6. Loops
7. While Loop
8. For Loop
9. Nested Loops
10. Infinite Loop
11. Break Statement
12. Continue Statement
13. Pass Statement
14. Switch Statement
1. Conditional Statements
Here , we will learn about conditional statements or decision-making statements in Python with the help of general flowchart diagram.
A simple program written in Python consists of a set of statements that contain expressions. An expression is a statement (or logical line) that comprises an operand and operator.
When we execute a Python program, at a time, only one statement executes by the Python interpreter. We call these statements as sequential statements.
Sequential statements are those statements that execute from top to bottom one by one (sequentially). The flow of execution takes place from top to bottom in the same order in which they appear in the
program.
However, if we want to change the flow of execution of a program, we can use control flow statements in Python.
Output
Area of triangle = 9.92
In this example, Python starts to execute from the first statement of the program. Python executes sequentially each statement. When the last statement is executed, the execution of program is complete.
In Python programs, we use conditional control flow statements to perform different actions based on different conditions. Python supports conditional control flow statements. They are:
if statement
if-else statements
Nested if statements
if-elseif-else statements
These conditional statements, known as decision making statements in Python because they execute a block of statements based on a decision.
They use the boolean expression for conditional test. The boolean expression may be either a single expression or multiple expressions.
When Python evaluates this boolean expression, it generates a boolean value either TRUE or FALSE as a result. Based on the result, the conditional control flow statement executes the block of statements.
A set of statements that are repeated again and again is called loop body. We can use the loop control statement when we need to execute a block of code several number of times according to a particular
condition.
for loop
while loop
nested loops
For loop is a counting loop that repeats a block of statements a certain number of times.
While loop is a conditional loop that keeps repeating a set of statements as long as some test condition is true.
Break statement
Continue statement
2. If Statement
An if statement in Python is the simplest decision-making statement that allows the programmer to execute a block of statements only if some condition is true.
We use if statement in the Python program to compare data and to make a decision based on the result of comparison.
If statement has one test condition and one action. If the test condition is true, the statements followed by a condition will execute and skip them if the condition is false.
It is also called a conditional statement or single selection statement in Python because it either selects or ignores the action.
if test_condition:
Python statement(s) to be executed if condition is true.
or,
if(test_condition):
statement(s)
Explanation in Detail
a) The test condition consists of a boolean expression that returns a boolean value, either true or false.
b) The test condition may contain any relational comparison that comprises relational or comparison operators like <, >, <=, >=, etc. A relational operator compares two values, variables, or complex
expressions.
c) If the test condition is true, the block of statements inside the if statement executes. If the test condition is false, the block of statements skips or bypass.
d) It is optional to enclose the test condition with a pair of braces ().
e) A block of if statement (also called a body of if statement) is a sequence of statements. All the statements must be intended with the same number of white spaces (called indentation).
The indentation in Python shows the body of if statement. IDLE adds indentation automatically after a colon ‘:’.
f) However, you can choose how many white spaces to use when intending the block of if statement. Generally, we use two or four white spaces for intending, but you can use one space or several spaces if you
prefer.
Example 1:
Let’s write a Python program to calculate the area of a circle if the radius is greater than 0.
radius = 2.5
pi = 3.14
if radius >= 0:
area = radius * radius * pi
print("Area of circle: ", area)
Output
Area of circle: 19.625
Explanation In Detail
In the preceding example, if the boolean expression or condition evaluates to true, intended statements inside the block of if statement executes.
In other words, if the value of radius is greater than or equal to 0, the Python interpreter computes the area of circle, and displays the result on the console.
Otherwise, the interpreter will skip two intended statements in the block, not execute, and continue with the rest of program.
Example 2:
Let’s write a program in Python in which we will prompt the user to enter a number and check that the number is divisible by 2 or not. If the number is divisible by 2, the program prints a message “number is
divisible by 2”.
Output
Example 3:
Let’s write a program in Python in which we will display a “You are eligible to cast a vote” message if the age is greater than or equal to 18. If the age is not greater than or equal to 18, we will display “You are
not eligible to cast a vote!” on the console.
Output
Enter your age to check you are eligible to cast a vote or not: 19
You are eligible to cast a vote.
Example 4:
Let’s write a Python program in which we will take marks for three subjects, such as math, chemistry, and physics from the user. Then, we will calculate the percentage of three subject marks and print “Grade A”
if the percentage is greater than or equal to 90. Look at a glance at the script code to understand better.
myPer = totalMarks / 3
print("Total marks obtained: ", totalMarks)
print("Your percentage: ", myPer)
if(myPer >= 90.0): # if the condition is true, then the statement will be displayed.
print("Grade A")
if(myPer < 90.0): # if the condition is true, then the statement will be displayed.
print("Grade B")
Output
Example 5:
Let’s write a program to check even or odd.
Output
Enter a number: 5
5 is a odd number
and
or
not
x, y, z = 20, 40, 50
if((y > x) and (y < z)): # True
print("y is greater than x but smaller than z")
if((x > y) and (y < z)): # False
print("z is greater than x, y")
if(y % x == 0 and x != 0): # True
print("y is divisible by x")
Output
Explanation In Detail
In the preceding example, the first and third if statements evaluates true as both conditional expressions joined by logical and operator are true.
The second if statement evaluates false as the first conditional expression is false. In this example, if statement will produce true only if both expressions are true.
If any of the expressions is false or both expressions are false, if statement will produce false and skip the intended statement.
Example 2: Use of logical OR (or) operator
x, y, z = 2, 1, 4
if(value := x > y or y < z):
print(value)
if(value := x > y or y > z):
print(value)
Output
True
True
True
Explanation In Detail
In the preceding example, if any of the expression is true or both expressions are true, if statement evaluates true. If both expressions are false, the if statement evaluates false and the block of statements does not
execute.
x, y = 2, 1
if(value := (x == 2) and not(y == 2)):
print(value)
Output
True
3. If-else Statement
If else in Python is a two-way conditional statement or double selection statement. It tests a conditional expression and executes one of two blocks of code, depending on the result.
In other words, an if else statement first evaluates the ‘if test condition/expression’.
If the test condition is true, Python executes the statements inside the block of the ‘if statement’. Otherwise, if the condition is false, Python executes the statements inside the else block.
Python if…else statement decides the execution path based on whether the condition is true or false.
num = 11
if num % 2 == 0:
print(num, "is divisible by 2.")
else:
print(num, "is not divisible by 2.")
Output
10 is not divisible by 2.
Explanation In Detail
In the above code, the specified test condition is false. Therefore, Python execute else block statement and print the message “10 is not divisible by 2”.
Thus, a two-way selection if else statement in Python routes the execution through two different paths based on the result of the condition.
if condition or expression:
statement to be executed if the condition is true.
else:
statement to be executed if the condition is false.
Explanation In Detail
In the above syntax, an optional else statement can follow an if statement. The if condition is a boolean expression that may be any comparison or logical expression that returns the boolean value either true or
false.
Each statement represents a single statement or a block of statements intended by two or four white spaces.
If the boolean expression in the if statement returns true, Python interpreter executes the statements inside the if block. If it returns false value, the interpreter executes statements inside else block.
The else block is an optional part. It means that else block part can be omitted if not required. You can follow this convention in all control statements in Python.
Flowchart Diagram of If else Statement
The flowchart for two-way if-else statement in Python is as shown below in the figure.
Let’s understand with the help of a flowchart diagram how two-way if-else statements work in the Python language.
If the test condition is true, then the if code will execute. If the condition is false, the else code will execute. In no case, both statements will execute at a time.
For example, consider the following below code.
passMarks = 40
if passMarks >= 40:
print("Passed")
else:
print("Failed")
Output
Passed
Explanation In Detail
In the above code, if the boolean expression evaluates to true, i.e., if the passMarks is greater than or equal to 40, is true, and it will print a message “Passed” on the console. If it evaluates to false, the message
“Failed” will print.
Example 1:
x, y = 20, 40
if x > y:
print(x, "is greater than ",y)
else:
print(y, "is greater than ", x)
Output
40 is greater than 20
Explanation In Detail
In the above code, Python evaluates the conditional expression x > y to false. Therefore, it executes else block statement and print the message “40 is greater than 20”.
Example 2:
gender = 'F'
if((gender == 'M') or (gender == 'm')):
print("You are a male")
else:
print("You are a female")
Output
You are a female
Explanation In Detail
In the above code, Python evaluates the conditional expression to false. Therefore, it executes else block statement and print the message “You are a female”.
Example 1:
Let’s write a program to check a number is even or odd using if…else statement.
Output
Enter a number: 20
20 is an even number.
Explanation In Detail
In the above code, we have entered an integer number 20 as a user and store it into a variable number. Python evaluates the if conditional expression (number % 2 == 0) to true. Therefore, it executes if block
statement and print the message “20 is an even number”.
Example 2:
Let’s write a Python program in which we will take marks of three subjects from the user and then calculate the total marks, percentage, and grade using if else statement.
Output
Example 3:
Let’s write the Python code to check whether a number is divisible with another number or not. Print appropriate message on the console.
Output
20 is not divisible by 7
Example 4:
Let’s write a Python program to take a number from the user and check whether it is a Buzz number. A number is a buzz number when it ends with 7 or is divisible by 7.
Output
Example 5:
Let’s write Python code in which we will increment the salary of employee 10% if the salary is greater than 8000. If the salary of employee is less than 8000, will increment 15%.
salary = 7500
if salary >= 8000:
salary = salary + (salary * 0.1)
print("Employee salary: ", salary)
else:
salary = salary + (salary * 0.15)
print("Employee salary: ", salary)
Output
Employee salary: 8625.0
Explanation In Detail
In the above code, the variable salary has initialized with the value 7500. Then, the if else statement will check that the salary is greater than 8000 or not.
If the salary is greater than 8000, it will increment by 10% and display the increment salary on the console. However, if the condition does not satisfy, the else block will execute. In this case, salary will increment
by 15% and display increment salary on the console.
Since the employee’s salary is 7500, which is less than 8000, Python executes else block statements and displays the increment salary.
Explanation In Detail
In the above syntax, if, elif, and else are keywords. The condition-1, condition-2 . . . . . condition-N is the boolean expression that returns either true or false. It consists of any relational or logical operators.
There can be only one if statement, and one else statement, however an arbitrary number of elif statements following if statement as per requirement.
The else statement must always come at last and take the default statement. Sometimes, it is also called if-elif-else ladder statement in Python.
b) If Python “if condition-1” evaluates to false, it tests the “elif condition-2”. If the condition-2 is true, Python executes statements inside the elif block.
c) If the condition-1 and condition-2 are false, Python evaluates condition-3 to true. If it is true, then Python executes statements in the elif block. If it is false, Python checks for the next elif condition-4 and so on.
d) If none of the above conditions is true, the interpreter goes to execute statements inside the else block. If the condition of any ‘if’ or ‘elif’ returns true value, all ‘elif’ and ‘else’ will skip.
e) An if block can have as many elif blocks as needed, but it can have only one else block. However, it is not mandatory for else block to be present.
If else block is absent and none of the above conditions in the ladder are true, the interpreter goes to execute the next statement outside the ladder.
Example 1:
Let’s write a Python program in which we will take a number from the user and check the number is zero, positive, or negative using if-elif-else ladder.
# This statement takes a number from the user and store it into a variable number.
number = int(input('Enter any number: '))
if number <= -1:
print(number, 'is a negative number.')
elif number == 0:
print(number, 'is a zero number.')
else:
print(number, 'is a positive number.')
Output
Enter any number: 89
89 is a positive number.
Explanation In Detail
In the above example, we have entered a number 89 as a user. Python evaluates the if condition. Since the condition is not true, then Python does not execute statement in the if block and goes to check elif
condition.
As the condition is not true, Python executes the default statement inside the else block and prints the message ’89 is a positive number’.
Example 2:
Let’s write a Python program to find the greater between the two numbers using if elif else ladder.
# These statements take two numbers from the user and store it into variables num1 and num2.
num1 = int(input('Enter your first number: '))
num2 = int(input('Enter your second number: '))
if num1 == num2:
print('Numbers are equal.')
elif num1 > num2:
print('First number is greater than second number.')
elif num1 < num2:
print('Second number is greater than first number.')
Output
Example 3:
Let’s write a program in Python to find the greatest among three numbers using if elif else statement.
# These statements take three numbers from the user and store it into variables n1, n2, and n3.
n1 = int(input('Enter your first number: '))
n2 = int(input('Enter your second number: '))
n3 = int(input('Enter your third number: '))
if n1 > n2 and n1 > n3:
print(n1, 'is the greatest number among the three numbers.')
elif n2 > n1 and n2 > n3:
print(n2, 'is the greatest number among the three numbers.')
else:
print(n3, 'is the greatest number among the three numbers.')
Output
Example 4:
Let’s write a program in Python to take the age of the user as input and find whether he is a child, adult, or senior on the basis of age. Using if-elif-else ladder statement.
Output
Example 5:
Let’s write the Python code to enter a character and check it is vowel or consonant.
Output
Example 6:
Let’s write the code in Python to check whether it is a Scalene triangle, Isosceles triangle, or Equilateral triangle. Note that:
Output
Enter the side A: 5
Enter the side B: 5
Enter the side C: 2
It is an isosceles triangle.
Example Program for Best Practice
Example 7:
Let’s write code in Python to make a simple calculator to find addition, subtraction, multiplication, and division of two numbers. The math calculator menu is as follows:
Math Calculator Menu
––––––––––––––––––
+ => Addition
– => Subtraction
=> Multiplication
/ => Division
Output
Example 8:
Let’s create an application in Python to calculate percentage and grade according to percentage of marks of three subjects. Use Python if-elif-else ladder statement.
Output
Explanation In Detail
Since the percentage 92.66 is greater than 90, the first condition will be true. Therefore, Python will not go to check other conditions. As the percent 92.66 is greater than 90%, Grade A will display and the rest
of the elif ladder will skip.
# Outer if statement.
if condition-1:
# Inner if statement declared inside the outer if statement.
if condition-2:
statement to be executed when the condition-1 and condition-2 are true.
Explanation In Detail
In the above syntax, if the condition-1 in the outer if statement is true, Python will follow to check another inner if condition-2. If it is true, the statement inside inner if block will execute. Otherwise, the statement
inside inner if block will not execute if the condition-2 evaluates to false.
If condition-1 in the outer if statement is false, Python will not go to check the condition-2 in the inner if statement.
Example 1:
x = 20
y = 10
z=5
# Outer if statement.
if x > y:
if y > z: # Nested inner if statement.
print('Hello')
Output
Hello
Explanation In Detail
In this example, we have placed an if statement inside another if statement to check for another condition. Python first evaluates the condition x > y to true. Since x is greater than y, the condition x > y is true.
Then, Python will check the inner condition y > z to true.
Since y is greater than z, the condition is true. Hence, Python will execute the statement inside inner if block and display the message ‘Hello’.
Example 2:
x = 20
y = 10
z=5
# Outer if statement.
if x > y:
if y < z: # Nested inner if statement.
print('Hello')
print('Hi')
Output
Hi
Explanation In Detail
In this example, Python first check the outer if condition x > y. Since x is greater than y, so the condition is true. Then, Python goes to check the inner condition y < z.
Since the condition is false, therefore, the statement inside the inner if block will not execute. However, the outer if condition is true, so Python will print the message ‘Hi’ on the console because the print
statement belongs to the outer if block.
Example 1:
x = 20
y = 10
z=5
# Outer if else statement.
if x > y:
print('Outer if block')
if y < z: # Nested inner if else statement.
print('Inner if block')
else:
print('Inner else block')
else:
print('Outer else block')
Output
Outer if block
Inner else block
Explanation In Detail
In this example, we have placed an if-else statement inside another if-else statement to check for another condition. The outer if condition x > y evaluates to true. Therefore, Python prints the message ‘Outer if
block’ and skips the execution of outer else block statement.
After checking the outer if condition, Python evaluates the inner if condition y < z. The condition y < z is false, the inner if block will not execute. Python will execute the statement inside the inner else block and
prints the message ‘Inner else block’.
Example 2:
Let’s write a Python program to check whether a number is divisible by 2 and 3.
Output
Explanation In Detail
In this example, we have placed two if-else statements inside another if-else statement, one in the if block and another in the else block.
Example 3:
Let’s write a program in Python using nested if else statement to check whether a number is zero, positive, or negative.
Output
Explanation In Detail
In this example, Python first tests the expression num >= 0. If it is true, Python follows the inner if condition num == 0 and evaluates to true.
If the inner if condition num == 0 is also true, the inner if block message will display as ‘Number is zero’, otherwise, display as ‘Number is positive’.
Python evaluates the expression num >= 0 to false, it follows its own else block without checking the inner if condition and display as “Number is negative”. This is because the number is neither zero nor positive.
Example 4:
Let’s write a program in Python using nested if statement, check the following:
If age < 18; display ‘You are minor and not eligible to cast vote.’
If age >= 18 and age < 60; display ‘You are young and eligible to cast vote.’
Otherwise, display ‘You are a senior citizen person and will be given special care to cast vote.’
age = int(input('Please enter your age: '))
# Outer if else statement.
if age < 18:
print('You are minor and not eligible to cast vote.')
else:
if age >= 18 and age < 60:
print('You are young and eligible to cast vote')
else:
print('You are a senior citizen person and will be given special care to cast vote.')
Output
Explanation In Detail
In this example, we have nested else block by placing another if-else statement inside the else block. If Python evaluates the if condition (age < 18) to true, the statement inside the if block will execute and else
block of if part will not execute.
If Python evaluates to false, else block of if part will execute. Inside the else block, Python will check the inner if condition (age >= 18 and age < 60) to true.
If the condition is true, if block statement will execute otherwise, else block statement will execute.
Example 5:
Let’s write a program in Python to check whether a year is a leap year.
Output
Explanation In Detail
In this example, we have checked many leap years using nested if statement. A year which is perfectly divisible by 4 is leap years. For example, years such as 2024, 2012, 2004, 1968, etc. are leap years.
Century year ending with 00 is a leap year when it is divisible by 400. For example, 2000, 1200, 1600, 2400, etc. are leap years but 1700, 1800, 1900, etc. are not leap years.
Example 1:
Let’s write a program in Python to make a simple calculator to calculate the addition, subtraction, multiplication, and division of two numbers. Take two numbers as input from the user.
Output
6. Loops
A loop in Python is a control structure that repeatedly executes a statement or a group of statements until a specific condition is true.
In other words, a loop is a control flow statement that allows the repetitive execution of a statement or group of statements repeatedly until a termination condition met. It facilitates the complicated execution
paths easy.
Looping is also called a repetition structure in Python. The block of code can execute many times from zero to infinite number depending on the need.
One complete execution of all statements within a loop is called iteration in Python.
A loop simply tells the Python interpreter to execute a bit of code multiple times if the condition is true and exits the loop when the condition becomes false.
Control statement
Body of the loop
The function of a control statement is to test or evaluate a given condition, also called boolean expression, before the execution of body of the loop. If the given condition satisfies, then the body of loop will
execute.
As long as the test condition evaluates to true, the statements in the loop body continue to execute. If not satisfied, then the body of loop will not execute. This type of loop is called an entry-controlled loop.
The general flowchart diagram for loops in Python is as below:
In all types of entry-controlled loops, there is a control variable called loop counter. You must initialize it with an initial value. The increment or decrement of the control variable modifies each time the iteration of
loop occurs. The loop condition or expression determines the continuation of loop body.
for loop
while loop
nested loops
infinite loops
Explanation In Detail
♦ The while loop is an entry-controlled loop statement that executes a statement or a group of statements inside the loop body repeatedly as long as the conditional expression evaluates to true.
It evaluates the conditional expression each time it executes the loop body and exits the loop when the conditional expression becomes false.
♦ A for loop is an entry-controlled loop statement that executes a statement or a group of statements a certain number of times.
♦ When we place a loop inside another, then it is called nested loops in Python. It allows us to loop over two variables. The outside loop is an outer loop, while the inside loop is an inner loop.
♦ An infinite loop is a loop statement that repeats forever. We also known it as endless loop because the specified condition is always true and the loop body executes repeatedly as long as the program is
running, and never ends.
7. While Loop
While loop in Python is the most fundamental loop statement that repeatedly executes a statement or a group of statements, as long as the specified test condition or expression evaluates to true.
In other words, a while loop repeats the body of the loop as long as a given condition is true.
It evaluates the condition each time it executes the loop body, and it exits the loop when the condition becomes false.
Each repetition of the body of loop is called iteration of loop.
Python while loop is the simplest of all the looping structures. It is an entry-controlled loop statement.
In the entry-controlled loop, Python first evaluates the test condition. If the specified condition is true, then the loop body executes.
If the condition is false, then the loop body does not execute. In this way, the while loop statement executes a block of code repeatedly while the test condition is true.
You can use the while loop statement in Python when you don’t know how many times you want to repeat the code.
Initialization
while test condition:
# Loop body
statement(s)
Explanation In Detail
In the above syntax, the while loop starts with a while keyword that creates a loop. It is followed by test condition or expression, then a colon (:) character.
The test condition or expression consists of boolean expression that produces either true or false value depending on the counter control variable. A while loop doesn’t have a loop variable that sets a range of
values. It has a loop condition.
In the syntax, statement(s) may be a single statement or a group of statements with uniform indentation.
The flowchart for while loop in Python has shown in the below diagram.
# Initialization: The variable count has defined outside the loop and will update inside the loop.
count = 0
# Declare the while loop statement.
# Loop continuation condition expression that must ends with a colon (:).
while count < 5:
# Body of the loop.
print('Hello Python') # This statement will execute as long as the condition is true.
count += 1 # It counts the number of executions, and increments count by 1.
print('Loop finished.') # Continue program if the condition is false.
Explanation In Detail
Here, the body of loop will execute 5 times for count = 0, 1, 2, 3, 4. Each time a statement “Hello Python” will print on the console.
When the count is equal to 5, the condition becomes false and the loop ends. The program control will transfer out of the loop to execute the rest of the code inside the program.
In the above example, count is a control variable that controls the number of executions. It increments by 1 after each repetition or loop. This kind of loop is called counter-controlled loop in Python.
Example 1:
Let’s write a simple Python program to print the first 5 natural numbers by using while loop statement.
Output
Current value of i is 1
Current value of i is 2
Current value of i is 3
Current value of i is 4
Current value of i is 5
Explanation In Detail
In this example, we have assigned the value 1 to the variable i. The while loop block consists of print and increment statements and executes repeatedly until the variable i is greater than 5.
With each iteration, the current value of i is printed and then increased by 1. This process continues until the condition in the while statement evaluates to false.
Example 2:
Let us write a program in Python to print your name five times using while loop.
Output
Example 3:
Let’s write a Python program to display numbers from 5 to 1 by using while loop statement.
Output
54321
Loop finished
Explanation In Detail
In the preceding example, the while loop prints number starting from 5 and going down to 1, until the specified condition i >= 1 evaluates to true. As the value of i is less than 1, the condition is false and the loop
ends.
Example 4:
Let us write a program to calculate the average of n natural numbers where n is an input taken from the user.
# Program to display the average of n natural numbers.
num = int(input('Enter a number up to which you want to calculate average: '))
i= 0
sum = 0
count = 0 # Initialization.
while i < num:
i = i + 1 # Increment by 1.
sum = sum + i
count = count + 1
average = sum / count
print('Average of', num,'natural numbers = ', average)
Output
Explanation In Detail
In this example, we have assigned the variable i, sum, count with a value 0. Python evaluates the expression i < num. Since it is true for the first iteration, the body of while loop executes.
The variable i increments by the value of 1 and it produces the required natural numbers. Variable sum adds the value of sum with the value of i. The variable count keeps the track of number of times the loop
body gets executed.
Python repeats the loop until the test expression becomes to false. We calculated the average as sum/count and printed it on the console.
Example 5:
Let us write a program to calculate the sum of first 10 natural numbers using while loop. That is, 1 + 2 + 3 + . . . + 10 = 55.
Output
Sum of 10 natural numbers = 55
Example 6:
Let’s write a program in Python to find the sum of digits in a number.
Output
Explanation In Detail
In this example, we have used a function named input() to read an integer number from the user and stored it in a variable num. We have assigned the variables sum and remainder with value 0.
Then, we need to calculate the last digit of the number. To get the last digit of a number, we have used the modulus division by 10 and assigned it in the variable remainder.
Now we have added the obtained last digit with the sum variable. We removed the last digit from the number by dividing the number by 10 and cast it as int. This logic will continue until the variable num becomes
0. Finally, we will get the sum of digits in a variable sum.
Example 7:
Let’s write a program in Python to calculate the GCD of two positive numbers.
# Program to find the GCD of two +ve numbers.
n1 = int(input('Enter the first positive number: '))
n2 = int(input('Enter the second positive number: '))
if(n1 == 0 and n2 == 0):
print('Invalid input')
if(n1 == 0):
print('GCD = ',n2)
if(n2 == 0):
print('GCD = ',n1)
while(n1 != n2):
if(n1 > n2):
n1 = n1 - n2
if(n2 > n1):
n2 = n2 - n1
print('GCD of two numbers = ',n1)
Output
Explanation In Detail
In this program, we have read two numbers using the function input() from the user and stored them into variables n1 and n2. We have used if statement to check the conditions.
If both n1 and n2 are zero, it is invalid input because zero cannot be divided by zero, which is indeterminate. If n1 or n2 is zero, the other one is gcd.
When the value of n1 > n2, then n1 = n1 – n2, or n2 > n1, then n2 = n2 – n1. This logic will continue repeatedly until the value of n1 is equal to the value of n2. Finally, the GCD will be n1.
Example 8:
Let’s write a program in Python using while loop to find the Fibonacci series of numbers till 30. The Fibonacci series is: 0, 1, 1, 2, 3, 5, 8, 13, . . . .
Output
Example 9:
Let’s write a program in Python using while loop to display the following pattern.
*****
****
***
**
*
Output
*****
****
***
**
*
Example 10:
Let’s write a program in Python to display the following pattern using while loop statement.
*
**
***
****
*****
Output
*
**
***
****
*****
Example 11:
Let’s write a program in Python using the while loop to display the mathematical table of an input number.
8. For Loop
For loop in Python is a basic conditional looping structure that executes a statement or a block of statements a certain number of times.
We use a for loop in the program when we know exactly how many times we have to repeat a loop.
In the above syntax, the for loop starts with for keyword and ends with a colon (:) character. The iterating_var after for keyword is a loop variable that keeps the track of how many times the loop has to run so
far.
The block of statements that gets repeated in a loop is called the loop body. It may contain any sequence of Python statement. You must follow the indentation in the body with four spaces from the beginning of
the line that begins the for loop.
If the sequence contains an expression list, Python first evaluates it. If it is true, then the Python assigns an element from the sequence to the iterating_var. Next, the block of statement executes.
Example 1:
Output
Explanation In Detail
In this example, Python first assigns the first item 1 from the sequence to the iteration variable count, like count = 1. Then, it executes the statement inside the block of for loop.
Similarly, Python assigns the second item 2 to the iteration variable count, like count = 2, and then again executes the statement inside the for loop body. Thus, the interpreter displays the statement ‘I love to code
in Python’ two times on the console.
Example 2:
Output
count = 1
count = 2
count = 3
count = 4
For Loop with range() Function in Python
Python provides a very useful in-built function named range(). It allows us to define a set of numbers over which the ‘for loop’ iterates the numbers in sequential order.
In other words, the range() function produces a sequence of values which can be iterated through using for loop. The general syntax for range() function is as:
range([start], stop [, step])
Explanation In Detail
Here, both start and step arguments are optional and the range of argument values must be an integer value.
start: This argument value indicates the starting of the sequence. If you do not specify the start value, then the sequence of numbers starts from the zero by default.
stop: The stop value produces numbers up to this value, but does not include the number itself. That is, the range of numbers is 0 to n-1. For example, range(1, 4) means the number 1, 2, and 3 but not 4.
step: The step value indicates the difference between every two consecutive numbers in the sequence. It can be both negative and positive, but not zero. However, it is optional.
Example 1:
Output
0
1
2
Start and stop argument values specified in the range function:
2
3
4
Start, stop, and step argument values specified in the range function:
1
4
7
Explanation In Detail
In the above Python code, the function range(3) produces numbers 0, 1, and 2. During the first iteration, Python assigns the value 0 to the iteration variable x and executes the statement inside the for loop block.
This process continues to execute until Python assigns all the numbers generated by the range() function to the variable x. The function range(2, 5) generates a sequence of numbers 2, 3, and 4.
The function range(1, 9, 3) generates a sequence of numbers 1, 4, and 7 with the difference between each number 2.
Example 2:
Let’s write the Python code to calculate the sum of numbers from 1 to 10.
sum = 0
for num in range(1, 11):
sum = sum + num
print('Sum of numbers between 1 to 10 = ',sum)
Output
Sum of numbers between 1 to 10 = 55
Example
Let’s write a Python program to iterate over each character in the string using for loop conditional statement.
for ch in 'Python':
print('Current character is ',ch)
Output
Current character is P
Current character is y
Current character is t
Current character is h
Current character is o
Current character is n
Explanation In Detail
In this example, we have created an iteration variable ch that iterates through each character of the string and prints each character in the separate line.
A list is a collection of elements or items. We can use for loop to iterate over the elements of a list.
Example
There is a list of fruit items we will iterate it.
Output
Apple
Banana
Orange
Mango
Loop finished...
Explanation In Detail
In this example, we have created an iteration variable called item that holds a single item in the list. The value of variable item is updated each time when the loop iterates over the elements of list.
Thus, the variable item holds Apple, Banana, Orange, and finally Mango. Once it reaches at the end of list, the for loop stops.
Output
Red
Green
Blue
Orange
Loop finished...
Output
List does not contain any even number.
Explanation In Detail
As you can see, that else block is executed when the loop has stopped iterating the list. Since there is no any even number in the list, therefore, statement inside the else block executes.
Example 1:
Let’s write a program in Python to calculate the sum of all even and odd numbers up to a number entered by the user.
Output
Enter a number: 10
Sum of even numbers = 20
Sum of odd numbers = 25
Explanation In Detail
In this example, we have generated a range of numbers using range() function. We have used the modulus operator to check even or odd numbers.
Then, we added up all even numbers and assigned to the variable even. Similarly, we added up all odd numbers and assigned to the variable odd. Then, we printed the result on the console.
Example 2:
Let’s write a program in Python to find the factorial of a number entered by the user.
Output
Enter a number: 6
The factorial of number 6 = 720
Explanation In Detail
The factorial of a positive integer number n is denoted by n! which is the product of all positive integers less than or equal to n. i.e. n! = n * (n – 1) * (n – 2) * (n – 3) . . . 3 * 2 * 1. For example, 6! = 6 * 5 * 4 *
3 * 2 * 1 = 720. The factorial of 0! is always 1.
In the above code, first we have used the input() function to take a number from the user. Then, we have cast the entered number to int and stored it into a variable num.
We have assigned the value 1 to the variable fact. To find the factorial of a number, we need to check the entered number is positive or negative.
If the user enters a zero, then the factorial of zero is always 1. We have used the range() function to produce to numbers from 1 to the user entered number.
Every number will be multiplied by the fact variable and is assigned to the fact variable itself within the for loop. The for loop will iterate over all numbers starting from 1 to the user entered number. At last, the
final factorial value is printed on the console.
Example 3:
Let’s write a program in Python to print a list of numbers in reverse order using for loop.
Output
9. Nested Loops
Nested loops in Python mean one loop inside another loop. Like nested if, Python allows us to place one loop inside another loop.
When we put one or more complete loop(s) within the body of another loop, then we call it as nested loops.
We can place many loops within a loop. But, it is advice that you do not go beyond three levels of nested loops, as it will make the program look clumsy.
In Python, we can construct a nested loop by using while, or for loop statement, or with their combinations.
Example
Output
Value of x = 1
Value of y = 1
Value of y = 2
Value of x = 2
Value of y = 1
Value of y = 2
Nested loops ends here...
Explanation In Detail
a) In this example, the execution will start from the outer for loop. Python first assigns the value 1 to the iteration variable x and prints the value of x on the console.
b) Now, the program control enters the inner for loop. During the first iteration, Python assigns the value 1 to the iteration variable y and prints the value of y on the console.
Similarly, for the second iteration, Python assigns the value 2 for the iteration variable y and prints the value of y.
c) After the complete iteration of the inner loop, Python assigns the value 2 to the iteration variable x and prints the value of x on the console.
d) Then, the program control enters to the inner loop for the second iteration. Now, Python starts the iteration by assigning the value 1 to the iteration variable y and prints the value of y on the console.
e) Similarly, Python assigns the value 2 to the iteration variable y and displays the value of y.
Thus, the values of x and y will change like this:
When x = 1, y = 1, 2
When x = 2, y = 1, 2
In the above sequence, the outer for loop will execute a total 2 times, and the statement inside the loop body will execute 2 times. But, the inner for loop will execute 2 times for each x value and hence the
statement inside the loop body will execute 4 times.
Nested While loops in Python
Like nested for loop, when we place a while loop inside another while loop body, then we call it as a nested while loop statement.
Example
Output
Explanation In Detail
a) In this example, initially, the counter variable x and y set with the value 1.
b) Python first evaluates the outer while loop condition x < 3 to true. Since the condition x < 3 is true, the statement inside the outer while loop executes.
c) The program control enters to the inner while loop and checks the condition y < 3. Since it is true, the statement inside the inner while loop executes. Then, the value of y increments by 1.
d) Now Python again checks the condition y < 3. Since the value of y is less than 3, the statement inside the inner for loop again executes. Then, the value of y again increments by 1.
e) Since the inner while loop condition is now false, the program control comes outside the inner while loop, and increments the value of x by 1.
f) Now, Python again evaluates the outer while loop condition x < 3 to true. Since it is true, the statement inside the outer while loop again executes. But, the program control does not enter the inner while loop
statement because the condition y < 3 is false.
g) Once the Python evaluates the outer while loop condition to false, the program control comes outside the outer while loop and executes the next statement that follows it.
The general flowchart for nested loops in Python has shown in the below figure.
As you can see in the flowchart diagram of nested loops, when the outer loop condition is true, the program control enters to the inner loop and checks the condition.
If the inner loop condition evaluates to true, the block of statements inside the inner loop executes. If the inner loop condition evaluates to false, the program control goes to execute the statements inside the outer
loop body.
After the complete execution of the outer loop body, the outer loop condition again checked. This process continues until the outer loop condition is false.
Example 1:
Let’s write a program in Python to print a table of 2 using nested for loops.
Output
Math table of 2:
2*1=2
2*2=4
2*3=6
2*4=8
2 * 5 = 10
2 * 6 = 12
2 * 7 = 14
2 * 8 = 16
2 * 9 = 18
2 * 10 = 20
Nested for loops ends here...
Example 3:
Let’s write a program in Python to print multiplication tables from 1 to 5 using nested for loop.
Output
Explanation In Detail
In this example, we have used end=’ ‘ in the print function that adds a space instead of default newline. Hence, the numbers will look in one row. The last print() function will execute at the end of the inner for
loop.
Example 4:
Let’s write a Python program to display a triangle of * using nested for loop.
Output
Displaying a triangle of *:
*
**
***
****
Loops end here...
Example 5:
Let’s write a Python program to display a triangle of numbers.
Output
Example 6:
Let’s create a program in Python to display a right triangle pattern of numbers.
Output
Example 7:
Let’s create a program in Python to display the following number pattern.
12345
1234
123
12
1
Output
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
Loops end here...
Example 8:
Let’s write Python code to print the following alphabet pattern using nested for loops.
A
AB
AB C
AB C D
AB C D E
Output
Displaying a right triangle of characters
A
A B
A B C
A B C D
A B C D E
Loops end here...
Example 9:
Let’s create a Python program to display a reverse right triangle of alphabet characters pattern using nested for loops.
AB C D E
AB C D
AB C
AB
A
Output
Displaying a reverse right triangle of characters
A B C D E
A B C D
A B C
A B
A
Loops end here...
10. Infinite Loop
An infinite loop (also called endless loop) in Python is a sequence of statements in a program which executes endlessly.
It occurs when the loop condition always evaluates to true. In other words, a loop becomes an infinite loop if a loop condition never becomes false.
Usually, it is an error in the program when an infinite loop occurs. This is because it takes place only when there is some logical disconnection between the loop body (program code) and the test condition.
Example
count = 1
while count == 1: # Creates an infinite loop.
num = int(input('Enter a number: '))
print('Your entered number = ',num)
print('Good bye!')
In this example, we have assigned the value 1 to the variable count. The count variable does not increment its value and continuously executing statements because the condition always produces the true result.
When you will run the above program code, it produces the following result:
Output
Enter a number: 29
Your entered number = 29
Enter a number: 30
Your entered number = 30
Enter a number: t
Traceback (most recent call last):
File "C:\Python Project\InfiniteLoop.py", line 3, in
num = int(input('Enter a number: '))
ValueError: invalid literal for int() with base 10: 't'
# Jump statement
break;
The flowchart diagram of break statement in Python has shown in the below figure.
From the above flowchart diagram, it is clear that if the Python evaluates the test condition within a loop to true, then the loop ends immediately and the execution control jumps to the next statement following the
loop.
Use of Break Statement in Python
There are three important uses of break statement in Python programming language that is as:
1. We can use the break statement inside the loop body to come out of it. Look at the below figure to understand clearly.
2. We can also use it inside the nested loops. In nested loops, a break statement ends the innermost loop and instructs the Python to execute the statement that follows the immediately terminated block.
3. A break statement is commonly used to prevent the execution of the else statement.
Example 1:
Let’s take a simple program in which we will use a break statement inside the for loop for breaking the loop.
Output
X= 1
X= 2
X= 3
X= 4
Explanation In Detail
In the above code, when x == 5, then the for loop automatically breaks. Therefore, the program only prints the current values from 1 to 4.
Example 2:
Let’s write a program in which we will use break statement inside while loop to exit from loop.
Output
I = 1
I = 2
I = 3
I = 4
Example 3:
for letter in 'Python':
if letter == 't':
break
print('Current letter is ',letter)
Output
Current letter is P
Current letter is y
Example 4:
Let’s write a program in which we will use break statement inside the inner for loop to exit from loop.
Output
10
11
12
13
20
21
30
31
32
33
Example
Output
T
e
c
h
Skipping the loop at n
o
l
o
g
y
As you can see in the above output, the continue statement does not break out of the loop entirely. It just jumps back to the beginning of the loop by skipping the rest of code in the loop body for the next
iteration without exiting the loop.
Look at the below figure to understand more clearly the continue statement in the for loop.
Output
1
2
Continue without 3
4
5
Explanation In Detail
As you can see in the output, 3 is not displayed on the console because when x == 3, the loop is continued and redirected to the control of execution back to the next iteration of the loop. As a result, the value 3
of x will not print.
Example 2:
Let’s write a program in Python to use the continue statement inside the while loop.
Output
1
2
4
5
6
Explanation In Detail
As you can see in the output, the number 3 is skipped when x is equal to 3.
Example 3:
Let’s write a program to use the continue statement inside the nested for loop.
# Outer loop.
for x in range(1, 4):
# Inner loop.
for y in range(1, 4):
if x == 2 and y == 3:
continue # continue statement inside the inner for loop.
print(x,y)
Output
11
12
13
21
22
31
32
33
Example 4:
Output
2
3
4
40
5
50
6
60
Explanation In Detail
In this program code, we have created a loop that iterates the value of variable x from 1 to 6. If x is less than 2, then the loop is continued and do nothing.
Once x is 3 or higher, Python prints the values. Once x is greater than 5, Python prints 10 * x. So, the above program code will print the values as shown in the output.
Output
No output
Here, pass is a keyword in Python. Look at the below flowchart diagram of pass statement.
Explanation In Detail
In Python, we can use the pass statement in function definition def statement, if statement, or for or while loop where they must have a nonempty indented code block.
If the code block is missing, the syntax error will generate. For this reason, Python provides a pass statement, which does nothing, but it is still a valid statement.
There are the following uses of pass statement in Python that are as follows:
1. We can use the pass statement in the program when a statement is syntactically required, but we do not want to use any executable statement at its place.
2. We can use the pass statement to hold the place of code that is not ready or incomplete code yet. We often use in the place of loops or functions.
To use it, we just need to type the word ‘pass’ where we want to insert any other code (like loop or function).
Example
count = 0
while(count <= 5):
pass
As you can see, we have created a while loop that is going to execute some code till the count is less than or equal to 5. Assume this is our code, but we have not complete writing the while loop and want to
move on to something else and come back to it later.
This is the perfect time or place to use the pass statement in Python. Our code will do nothing. When writing the code is finished, we will place it at the place of pass statement.
3. Normally, we use the pass statement within the block of code under the loop statement, typically after a conditional if statement or while statement.
4. We mostly use the pass statement to create empty or null classes or functions.
Example 1:
Let’s write a program to use the pass statement in ‘while loop’.
count = 0
while count <= 5:
count = count + 1
if count == 3:
pass # nothing to be done on this line for output.
print(count, end=' ')
Output
123456
Example 2:
Let’s write a program in Python to use the pass statement in ‘for loop’.
Output
2345
Example 3:
Let’s write a program to use the pass statement in creating an empty class.
class enpty_class:
pass
Output
blank output
Explanation In Detail
In some programming scenarios, we need to construct empty functions or classes. To construct an empty class, just type pass statement like above.
If we remove it, we will get an error: IndentationError: expected an indented block after class definition on line 1. Therefore, ‘pass’ statement is useful when a statement is syntactically required, but the program
requires no action.
Example
Output
Dhanbad
Example:
Let’s write the program code in Python to implement the switch case statement using dictionary mapping.
Output
Dhanbad
Chennai
Explanation In Detail
In this example, we have created different functions which return the name of city. Then, we have created a dictionary in which we have put these in the form of key-value pairs.
After constructing the dictionary, we created a main function named switch with a parameter. This parameter takes a user input in the form of keys to find the name of city.
When we call these values with the help of keys, the specific function gets called, and we get the desired output on the console. At the last, we have called functions by passing two key arguments and printed the
desired output.
This function takes three parameters: object, name, and default. Read the explanation of these parameters below.
Example :
# Creating a class.
class PythonSwitch():
def main_function(self, name_of_day):
default = "Incorrect name of day"
method_name = 'day_' + str(name_of_day)
method = getattr(self, method_name, lambda: default())
return method()
def day_1(self):
return "Sunday"
def day_2(self):
return "Monday"
def day_3(self):
return "Tuesday"
def day_4(self):
return "Wednesday"
def day_5(self):
return "Thursday"
def day_6(self):
return "Friday"
def day_7(self):
return "Saturday"
Output
Sunday
Tuesday
Chapter 5 :
Functions in Python
If you have a block of code that gets invoked more than once, put it into a function. This is because function allows us to use a block of code repeatedly in different sections of a program.
It makes the program more efficient by minimizing the repetition. It makes the code reusable.
Functions help to break down long and complex programs into smaller and manageable segments and enhance program readability and comprehensibility.
Functions are defined outside the class, whereas methods are defined inside the class.
1. Functions help to reduce the duplicate code. They can make a long program into smaller. We can avoid the repetition of frequently required code using functions.
Later, if we need to make a change in the code, we can easily update it in one place. Hence, debugging of code becomes easy.
2. Breaking up of a long and complex program into functions allows us to debug each segment one at a time and then assemble them into a working whole.
3. We can group together all logically related statements in one entity using functions in Python. Function makes the program easy to read, understand, and debug. It improves the clarity of the code.
4. Once we write the code inside the function and test it, we can reuse this code as per the requirement. Reusability is the significant use of functions in Python.
Syntax to define User defined Function in Python
The user creates or defines user-defined functions. The general syntax to declare a user defined function in Python is as follows:
Explained in Detail
In the above syntax, the first line of function definition is header, and the rest is the body of function. The function definition begins with def keyword followed by the function name, parentheses (()), and then
colon (:). The parameter list placed within parentheses is optional.
Components of Python Functions
A block of statements that defines a function in Python consists of the following parts:
1. Keyword def:
Function definition starts with the keyword ‘def’ that defines the function. It tells the beginning of the function header.
2. Function name:
The function_name represents the name of a function. Every function must be a unique user-defined name or an identifier and given to it in the function header statement.
It is an excellent practice to name your function according to the work it performs. In the above example, the function name is msg, and add.
3. Parameters:
The formal parameters (arguments) placed inside the parentheses are optional. A parameter is a piece of data or information that we use inside the function to perform a specific task.
4. Colon (:):
A colon indicates the end of function headers.
5. Docstring:
A docstring is a documentation string that is an optional component. We commonly use it to describe what the function does. We write it on the line next to the function header.
A docstring must enclose in triple quotes and can write up to in several lines. We can access it with: function_name.__doc__.
6. Statement(s):
The body of function consists of one or more valid statements. Each statement must be intended with the same indentation to form a block.
In general, 4 spaces of indentation are standard from the header line in Python. When the function gets called, the statements inside the function’s body execute.
Once the function is invoked, the formal parameters inside the parentheses become arguments.
7. Return statement:
A return statement ends the function call and returns a value from a function back to the calling code. It is optional. If we do not define return statement inside the function’s body, the function returns the object
‘None’.
We will learn about the return statement in the further tutorial in more detail.
Built-in functions
User-defined functions
Built-in functions in Python are predefined functions by the Python system. They allow us to perform a variety of tasks, such as printing messages, converting one type of data to another, etc.
The predefined functions are always available to use. We do not need to import required module for them. Python comes with a variety of built-in functions.
1. abs(value): This function returns the absolute value of a given numeric value.
Example 1 :
Output
0b11000
Output
5.0
Output
5
Output
Square of number 36 = 6.0
6. pow(x, y): This function returns the value of x raised to the power y.
Example 6 :
Output
16.0
Output
Factorial of number 5 = 120
8. len(iterable): This function returns the number of elements or items of the specified iterable object.
Example 8 :
Output
Length of list = 5
9. print(object): This function prints the object to the standard output device.
Example 9 :
Output
This is a message.
10. input(prompt): This function reads input, converts it to a string, and returns that.
Example 10 :
# Prompt or take the input from the user and store it into a variable str.
str = input('What is your name?')
print(str)
Output
What is your name?
11. max(iterable): This function returns the largest number of two or more numbers.
Example 11 :
Output
12. min(iterable): This function returns the smallest number of two or more numbers.
Example 12 :
Output
Smallest number is 10
13. range(stop) or range(start, stop): This function returns the sequence of numbers, starting from ‘start’ value up to (not including) the ‘stop’ value.
Example 13 :
# Creating a sequence of numbers from 0 to 7, and print each number in the sequence.
num = range(5)
for n in num:
print(n, end=' ')
Output
01234
14. round(f, n): This function rounds a number to a given precision in decimal digits.
Example 14 :
Output
6.76
15. log10(x): This function returns the logarithm of x at base 10. Example 15 :
Output
0.301
Example 1 :
Output
Hello world!
Welcome to the world of the programming!
Example 2 :
Output
Number 20 is even
Number 25 is odd
Example 3 :
Output
John
24
Example 4 :
Output
Sum of three numbers = 90
Explained in Detail
In this example, we have created a function named sum_three_numbers with three parameters, such as n1, n2, and n3.
This function’s body has two statements: first is a variable sum that adds three numbers and stores it into the variable sum and second is the return statement that returns the value to the calling function.
# Function definition.
def funct_name(): # function header.
print('This function does not contain any parameter.')
# Main program execution started from here.
funct_name() # function calling.
Output
This function does not contain any parameter.
Explained in Detail
In this example, we have created a function named funct_name that does not contain any parameter. When we called it, the program control goes to the function and executes the statement inside it and print the
message.
Example 2 :
# Function definition.
def calcSum(x, y): # Here, x and y are local variables.
z = x + y # Here, z is a local variable.
print("Sum of two numbers = ",z)
# Main program.
# Calling a function by passing two argument values.
calcSum(20, 30)
Output
Sum of two numbers = 50
Explained in Detail
In this example, when the Python interpreter executes calcSum(20, 30), the function calcSum() is called by passing two argument values.
Then, the program control goes to the calcSum() function and statements inside this function execute with using both values. Finally, the function prints the sum of two numbers as a result.
Look at the execution style of function in the below figure to understand more clearly.
We can also call a function from another function in Python. Let’s write a program in which we will calculate the sum of two numbers by taking numbers as input from the user.
Example 1 :
Output
Enter your first number: 10
Enter your second number: 50
Sum of two numbers = 60
Explained in Detail
In this example program, we have created two functions; one is parameterized function calcSum(num1, num2) and another is non-parameterized function funct_in().
After taking the input from the user, we have invoked the function calcSum() from the funct_in() function. In this way, we can easily call one function from another function.
Example 2 :
Let’s write a program in Python to calculate the perimeter and area of the rectangle using functions.
Explained in Detail
When the Python interpreter executes the funct_in(), then the program control goes to the function funct_in(). Inside the function, Python takes the length of rectangle in string from the user, cast into the integer,
and then store it into a variable length. Similarly, for breadth.
When Python executes calcPer() function with passing arguments, the program control goes to function2 calcPer() and executes all statements by using argument values inside it.
After the complete execution of this function, the control goes back to the executing the function calcArea() inside the funct_in() function.
When the Python executes the function calcArea() with passing arguments, the control goes to the function calcArea() and executes all statements by using arguments inside it.
Example 3 :
Writing a program in Python to calculate the addition, subtraction, multiplication, and division of two numbers taken from the user.
Output
Example 4 :
Writing a Python program to calculate the square of a given number.
def square(num):
result = num * num
print("Square of",num,"=",result)
square(5)
Output
Square of 5 = 25
Example 5 :
Write a program in Python to swap two numbers.
Output
Before swapping:
x: 20
y: 10
After swapping:
x: 10
y: 20
Example 6 :
Writing a Python program to check the given number is even or odd.
Output
Example 7 :
Writing a Python program to test whether a year is leap.
Output
Example 8 :
Writing a Python program to check a number is prime or not, using function calling.
Output
Explained in Detail
In this example, we have used nested if-else statement and for loop to check the conditions for the prime number.
First, we have taken a number as input from the user in the string form. Then, we have converted the entered number into int and stores it into a variable n. We called the function primeChecker() with passing the
variable value.
Inside the function primeChecker(), we have used if-else statement to check the number is greater than 1 or not. If the number is not greater than 1, the else part will execute and print ‘not a prime number.’
Inside the outer if statement, we have used for loop to perform the iteration from 2 to number/2. Inside the for loop, we used the if-else statement. If the number is completely divisible by x with the remainder 0,
then it is not a prime number; otherwise, the number is a prime number.
Example 9 :
Writing a program in which we will create a function and print a list of values containing the square of numbers between 1 to 10 (both included).
def sqList():
# Creating an empty list that will hold values.
l = list()
for x in range(1, 11):
l.append(x ** 2)
print(l)
# Function call.
sqList()
Output
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Explained in Detail
In this example, we have used the for loop for iteration over generated numbers. The numbers will automatically generated using range() function. We have used the append() function to store the result directly
into the list.
The statement l = list means that we are creating an empty list that will store values generated while the for loop executes.
Example 10 :
Suppose we have a list of five subject marks like [68, 98, 78, 88, 86] and we have to find and print the total marks and percentage of a student.
def totalMarks():
# Marks of five subjects for a student.
marks = [68, 98, 78, 88, 86]
# Transferring individual marks into independent variable.
m1 = marks[0]
m2 = marks[1]
m3 = marks[2]
m4 = marks[3]
m5 = marks[4]
# Total marks.
totMarks = m1 + m2 + m3 + m4 + m5
print('Total marks obtained:',totMarks)
# Percentage.
per = totMarks / 5
print('Percentage:',per)
# Function call.
totalMarks()
Output
Parameters are the local variables mentioned within the parentheses in the function definition. We also call them as formal parameters.
Arguments are specific values (or data) passed into the function’s parameters when it is called. We also call them actual parameters.
# Function definition with two formal parameters x and y. They are local variables.
def multiply(x, y):
print(x * y)
# Main program.
# Function call 1.
multiply(20, 30) # Here, 20 and 30 are argument values.
a = 50
# Function call 2.
multiply(20, a) # Here, value 20 and variable a are arguments or actual parameters.
b = 80
# Function call 3.
multiply(a,b) # Here, variables a and b are argument values/ actual parameters.
Output
600
1000
4000
Explained in Detail
As you can see in the above program, we have defined two parameters x and y in the function definition. Both are local variables. We have passed two argument values to the function’s parameters.
However, we can pass many argument values based on the function’s parameters defined, but they should be separated them by a comma.
Types of Function Arguments in Python
In Python, there are four types of function arguments. We can invoke a function using any of these four types of formal arguments. They are:
Default arguments
Required arguments
Keyword arguments
Variable-length arguments
Output
Name: Deepak
Gender: Male
Name: Tripti
Gender: Female
Explained in Detail
In this example, we have specified the default value for the formal parameter gender as ‘Male’. During the first function call, we simply pass the argument value ‘Deepak’ to the parameter name. We did not pass
argument value to gender. In this case, the default value of gender argument will be used.
During the second function call, we passed all two arguments ‘Tripti’ and ‘Female’ to the both parameters name and gender. Hence, no default argument will use.
Example 2 :
Output
Explained in Detail
In this example, we have specified default arguments for the parameters rollNo and branch as 20 and ‘Electrical’, respectively. When we do not pass default values to the parameters rollNo and branch, the
default argument values used.
Required arguments are those arguments that are passed to the function’s parameters in the exact positional order to match the function definition. These arguments are also called positional
arguments in Python.
Positional arguments are mandatory arguments to the function. During the function call, if we do not pass argument values in the correct number and order, or we pass more or less arguments than the number
defined in the function, we will get a syntax error.
Example 1 :
# Program to find the area and perimeter of rectangle using function required arguments.
def rectangle(length, breadth):
areaRec = length * breadth # Area of rectangle.
perRec = 2 * (length + breadth) # Perimeter of rectangle.
print("Area of rectangle = ",areaRec)
print("Perimeter of rectangle = ",perRec)
# Main program.
def main():
ln = int(input("Enter the length of rectangle: "))
br = int(input("Enter the breadth of rectangle: "))
rectangle(ln) # Intentionaly missing one argument value.
main() # function calling.
Output
Explained in Detail
In this example program, the length and breadth defined in rectangle() function are formal parameters. The ln and br are actual parameters or arguments.
When we execute the above program code, Python assigns the input value to actual parameters, ln and br. We have called rectangle() function from inside the main() function by passing one argument and another
is missing. Therefore, we got syntax error.
Hence, when you call a function that specifies some formal parameters, you must pass the exact required number of arguments to the function.
Keyword Arguments in Python
Keyword arguments are those arguments in which values are associated with parameter names. That’s why these arguments are also called named arguments.
They are especially useful when we call a function with a long parameter list where most of the formal parameters have default values and we only wish to update very few of them.
When we use keyword arguments in the function call statement, the caller identifies arguments by the parameter name. We pass the keyword arguments with assigned values in the function call.
The advantages of using keyword arguments in the function call are as:
Using keyword arguments, function calling becomes easier since we do not need to worry about the order of arguments.
We can pass values to those parameters to which we wish to, provided that other parameters have default argument values.
Example 1 :
Printing the name, age, and gender of two persons using required arguments.
Output
Name: John
Age: 20
Gender: M
Name: Jenny
Age: 18
Gender: F
Explained in Detail
In this example program, we have not used keyword arguments. Therefore, the order in which we specify the argument values is important. Otherwise, we will get incorrect outcomes.
Example 2 :
Modifying keywords, name, age, and gender.
Output
Name: Herry
Age: 20
Gender: M
Name: Jimmy
Age: 18
Gender: F
Explained in Detail
Now observe the function call statement in the above program: the variable name gets the value of ‘Herry’ due to the order or position of the argument. Then, the formal parameters age and gender gets values 20
and ‘M’ respectively due to named or keyword arguments.
Similarly, in the second function call, we have assigned all the formal parameters through keyword arguments. So, the position of all arguments does not matter. However, it is not recommended to change the
order of parameters.
In some case, we may need to call a function with more arguments than we specified when defining the function. These arguments are called variable length arguments in Python.
They are useful when we do not know the exact number of arguments that will be passed to the function. We can pass the multiple non keyword argument values with a single parameter name.
Example 1 :
Output
Explained in Detail
In this example program, you can see that in the first function call, we have passed 2 arguments. In the second function call, we have passed three arguments, whereas we have passed four arguments in the third
function call.
Hence, this is a significant feature by Python that allows us to pass n number of non keyword arguments with a single parameter name.
Example 2 :
# Function definition with one formal parameter and variable length parameters.
def listDay(arg1, *arg2):
print(arg1, arg2, sep="")
def main():
listDay('Name of days are:', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')
main() # function calling.
Output
Name of days are:('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')
Explained in Detail
In the above example program, the first argument ‘Name of days are:’ passed to the function and assigned into arg1 formal parameter and passed the rest of the non keyword arguments as a tuple with ‘*arg2’.
When we define a custom or user defined function in Python we may, optionally we may need to specify parameter names between the function’s parentheses.
If we specify parameters in the function definition, then we need to pass argument values to the function’s parameters while calling it.
The function use that passed values during its execution by referencing it via parameter name.
Basically, there are two ways to pass argument values to the function’s parameters. They are:
Call/Pass by Value
Call/Pass by Reference
Call/Pass by Reference
In pass by reference (also known as call by reference), the argument passed to the function’s parameter is the original object. If we change the value of object inside the function, the original object
will also change.
There are the following important points about the pass by object reference you should keep it mind.
In the Python programming language, all argument values are passed to a function by object reference.
If the object is mutable (changeable), the changed value is available outside the function. Mutable objects may be list, set, dictionary, byte array.
If the object is immutable (not changeable), the changed value is not available outside the function. Immutable objects may be numbers (int, float, complex), strings, tuple, frozen set,
bytes.
If we pass immutable objects to the function, the passing works like pass by value or call by value.
If we pass mutable objects to the function, the passing works like pass by reference or call by reference.
Example 1 :
Writing a Python program in which we will pass mutable objects (list) to the function using pass by object reference.
# This program illustrates the concept of call by object reference using mutable objects.
def my_funct(y):
print('Values inside the function before modifying:',y)
y[2] = 4 # modifying value.
print('Values inside the function after modifying:',y)
Output
Values outside the function before modifying: [1, 2, 3]
Values inside the function before modifying: [1, 2, 3]
Values inside the function after modifying: [1, 2, 4]
Values outside the function after modifying: [1, 2, 4]
Explained in Detail
In this example, ‘x’ is a list of values. Since the list is a mutable object in Python, the passing acts like call by reference. We have passed x as an argument to the function’s parameter y using call by reference.
Here, y is a formal parameter, whereas x is an actual argument. Both x and y belong to the same memory location. If we make any change in y inside the function, then it also affects in x outside the function.
In this scenario, Python makes only one copy of the argument in the memory location for processing. Values are the same in that copy, but parameter names are different, x and y.
Example 2 :
Writing a Python program in which we will pass immutable objects (string) to the function using pass by object reference.
# This program illustrates the concept of call by object reference using immutable objects.
def my_func(name):
print('String inside the function before modifying:',name)
name = 'John' # modifying value.
print('String inside the function after modifying:',name)
# Main part of program.
n = 'Herry'
print('String outside the function before modifying:',n)
Output
String outside the function before modifying: Herry
String inside the function before modifying: Herry
String inside the function after modifying: John
String outside the function after modifying: Herry
Explained in Detail
In this example, n is a string. Since string is an immutable object in Python, the passing acts like call by value. We have passed ‘n’ as an argument value to the function’s parameter name.
Here, ‘name’ is a formal parameter, whereas ‘n’ is an actual argument. Initially, both have the same memory location. As we have made an update in the value of name (name = ‘John’), the value of name also has
updated.
In this scenario, the value of ‘n’ remains the same and the memory location of ‘n’ also remains the same. But, the memory location of ‘name’ is changed. Hence, Python makes two copies of arguments in two
memory locations for processing.
Example 3 :
Wtiting a program in which we will pass mutable objects (List) to the function using pass by object reference. In this program, two variables will share the same memory location.
def my_func(y):
print('Id of y before modifying list:',id(y))
print('Values inside the function before modifying:',y)
y[2] = 5
print('Values inside the function after modifying:',y)
# Main program.
x = [1, 2, 3]
print('Values outside the function before modifying:',x)
print('Id of x before modifying list:',id(x))
Explained in Detail
In this example, ‘x’ is a list. Since the list is a mutable object, the passing will act like call by reference. We pass ‘x’ as an argument to the function my_func(). ‘x’ is an actual argument, whereas ‘y’ is a formal
parameter.
Before updating the list, the memory location of both variable x and y is the same. But, as we made an update in y, also reflected in x. In this case, memory location of both x and y are the same even after making
the changing in y.
In this program, we have used id() function that take an object as a parameter (i.e. id(object)) and return the identity of this particular object. The returned value is an integer, which is unique and permanent for
this object during its lifetime.
Example 4 :
# This program is a demonstration of call by reference overwritten.
def my_func(y):
print('Values inside the function before modifying:',y)
y[1] = 60
print('Values inside the function after modifying:',y)
y = [1, 2, 3, 4, 5] # It would assign a new reference to y.
print('y =',y)
print('x =',x)
# Main program.
x = [10, 20, 30, 40]
print('Values outside the function before modifying:',x)
my_func(x)
print('Values outside the function after modifying:',x)
Output
Values outside the function before modifying: [10, 20, 30, 40]
Values inside the function before modifying: [10, 20, 30, 40]
Values inside the function after modifying: [10, 60, 30, 40]
y = [1, 2, 3, 4, 5]
x = [10, 60, 30, 40]
Values outside the function after modifying: [10, 60, 30, 40]
6 Return in Python Return Statement
A return in Python is a keyword that passes (or returns) a value or data from the function back to the main code.
When we declare a return keyword with a value or expression separating by the comma, then we call it a return statement. It is used to return a value from a function to the caller.
A function that returns some computed result in the terms of a value to the caller is called fruitful function or non-void function in Python.
A function that does not return any computed or final value to the caller is called void function. It may or may not have a return statement.
def function_name(formal_parameters):
.......
function's body
.......
return <values/expression>
There are a few key points about the return statement that you should keep in mind. They are:
1. Return statement finishes the function call’s execution and returns the result (value or expression).
2. Python function can have one or more return statement but only one statement will execute based on the matching condition.
3. A void function may or may not return a value to the caller. If the function does not contain a return statement, it will send a None value that represents nothingness.
Example 1 :
Output
In this example, the greet() function does not return explicitly a value. It simply prints a message on the console. Since the function does not have a return keyword, it prints None value, which is implicitly sent by
functions without return statement.
4. A function that returns a value, always have a caller which call and receives the final value of a function.
5. Return None is the same as a return statement with no argument value or expression. This means that a void function has a return statement, but it is not returning any value to the caller. It has the following
general syntax.
return
6. A return statement may return more than one value from the function to the caller. It has the following general syntax.
return <value1>, <value2>, <value3>, . . . .
7. The statement following the return statement will not execute.
Example 2 :
Output
I love Python
None
Example 3 :
Writing a simple program in Python that will return the sum of two numbers to the caller.
Output
Sum of two numbers = 50
Explained in Detail
In this example, we have defined a function named addition that has two parameters num1 and num2. When we have called this function with passing two argument values 20 and 30, it calculates the sum of two
numbers and returned that values to the caller.
Then, we have stored the returned value into a variable named total and printed it on the console. Look the complete execution style of function addition in the below figure.
Example 4 :
Writing a simple program in Python to calculate the cube of a number. We will take a number from the user.
def calCube(x):
return x * x * x # x is the formal parameter.
def main_function():
n = int(input('Enter your number: '))
# Calling function from another function.
result = calCube(n) # n is the actual parameter
print('Cube of a number = ',result)
# Calling main function.
main_function()
Output
Explained in Detail
Inside the main_function(), we have taken a number from the user using input() function, converted it into int and stored in a variable n.
Then, we have called the calCube() function with passing the value of n to the function’s parameter x. After the calculation of cube, function returned the value to the caller. We have assigned it into a variable
result and then printed the result on the console.
Example 5 :
Writing a program in Python to compute the area and circumference of circle using function and return statement.
PI = 3.14
def areaCircle(r):
area = PI * r * r
return area
def circumCircle(r):
circumference = 2 * PI * r
return circumference
def main_func():
radius = int(input('Enter radius of the circle: '))
area = areaCircle(radius)
circum = circumCircle(radius)
print('Area of circle =',area)
print('Circumference of circle =',circum)
main_func() # calling main function.
Output
Example 6 :
Writing a Python program to make a simple calculator using function and return statement.
def add(x, y):
return x + y
def sub(a, b):
return a - b
def mult(p, q):
return p * q
def div(r, s):
return r / s
Output
Enter your first number: 10
Enter your second number: 5
Addition = 15
Subtraction = 5
Multiplication = 50
Division = 2.0
Python Function Return Multiple Values
We can return multiple values from a Python function. We separate the values after the return keyword by comma.
Example 1 :
print(p)
print(q)
print(r)
print(s)
print(func())
Output
10
Hello
P
20
(10, 'Hello', 'P', 20)
Example 2 :
Writing a program in Python in which we will take marks of five subjects from the student as a user. Then, we will calculate total marks and percentage of a student’s marks using function and return more than
one value from a function.
Output
It can accept any number of parameters and perform operation inside the function. A void function may or may not return a value to the caller.
If we do not declare return statement to return a value, Python will send a value None that represents nothingness.
Example 1 :
Writing a programme , which will calculate the sum of two numbers and prints the result on the console.
Output
Explained in Detail
In the above program, we have declared a void function named voidOperation(), which does not return any computed value but performs basic operation inside it.
Inside the void function, we have taken two numbers as inputs from the user. Then, we have casted into int and stored them into two variables named num1 and num2, respectively.
When we have called the void function voidOperation() from inside another function main_fn(), the voidOperation() function performs the operation to calculate the sum of two numbers and prints the result on
the console.
Example 2 :
Writing a program in Python in which we will find even and odd numbers till n numbers using continue statement. We will take n numbers as input from the user.
Output
Enter your number till you want to find an even or odd number: 5
Odd number: 1
Even number: 2
Odd number: 3
Even number: 4
Odd number: 5
Example 3 :
Writing a program in Python in which we will take a number from the user and check whether it is a palindrome.
A palindrome number is that number that when we read in reverse order is the same as is read in right order. For example, 121, 125521, 610016, etc.
Output
Example 4 :
Writing a program in Python in which we will accept a number from the user and check whether a number is a perfect number.
We will call a number as perfect number if it is equal to the sum of its factor other than the number itself. For example, 6 is a perfect number because 6 = 1 + 2 + 3.
Output
Example 5 :
Writing a Python program in which we will take marks of five subjects from a student as a user and calculate the total marks, percentage, and then display them on the console.
Output
In other words, the scope is the region of a program where we can access a particular identifier or variable. This is called scope of variable or simply variable scope.
Variables declared inside a program may not be accessible at all locations of that program. It depends on the where we have declared a variable in a program.
Most variables that we define in Python are local in scope to their own function or class.
Example 1 :
# Main program.
print(name) # Not accessible because the variable name is undefined here.
localScope() # calling function.
Output
Explained in Detail
In the above example, the variable name defined inside the function will be accessible within that entire function. Therefore, we have easily accessed and printed the value of variable name on the console.
But, when we accessed from the main program that calls the function, then we got NameError. This is because the variable defined within a function has a local scope and is only visible inside the function, not
outside the function.
Variable Scope and Lifetime in Python
Scope : Scope of variable is a region of the program where a variable is visible or accessible.
Lifetime : Lifetime of a variable is the duration for which a variable exists in the memory.
Lifetime of a variable declared inside a function is as long as the function is alive. When the execution of function body is finished, then the variable defined inside a function will destroy.
Global scope
Local scope
When we define a variable inside the main program but outside the function body, then it has a global scope. The variable declared in the main body of the program or file is a global variable.
In the global scope, the global variable will be visible throughout the program or file, and also inside any file which imports that file. We can easily access a variable defined in global scope from
all kinds of functions and blocks.
Example 1 :
Writing a program in Python in which we will define a global variable and access it from both inside the function and main program body.
# Main program.
showMe() # calling function.
print('Value of x from global scope = ',x)
Output
Explained in Detail
In this example, variable x is a global variable. We have accessed it from both inside the function and outside the function because it has a global scope.
Local Scope
A variable defined or created inside a function body or a block has a local scope. We can access it only within the declared function or block and not from outside that function or block.
As the execution of function body or block is finished, Python destroys the local variable from the memory. In other words, local variable exists in the memory as long as the function is executing.
Example 1 :
Writing a program in which we will define a local variable within in a function and we will access it inside a function and from outside the function.
def my_funct():
msg = 'Good morning!' # local variable with local scope.
print(msg) # accessing local variable from inside the function.
my_funct()
print(msg) # accessing local variable from outside the function.
Output
Good morning!
print(msg) # accessing local variable from outside the function.
NameError: name 'msg' is not defined
Explained in Detail
As you can see in the output, as we called local variable from outside the function or main program, we got error because Python destroyed the local variable after the execution of function. That is, the local
variable does not exist outside the function.
When we define a variable inside the function, it is not related to any way to another variable with the same name used outside the function.
Example 2 :
Writing a program, where a variable defined outside a function will be read inside a function only when the function does not change the value.
Output
City: Dhanbad
City: New York
Explained in Detail
In the above program code, first we have assigned a value ‘New York’ to the city, and then printed the value of city on the console after calling the function.
Next, we have created a function named showMe(). Inside the function showMe(), we have defined a variable with the same name as that of global variable but with a change value.
When we accessed this variable, then Python prints the change value on the console, not the value of global variable because it is not related to any way to another variable with the same name used outside the
function.
As the execution of function body is completed, the value of city is destroyed because it is a local variable to that function only.
The scope of local variable is limited to the function or block in which we specify it. Furthermore, when we define a variable within a function or block, that variable is local by default.
We can use it only within that function because it is not accessible outside.
But, we can create a variable global within a function using global keyword. When we define a variable with a keyword global inside a function, we call it as global statement in Python.
Example 1 :
Writing a program by declaring a global statement using the global keyword to better understand the definition.
Output
50
Explained in Detail
As you see in the above example program, we can easily access the global variable declared inside a function from outside the function.
Example 1 :
Writing a program in which we will access a global variable from the inside of a function.
x = 10 # x is global variable.
y = 20 # y is a global variable.
def my_func():
# Accessing global variables inside the function.
print(x)
print(y)
my_func()
Output
10
20
Example 2 :
Writing a program in which we will try to modify the global variable from inside a function.
x = 10 # x is global variable.
y = 20 # y is a global variable.
def my_func():
# Trying to modify the global variable inside the function.
x = x + 30
print(x)
print(y)
my_func() # function call.
Output
UnboundLocalError: local variable 'x' referenced before assignment
Explained in Detail
Here, we have created two global variables, namely x and y. Inside the function my_func(), we are updating the value of x by incrementing by 30. No updating is in the value of b.
Since we are trying to modify the global variable x inside the function without using global statement, therefore, it has displayed error. Because we can only access the global variable but cannot modify it inside the
function.
Example 3 :
Writing a programe, to use the global keyword. Using global statement, we can modify or update the value of global variable x inside the function.
x = 10 # x is global variable.
y = 20 # y is a global variable.
def my_func():
# Modify the global variable inside the function using global statement.
global x # global statement.
x = x + 30
print(x)
print(y)
my_func()
Output
40
20
Explained in Detail
In the above program code, we have defined x as the global keyword inside the function my_func(). Then, we have incremented the variable x by 30, i.e. x = x + 30.
As we can see in the output while calling my_func(), the value of global variable x is modified from 10 to 40.
Example 1 :
x = 50
def showMe():
x = 60
print('Inside function, x =',x)
showMe()
print('Outside function, x =',x)
Output
Inside function, x = 60
Outside function, x = 50
Example 2 :
x = 10
def my_func1():
x = 20
print('Inside my_func1, x = %d'%x)
def my_func2():
global x
x = x + 30
print('Inside my_func2, x = %d' %x)
Output
x starts at 10
Inside my_func1, x = 20
After my_func1, x is now 10
Inside my_func2, x = 40
After my_func2, x is now 40
Explained in Detail
In this example, first we have defined a variable x and assigned a value 10 to it. Then, we have defined two functions my_func1() and my_func2().
In the my_func1() function, we have defined a variable x and assigned the value of 20 to it. This variable x has a local scope, which is strictly only for use within this function.
Inside the my_func2() function, we have defined a variable x with a global keyword. Since we have used global keyword, it refers to the global variable, not local scope.
Now anything happens to the variable x within the routine will change in the value of variable declared in the first line of code.
Now the code continues and will print the statement “x starts at 10”. Then, calls function my_func1(), which creates its own variable x, assigns the value 20 to it and prints the output.
When the program control comes back from that, it prints “After my_func1, x is now 10”. Next, we have called the function my_func2().
Since we have declared that variable x in the function is the global one, it gets changed to 40 and printed. On return from the function, it prints “After my_func2(), x is now 40”.
Example 3 :
Writing a program where global keyword within a nested function.
# Outer function.
def outer_func():
x = 30
# Inner function.
def inner_func():
global x
x = 60
Output
Explained in Detail
Here, we have declared a global variable inside the nested function inner_func(). Inside outer_func(), x has no effect of the global keyword. Before and after inner_func() function call, x takes the value of the local
variable, i.e. x = 30.
Outside the outer_func() function, x will take the value defined in the inner_func() function, i.e. x = 60. Because we have used the global keyword with x to construct a global variable inside the inner_func()
function (local scope).
Therefore, if we make any changes inside the inner_func() function, the changes will also appear outside the local scope, i.e. outer_func().
Chapter 6 :
Strings in Python
Here, we will learn about the meaning of mutable and immutable objects in Python.
We know that everything in Python is an object. For example, objects or relation between objects represent all the data in a Python program.
Every object in Python has three characteristics. They are:
Identity
Data type
Value
An object’s identity never changes once it has created. That is, it is unchangeable. It refers to the address of an object in the computer’s memory.
The is operator compares the identity of two objects and the id() function returns a unique identification value (as an integer) of the object stored in the memory. This unique identification value represents the
identity of an object.
An object’s data type refers to the type of object that is created. Integer, list, string, etc. are examples of an object’s data type. It also defines the types of values that an object can take.
Mutable and Immutable Object’s Value in Python
Object’s id and type cannot be changed once it has been created, only the value of some objects can change. There are two types of an object’s values or data in Python. They are:
The term mutable means changeable. An object that value or data can change during the execution of a program is called a mutable object or mutable data type. The values of a mutable object can
change after it has created.
In other words, we can change the value of a mutable variable after it has created. The examples of Python’s mutable data types are as:
List
Set
Dictionary
Bytearray
Array
The values of these data types in Python can change after their assignment or creation. When the value of a mutable object is changed, the Python interpreter does not reallocate its memory.
Example 1 :
Writing a program to demonstrate a list of a mutable data type in Python.
Output
Original list: ['cat', 'dog', 'goat', 'cow']
Id of original list: 1171325498496
List after appending a value: ['cat', 'dog', 'goat', 'cow', 'Buffalo']
Id of list after operation: 1171325498496
List after removing a value: ['cat', 'goat', 'cow', 'Buffalo']
Id after remove a value: 1171325498496
Explained in Detail
In the above program, we have created a list of values and performed multiple operations to demonstrate that a list is a mutable object whose values we can change.
Initially, we created a dummy list and printed the values of list and its id using id() function. Then, we appended a value to the current list, and printed the updated list and its id.
As you will notice, that list’s value has changed, but its identity remains the same (1171325498496). This shows that a list in Python is a mutable object whose values can be changed after creation.
Example 2 :
Writing a program in which we will change the value of a list by using assignment operator in Python.
# Creating a list of values.
list = [20, 40, 60, 80, 100]
print('Original list:',list)
print('Id of original list:',id(list))
Output
Example 3 :
Writing a program in which we will concatenate a new list into the old list using + operator.
Output
Explained in Detail
As you can observe in the above program code, list concatenation creates a new list with a new identity (i.e. new memory address). When it happens, the garbage collector removes the old list from the memory
because it is garbage.
Example 4 :
Writing a program to demonstrate a set of a mutable data type in Python.
Output
The term immutable means unchangeable. An object that value or data cannot change in its place after initialization or assignment during the execution of a program is called an immutable object or
immutable data type.
The values of an immutable object cannot change after it has created. In other words, we cannot change the value of an immutable variable after it has created.
Integers
Floating-point numbers
Boolean
Strings
Tuples
Frozen set
Bytes
The values of these data types in Python cannot modify after their assignment or initialization. When the value of an immutable object modify, the Python interpreter always allocates a new memory location.
Example 1 :
# Creating a string.
str = 'Hello'
print('Original string:',str)
print("Id:",id(str))
# Modifying the value in existing string, but Python will create new string object.
str = 'Good bye'
print('New string:',str)
print("Id:",id(str))
Output
Explained in Detail
From the above code, it seems that whenever we override the value of variable, it might look like we are changing the object’s value. Actually, it is not happening.
Here, we are not changing the object’s value from “Hello” to “Good bye”. Actually, the reference variable str has only switched to refer from the “Hello” object to “Good bye” object.
Both are two different string objects having two different identities. Both string objects have different memory locations or ids.
This shows that string is an immutable object, meaning that whenever we try to modify a string object’s value, Python interpreter always allocates a new memory location with a new address. It never changes the
string object’s value in the existing place. Attempting to modify the value of string is not allowed in Python.
Strings in Python are a sequence of characters, which consist of one or more letters, numbers, punctuation marks, and spaces.
For example, “Python” is a string which contains a sequence of six characters ‘P’, ‘y’, ‘t’, ‘h’, ‘o’ and ‘n’.
String is one of the most popular and useful data types in Python. Therefore, Python provides lots of features and functions for it.
In Python, strings are immutable objects of the built-in str class, which store the sequence of characters, called string.
To create strings or a string literal in Python, we must enclose it in either single (‘), double (“) or triple (”’ or “””) quotes and assign it to a variable. The general syntax to create or initialize a string is as:
<name of string> = "<value of string>"
Here, we have created a string variable named language and assigned it with a value “Python” in double quotes. Since a string is an array of characters, whenever we store a string into a variable, the first
characters always get placed at index number 0.
Look at the below figure to understand better where the first letter of ‘Python’ string has placed at index number 0, second at index number 1, and so on.
In Python, we can access individual characters of a string through index and a range of characters by slicing. An index is a number which denotes the position of elements.
From left to right, the indices start at 0, not 1. So, the first character of a string takes zero as its index number and succeeding characters take 1, 2, 3… and so on as index numbers. Index of the last character is
always (length of string – 1).
To access the characters of a string, just write the variable name and enclose the integer number inside the index operator or square brackets [ ].
Example 1 :
Writing a program in which we will access the characters of a string.
Output
String: Goodbye
First character of sting: G
Second character of sting: o
Third character of sting: o
Last character of sting: e
Explained in Detail
Indexing also allows negative address references to access the characters of a string from backwards (i.e. from right to left). For example, the last character takes -1 as its index, the second last character takes
-2 as its index, and so on.
Example 2 :
Writing a program on the taking negative index number for accessing characters of a string.
Output
String: Python
First character of sting: n
Second character of sting: o
Last character of sting: P
In Python, strings are immutable objects, meaning once we create it, we can no longer change it. That is, their values cannot be change or modified.
If we try to modify it either by taking a new value, or concatenating another string on the end, etc., Python interpreter will automatically allocate a new space in the memory for a new string object.
So, we cannot perform any changes with the existing string object in Python. This non-changeable behavior is nothing but a string immutability in Python.
Example 1 :
Output
Explained in Detail
In the above example program, it looks like we have assigned a string “Python” to a variable str of string type and then appended a string “Programming” to string str.
Thus, the string looks mutable in nature. In fact, it is not happening. When the operation str + “Programming” will be performed, a new string object will create and assign back to str, and deallocate the old string.
In other words, when Python will execute the statement str = str + ” Programming”, it will create a new string object in the memory for storing a new value.
To understand more it clearly, we have used a built-in id() function that returns the identity of an object. Look at the output that the memory address of string object before and after update is different. This shows
that we cannot modify or update the value in the existing string object.
3 Python String Length len() Function
In Python or other programming language, the length of a string is the total number of characters present in a string.
To find the length of a string, Python provides a built-in function named len().
This len() function returns the length of a string object or the total numbers of characters present in the string object. It counts all characters, numbers, and symbols enclosed in ” “.
Example 1 :
Writing a program in Python to find the length of a string using len() function.
Output
Length of string str is 6
Example 2 :
Writing a program to find the number of characters present in the string using len() function.
Output
Number of characters in the string "Python Programming" is 18
Example 3 :
Writing a program in Python to calculate the length of list, tuple, set, and dictionary using len() function.
Output
String concatenation means joining or combining two or more strings. Joining of two or more strings to make them one is called string concatenation in Python.
In general, Python provides (+) operator to concatenate multiple strings. We can concatenate two or more strings, or a string with a number or symbol to display information as per requirements.
For example, when you fill an online registration form, you fill your first name, middle name, and last name in three separate columns.
But when you finish the form, then you see your complete name as a single string. This is a realtime use of string concatenation in Python.
Example 1 :
Output
Explained in Detail
In the above example code, we have taken first name, middle name, and last name as inputs from the user using input() function and stored into variables named first_name, middle_name, and last_name,
respectively.
Then, we have concatenated all strings using (+) operator, stored in a variable named string_concatenation, and printed it on the console. Thus, we can combine several strings into one large string using the +
operator.
Using + operator
Using join() method
By using % operator
By using format() function
Using f-string (Literal String Interpolation)
Example 1 :
Writing a program to add multiple strings together to make them one.
# Python program to join three strings.
str1 = 'Python'
str2 = ' Programming' # string with a space.
str3 = ' Language' # string with a space.
Example 2 :
Output
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Explained in Detail
In the above example, we have used the (+) operator to concatenate two values of different data types. We are trying to join string data type with integer data type. Therefore, Python generates TypeError error.
Example 3 :
Writing a program to concatenate integer number with a string.
You first need to convert integer data type into string data type using str() function and then concatenate both string values.
Output
Joined string: 20twenty
Explained in Detail
In the above code, we have used str() function to convert an integer data type into string data type. This function returns a string version of object. If we do not provide any object, it returns an empty string.
Example 4 :
Writing a program to concatenate an integer type with string type without using str() function if you write integer type into string type.
Output
Joined string: 25twenty-five
Example 5 :
Writing a program by using multiplication operator (*) to repeat a string number of times
# Python program to repeat a string number of times.
str = 'Love' * 4 # Multiplying strings.
print('Repeated string:',str)
Output
Repeated string: LoveLoveLoveLove
Example 6 :
str1 = 'Python'
str2 = str1 * 2
print(str2)
str3 = (str2) * 2
print(str3)
Output
PythonPython
PythonPythonPythonPython
('Love', 'Python', 'Love', 'Python')
We can join strings by using join() method. This function provides a flexible way to concatenate strings. The general syntax for join() method is as:
string_name.join(sequence)
Example 1 :
dob = ["23","12","2016"]
my_dob = '/'.join(dob)
print('Date of birth:',my_dob)
Output
Explained in Detail
In this example, we have inserted a blank space between each sequence of string using join() function and stored returned concatenated string in the variable full_name.
In dob list variable, all the elements in the list are of string type. We have inserted ‘/’ between each of the list elements and stored the returned joined string into a variable my_dob and then displayed it on the
console.
Example 2 :
Output
day = 20
month = 'Oct'
year = 2002
dob = "% s % s % s" % (day, month, year)
print("Date of birth:",dob)
Output
Full name: John Smith
Date of birth: 20 Oct 2002
day = 12
month = 'Nov'
year = 2010
dob = "{} {} {}".format(day, month, year)
print("Date of birth:",dob)
Output
age = 34
print('Age:',f'{age}')
Output
In Python or any other programming language, string comparison means identifying whether or not two strings are equivalent to each other.
Basically, Python provides us three general ways by which we can compare between two strings. They are as:
Operator (==): This “equal to” operator checks whether or not two strings are equal.
Operator (!=): This “not equal” operator checks if two strings are not equal.
Operator (>): This “greater than” operator checks if the string on its left side is greater than that on its right side.
Operator (<): This “less than” operator checks if the string on its left side is smaller than that on its right side.
Operator (>=): This “greater than or equal to” operator checks if the string on its left side is greater than or equal to that on its right side.
Operator (<=): This “less than or equal to” operator checks if the string on its left side is smaller than or equal to that on its right side.
Example 1 :
Output
False
True
True
True
False
False
Example 2 :
# Python program to compare two strings using comparison operators.
print('abc' == 'abc')
print('abc' != 'abc')
print('a' == 'A')
print('a' != 'A')
print('abc' > 'ABC')
print('1234' > '4567')
Output
True
False
False
True
True
False
Example 3 :
Output
False
True
False
True
Example 4 :
str1 = 'abc'
str2 =' abc' # space before letters in the string.
print(str1 == str2)
print(str1 > str2)
print(str1 < str2)
print(str1 != str2)
Output
False
True
False
True
Output
True
True
True
False
False
False
Explained in Detail
In this example, str1, str2, and str3 are string objects with the same values. Therefore, they are equal, identical, and stored in the same memory location. Hence, ‘is’ identity operator returned true value and ‘is
not’ operator returned false value.
Example 2 :
str1 = '1234'
str2 = '1234'
if str1 is str2:
print('Both strings are identical.')
else:
print('Both strings are not identical.')
Output
Both strings are identical.
Example 3 :
str1 = 'abcd'
str2 = input('Enter a string "abcd": ')
print(str1 is str2)
str3 = 'pqrs'
str4 = input('Enter a string "pqrs": ')
print(str3 is not str4)
Output
Explained in Detail
In this example, the statement print(str1 is str2) returns false value because both are referring to the different string objects in different memory locations instead of having the same value.
Similarly, the statement print(str3 is not str4) returns true value because both are referring to the different string objects in different memory locations instead of having the same value.
for i in range(len_str1):
if str1[i] >= "0" and str1[i] <= "9":
count1 += 1 # increment by 1.
for i in range(len_str2):
if str2[i] >= "0" and str2[i] <= "9":
count2 += 1 # increment by 1.
return count1 == count2 # comparing.
# Mian program.
# Calling function by passing argument values.
print(string_comp("1234", "1234"))
print(string_comp('345', '1234'))
print(string_comp('Programming', 'Programming'))
Output
True
False
True
A sub-part of the original string is called substring. It is any sequence of characters which already exists in the original string.
With string slicing, we can access a range of characters in a string or create substring.
Example 1 :
Output
Substring: Lang
Explained in Detail
In the above code, we have obtained a substring of four characters starting from 0 to 4. The square brackets ([ ]) is an array operator. The first index is inclusive and the last index is exclusive. So, 0:4 means 0 to
3 sequence of characters, not 4th character. Look at the below figure to understand string slicing better.
Ways to Perform String Slicing in Python
There are basically two ways to perform string slicing in Python. They are as:
Python provides a built-in function named slice() that we can use to obtain a slice (i.e. subpart) of elements from the collection of elements.
This function returns a slice object we can use to slice strings, lists, tuples, sets, bytes, or range objects. Python language provides two overloaded slice() functions.
The first function takes a single formal parameter ‘stop’ index, while the second function takes three formal parameters ‘start’ index, ‘stop’ index, and ‘step’ value as well.
slice(stop)
slice(start, stop, step)
Parameters:
(a) A start parameter specifies the starting index at which the slicing of string object begins.
(b) A stop parameter specifies the ending index where a string object’s slicing comes to a halt. The slice() function excludes the stop index while generating the substring. That is, the slice() doesn’t stop ‘at’ or
‘after’ the stop index. It stops just before this index when performing slicing.
(c) A step parameter is an optional parameter that specifies the increment between each index for slicing. It basically refers to the number of characters that we can skip after start indexing character in the string.
If you pass only one parameter, start and stop parameters are considered to be None.
Example 1 :
# This statement starts the slice object at position 11 and slice up to position 21 and returns the result.
my_sub2 = slice(11, 21) # returns slice object.
print('my_sub2 object:',my_sub2)
print('Substring from 11 to 21 :',string[my_sub2])
# This statement uses the step parameter to return every second element.
my_sub3 = slice(0, 20, 2)
print('Substring containing every second elements:',string[my_sub3])
Output
my_sub1 object slice(None, 7, None)
Substring from 0 to 7: Welcome
my_sub2 object: slice(11, 21, None)
Substring from 11 to 21 : Programme
Substring: Wloet cetc
We can obtain a substring of an original string using slice operator. It is an easy and convenient way to slice a string. To slice or access a range of characters in a string or create a substring, use the slice operator
[:].
The general syntax for slicing string is as:
string_name[start:end[:step]]
In the above syntax, a colon specifies the range of value. It also separates the two indices. We can access the substring within an original string by specifying a range of index number by colon.
This slice syntax returns the sequence of characters beginning at the start index and extending up to but not including the end index. The start and end values should be an integer. We can perform string slicing
operation using either positive or negative indexing.
Example 1 :
Writing a program in which we will perform string slicing operation using range slice operator.
Here, we will create a variable named healthy_juice and assign it with a string value “Tomato juice”. The sequence of characters of this string will be index, starting from 0, and so on, as shown in the below figure.
# Python program to demonstrate the string slicing using range slice operator.
# Original string.
healthy_juice = 'Tomato juice'
print('Original string:',healthy_juice)
# This statement starts to slice string at position 0 and slices up to position 4 and returns the result.
my_sub1 = healthy_juice[0:4]
print('Substring from 0 to 4:',my_sub1)
# This statement starts to slice string at position 0 and slices up to position 6 and returns the result.
my_sub2 = healthy_juice[:6]
print('Substring up to 6:',my_sub2)
# This statement does not slice the string and displays the entire string.
my_sub4 = healthy_juice[:]
print('Entire substring:',my_sub4)
Output
Explained in Detail
In the above example program, we have created a variable named healthy_juice and assigned a string “Tomato juice”.
(a) In my_sub1, we have sliced the original string from the position 0 up to position 4 and stored the returned result in a variable my_sub1.
(b) In my_sub2, we have not included the start index number. Therefore, slicing starts from position 0 and goes up to index number 6. We have stored the returned result in a variable my_sub2.
(c) In my_sub3, we have not included the stop index value. Therefore, slicing starts at position 6 and slices the original string up to the end of string index.
(d) In my_sub4, we have not omitted the start and stop index value. So, the entire string will display.
(e) If the start index number is equal to or higher than end index number. In my_sub5, the start index number is equal to end index number. Therefore, it displays an empty string.
(f) In my_sub6, the end index number is beyond the end of string. Therefore, it stops at the end of string.
Since a string is a sequence of characters, we can iterate or traverse each character of the string. This process is called traversing or iteration.
There are basically three ways to iterate over characters of a string in Python. They are:
Example 1 :
Writing a Python program in which we will iterate or traverse over each character of a string using for loop.
Output
Google
Y
a
h
o
o
Explained in Detail
In this example program, we have used end= ‘ ‘ in the print() function. By default, the print() statement ends with a newline character (\n). The function of end parameter is to change default behavior of print()
statement in Python.
The parameter end = ” ” in the print() function is to place a white space after each character of a string while iterating. Thus, the the print() function ends with white space, not a newline.
The for loop iterates over each character of a string and prints each letter on a separate line.
Example 2 :
Writing a Python program in which we will iterate over the index of characters of a string using for loop.
Output
Google
Example 3 :
Writing a program in Python to iterate through each character of a string using while loop.
Output
Python Programming
Example 4 :
Writing a program in Python to traverse over a string using enumerate() function.
Output
Instagram
Example 5 :
Output
In the string 'Python'
Character 'P' has an index value of '0'
Character 'y' has an index value of '1'
Character 't' has an index value of '2'
Character 'h' has an index value of '3'
Character 'o' has an index value of '4'
Character 'n' has an index value of '5'
Explained in Detail
In this example, we have created a string “Python” and assigned it in a variable named language. We have initialized the index variable with a value zero. We have used a for loop that make it easy to loop or
iterate over each character of a string.
The index value is incremented by a value of one when each character traversed in the string. We have displayed each character of the string and its corresponding index value.
In Python, we can also traverse or iterate over each word of a string. A string can consists of several words separated by a white space. There are two methods to iterate over words of a string in Python.
They are:
Example 1 :
Writing a program in Python to iterate over each word of a string using split() function.
Output
Explained in Detail
In this example, we have used split() function to traverse over each word a string. This function splits the string into a list of words, but it fails if a string contains punctuation marks, such as question mark,
exclamation point, comma, colon, semicolon, etc. To overcome this issue, use re.findall() function.
Example 2 :
Writing a program to iterate over each word of a string using re.findall() function.
Output
In the string 'I love Python programming.'
Words of string are as:
I
love
Python
programming
Here is a table of all the symbols that we can use alongside % to format string.
Example 1 :
Use of %s operator
age = 22
print('My age is %s'%age)
Output
My age is 22
Explained in Detail
%s is used to convert any type of value into string format. Here, we have used %s to insert or put the value of variable age into a string. The %s is replaced by the argument value and print it.
Example 2 :
first_name = 'John'
last_name = 'Harry'
print('My name is %s %s'%(first_name, last_name))
Output
My name is John Harry
Explained in Detail
In this example, the (first_name, last_name) is a tuple and the complete expression is transformed into a string with the help of %s. The first %s is replaced by the value of “first_name” and the second %s is
replaced by the value of “last_name”. All the other characters in the string stay as they are.
Example 3 :
Usage of %i and %d
num1 = 20.456
num2 = 30.5768
print('First number is %i'%num1)
print('Second number is %d'%num2)
Output
First number is 20
Second number is 30
Explained in Detail
We can also perform string formatting with integer by using %i or %d instead of %s. In the above example, we have assigned the values of num1 and num2 in the form of decimal, but formatting string %i and %d
print only the integer part of the variable’s value.
Example 4 :
Usage of %f or %F
per1 = 80.4567
print('My first term percentage is %f' %per1)
per2 = 80.4546
print('My second term percentage is %.2F' %per2)
Output
Example 5 :
Usage of %x and %o
num = 27
print(f"Hexadecimal representation of {num}: %x" %num)
print(f"Octal representation of {num}: %o" %num)
Output
Hexadecimal representation of 27: 1b
Octal representation of 27: 33
Example 1 :
Output
Explained in Detail
In this example, we have taken the name of user as input by using input() function and stored in the variable my_name. Then, we have called the format() method on the string literal with passing the value of
my_name which are interpolated, in order, into the locations of replacement fields, indicated by empty curly braces, ({ }).
Example 2 :
name = "John"
age = 22
id = 23424
print("Name: {}, Age: {}, Id: {}".format(name, age, id))
Output
Name: John, Age: 22, Id: 23424
Example 3 :
name = "Bob"
age = 22
id = 35465
print("{} {} {}".format(name, age, id))
Output
Bob 22 35465
Example 4 :
n1 = "Mark"
n2 = "John"
n3 = "Harry"
# Default order.
print("Students by default order: ")
print("{}, {}, {}".format(n1, n2, n3))
Output
Example 5 :
n1 = "Mark"
n2 = "John"
n3 = "Harry"
print("Students by default order: ")
print("{}, {}, {}".format(n1, n2, n3))
Output
Python 3.6 has introduced a new string formatting mechanism called f-strings (short for formatted string literals). This mechanism is quite cool and is faster than using format() method and % formatting. It provides
a more convenient way to create formatted strings.
An f-string is a string literal, prefixed with ‘f’, which contains expressions inside the pair of curly braces ({ }). To create an f-string, first write the character f immediately preceding a string literal.
Within string literal, enclose expressions in the pair of curly braces to put the value of expressions into the formatted string. The general syntax to create formatted string literals in Python is as:
f"string_statements {variable_name [:{width}.{precision}]}"
Example 1 :
name = "Harry"
age = 22
sName = "RSVM"
print(f"{name}, {age}, {sName}")
Output
Harry, 22, RSVM
Example 2 :
name = "Harry"
age = 22
print(f"Hello! My name is {name} and I'm {age} years young.")
Output
Hello! My name is Harry and I'm 22 years young.
Example 3 :
Arithmetic operations using f-strings
n1 = 23
n2 = 45
n3 = 55
print(f"Sum of three numbers = {n1 + n2 + n3}")
Output
Sum of three numbers = 123