You are on page 1of 48

3

INTRODUCTION TO PYTHON
3.1 PYTHON OVERVIEW
Python is an open source, interpreted, object oriented, general purpose high-
level programming language. It was developed by Guido van Rossum in the late 1980s at
the National Research Institute for Mathematics and Computer Science in the Netherlands, as
a successor to the ABC programming language. The first version of Python 0.9.0 was released
in 1991. The next important version of Python was Python 2.0 which was released in year 2000.
Python 3.0 was released in year 2008. The last version of Python 2 was Python 2.7.18. After
this version Python 2 was discontinued in the year 2020. At present the latest version of Python
is Python 3.10.0.
Python can be downloaded from the official website of Python : www.python.org

3.2 PYTHON FEATURES


A few important features of Python are as follow :
1. Easy to use and learn
Python is easy to use programming language. It’s syntax is very simple and easy to learn. It
has removed the use of brackets, semicolons etc. Even there is no use of main function in this
language. It’s syntax is similar to English. Due to its simplicity, it is a recommended language
for the beginners.
2. Free and Open Source
Python is a free and open source programming language. Anyone can participate in the
development of Python. A large community of software developers is continuously involved
in the development of the Python. The use and redistribution of Python is free and legal.
3. Platform independent Language
Python is platform independent, it can be used on various hardware and software platforms
such as such as Windows, Linux, Mac, Solaris, iOS, Raspberry Pi etc.

4. Interpreted Language
Python is an interpreted language, It means python code is interpreted and executed one line a
time due to this the debugging of the programs is easy moreover the programs are easily
portable because there is no need to create .exe file of the code (.exe files are platform
dependent).
5. Large Library Support
Python has a large standard library apart from this it a vast range of specific libraries for the
various fields such as data science, machine learning, scientific computing, database, web
development etc. A few important libraries supported by Python are : Matplotlib, Pandas,
NumPy, Requests, SQLAlchemy, SciPy , PyGame etc.

6. Object-Oriented Language
Python supports the concepts of object-oriented language such as objects, classes, inheritance,
polymorphism, encapsulation etc. Which make it suitable for solving real world complex
problems in an easier manner.
7. Expressive Language
Python is an expressive language, it’s code is very simple, for example the statement 23+90
will be written to find the sum of 23 and 90 which is similar to our natural language. Also to
display message: Welcome to Python, We will write python statement print (“Welcome to
Python”) which is very easy to understand and expressive.
8. GUI Programming Support
Python support graphical user interface development programming. Tkinter, JPython, Kivy,
PyQT5 etc. are the libraries which support many features to develop GUI applications for
desktop and web.
9. Dynamically typed language
In Python, we don't need to specify the data-type of the variable. We can directly assign values
to the variables, the datatype to the variables is automatically assigned by Python. e.g. subject=
“Computer Science” will automatically set the datatype of the subject variable to string.
10. Embeddable
The code of the other programming languages such as C, C++, Java can use in the Python
source code. We can use Python source code in another programming language as well. It
provides the programmers a facility to get the benefits of features of various programming
languages simultaneously.
3.3 Applications of Python :

Python language can be used for creating various types of application , a brief description about
the applications of Python is as follow:
1. Artificial Intelligence and machine learning
Python is such a stable, flexible, and simple programming language. Python has many library
packages related to machine learning and Artificial intelligence.
2. Data analytics
In the present scenario a huge amount of data is getting produced every day and the role of data
analytics has become very important. Python has many dedicated packages to related to data
science and analytics which are useful for manipulating data and deriving useful conclusions.
3. Programming applications
Python can be used as a general-purpose programming language. We can create all kinds of
applications such as GUIs, database related application, web applications, video games and
many more.
4. Web development
Python is a great choice for web development. There are many Python web development
frameworks such as Django, Pyramid, and Flask which allow programmers to create websites
and web apps easily.

5. Language development
The simple and elegant design of Python and its syntax has inspired the creation of new
programming languages such as Cobra, CoffeeScript, and Go.This fact also means that Python
is a useful gateway language. So, if you’re totally new to programming, understanding Python
can help you branch out into other areas more easily.

6. Finance
Python is increasingly being utilised in the world of finance, often in areas such as quantitative
and qualitative analysis. It can be a valuable tool in determining asset price trends and
predictions, as well as in automating workflows across different data sources.

3.4 INSTALLING PYTHON


Python is available for a wide variety of platforms such as Windows, Linux, macOS (Fig 3.2).
Also there are various versions available for download. We can download the desired Python
version from for the specific platform from the downloads section in official website of python
i.e. www.python.prg.

Here we have shown the installation of Python for Windows 10 OS.


Windows Installation

To find the various releases available for download for Windows OS, select the view full list
for downloads option.

Fig. 3.3

Here we are downloading the latest version of the Python 3.10.0, for this click on download
link of download link of Python 3.10.0. After downloading , run the setup for installation.

Fig 3.4
Follow the instruction during installation process, installation process will be completed auto
matically after installation of all the components of Python.

3.5 ELEMENTS OF PYTHON:


After the successful installation of Python we can use Python on our device. To open Python
click on start button and search for Python 3.10.0 in the list installed softwares and click on it.
Here we will find 4 modules or elements.
1. IDLE Shell (Python 3.10) - IDLE is Python’s Integrated Development and Learning
Environment. It is GUI based shell through which programmers can write, save, run
and debug programs. Fig 3.5.
IDLE has the following features:
 coded in 100% pure Python, using the tkinter GUI toolkit
 cross-platform: works mostly the same on Windows, Unix, and macOS
 Python shell window (interactive interpreter) with colorizing of code input, output,
and error messages
 multi-window text editor with multiple undo, Python colorizing, smart indent, call
tips, auto completion, and other features
 debugger with persistent breakpoints, stepping, and viewing of global and local
namespaces

Fig 3.5
2. Python (Python 3.10) Command Line Shell- Python can also be accessed from the
command line. Command based shell is an interpreter which accept, translate and
execute one statement python statement at a time. To use python shell in an effective
manner programmer should have the knowledge of command line syntax and options.
Command line mode is fast in comparison to IDLE.

Fig 3.6
3. Python 3.10 Manual- This element contatin various types of documentations for the
users so that they can understands and use Python easily. The few examples of
documentation given in this component are : Python setup and usage manual, Python
Tutorial, FAQ, Python standard library, Installing Python modules, dealing with bugs,
History and License, copyrights etc.

Fig 3.7
4. Python 3.10 Module Docs- This component allows us to access the documentation
regarding the detailed information of the python modules, dynamic link libraries
(DLLs) and Packages etc.

Fig 3.8
3.6 PYTHON INTERPRETER

Python is a high-level programming language, which provide programmers ease to write programs to
solve problems through computers. But we know that computer understand machine language or binary
language only. So, program written in Python must be translated to machine language before executing
it by the system. To translate high level language programs to machine language we can use one of the
system software : compilers or interpreters. Here is a brief information about these.

S.N Interpreter Compiler


1. It scans and translates one statement of the It scans the entire program and translates the
program at a time. complete program as a whole.
2. Interpreters do not generate intermediatory Compilers generate intermediatory code
object codes, so they are efficient in term of known as object code, thus they consume
memory requirements. more memory in comparison to interpreters.
3. The overall execution time of the program The overall execution time of the program
using interpreters is slower than compilers. using compilers is faster.
4. Debugging using interpreter is easier because Here the complete program is checked for
the program is executed by interpreter line by errors as a whole and executed as a whole so
line till there is no error. debugging is relatively difficult.
5. Examples of Programming languages which Programming languages like C, C++, Java,
uses interpreter: Python, PHP, Perl, FORTRANT use compilers.
MATLAB, Ruby use interpreters.

Working of interpreter and compiler


3.7 PYTHON SHELL
Shell is an interface through which programmers can write, debug , execute programs and also
see the results obtained after the execution. There are two types of shells in the Python :
command line based and GUI based. We have briefly discussed these in the topic elements of
Python. The programmer write program code the shell, the shell is first checked for the errors
if no errors are found then that statement is translated into the machine language by the
interpreter and the machine code is then executed by the system. The output obtained after
execution is send back to the shell so that programmer/user can see the results. Let’s understand
the basic working of Python shell by using it as a calculator.
Python as a calculator
Python shell can be used as a calculator. To use Python as a calculator open Python command
line or IDLE and use it as a calculator as shown in the examples given below.
Example: By using IDLE

Example: By using Command line

3.8 PYTHON SYNTAX RULES


1. Python is case sensitive. Hence a variable with name first_number is not same
as First_Number
2. For path specification, python uses forward slashes. Hence if you are working with a
file, the default path for the file in case of Windows OS will have backward slashes,
which you will have to convert to forward slashes to make them work in your python
script. For window's path C:\folderA\folderB relative python program path
should be C:/folderA/folder.
3. In python, there is no command terminator, which means no semicolon ; or anything.
So if you want to print something as output, all you have to do is: print"Hello, World!"
4. In one line only a single executable statement should be written and the line change act
as command terminator in python.
5. To write two separate executable statements in a single line, you should use
a semicolon ;to separate the commands. For example,
print"Hello, World!";print"This is second line"
6. In python, you can use single quotes '', double quotes "" and even triple quotes '''
""" to represent string literals.
word ='word'
sentence="This is a one line sentence."
para ="""This is a paragraph
which has multiple lines"""
7. In python, you can write comments in your program using a # at the start. A comment
is ignored while the python script is executed.
# this is a comment
print"Hello, World!"
# this is a
# multiline comment
8. Line Continuation: To write a code in multiline without confusing the python
command line interpreter is by using a backslash \ at the end of each line to explicitly
denote line continuation. For example,
sum =123+ \
456+ \
789
9. Expressions enclosed in ( ), [ ] or { } brackets don't need a backward slash for
line continuation. For example, vowels=['a','e','i',
'o','u']
10. Blank lines in between a program are ignored by python.
11. Code Indentation: This is the most important rule of python programming. In
programming language like Java, C or C++, generally curly brackets { } are used to
define a code block, but python doesn't use brackets, then how does python knows
where a particular code block ends. Well python used indentation for this. It is
recommended to use tab for indentation, although you can use spaces for indentation
as well, just keep in mind that the amount of indentation for a single code block should
be same.
If True:
print"Yes, I am in if block"
print “me too”
# the above statement will not be
# considered inside the if block
the correct way would be,
if True:
print"Yes, I am in if block"
print"me too"
So these are some basic rules that you must know so that it becomes easier for us to
learn various concepts of python programming.

3.9 GENERAL STRUCTURE OF PYTHON PROGRAM


A Python program can contains various sections.

No Sections Description
1 Documentation We can give comments about the program, creation or modified
section date, author name etc. in this section. This section also includes
the comments about the programs. Comments improve the
readability of the program. Comments are only for the
programmer and are ignored by the compiler. Comments can be
of two types in Python language:
Single Line Comments: As clear from name these comments are
only of single line and placed after # sign.
For example: # to calculate Area and perimeter of a Rectangle
Multiline Comments: If the comments are of more than one line
than comment is called multiline. It is a special comment
enclosed in triple quote marks that can spread over several lines.
Every program should have a short description of what it does.
For example:- """Author: Dr. Chaman Singh ,
Program: To find area and perimeter of a
rectangle with length and width """
2 import Section Various Modules that are required to execute a Python program
are included in this section. This section includes link to all
modules. This section we provide instructions for linking
different functions from the system library to the interpreter. This
section is also known as Pre Processing stage, because this will
run before the main program at the time of execution. The section
name starts with ‘from’. Here we included two modules one is
math used to mathematical calculations and other is Tkinter for
Graphics applications:-
from math import *
from Tkinter import *
3 Global Global variables are defined in this section. When a variable is to
declaration be used throughout the program, can be defined in this section.
section This is not compulsory section.
Example:- global Area, Radius, Perimeter
global Arc
4 Main Program Main is the entry point of any program. Every Python program is
started from main program part contains executable section. It
indicates the starting of program. Executable section means
Python code of algorithms steps is included in this part. This
section also called to other sub program called functions. Also
contains input and output statements.
width = 5
height = 3
Area=width*height
Perimeter=2*(width+height)
print "Area = ", area
print "Perimeter = ", perimeter
#Input from keyboard
width = eval(input('Enter Width of the Rectangle: '))
height = eval(input('Enter Height of the Rectangle: '))
# function calling below
print "Area = ", area(width, height)
print "Perimeter = ", perimeter(width, height)
5 User defined User can define their own functions in this section which perform
function particular task as per the user requirement. They called from main
section program. All the user defined functions are written after or before
(Subprogram the main program. Eg:- area() and perimeter() are defined as:-
section) # function definitions
def area(b, h):
A=b*h
return A
def perimeter(b, h):
P = 2 * (b+h)
return P

3.10 INPUT AND OUTPUT STATEMENTS


Input statement : In Python we can receive inputs from the user by using the input function.
Input function has following syntax:
input()
we can put a string message inside input() so that user get a message regarding the input
information e.g.
input( 'Enter your favourite subject : ')
output: Enter your favourite subject : computer science
Input function returns a string, which can be stored in a variable. E.g.
fav_sub=input( 'Enter your favourite subject : ')
output: Enter your favourite subject : Computer Science
To read a value other than string type we have to use the type casting with input function e.g.
to read an integer we will use int() e.g.
num= int(input('enter a number '))
output : enter a number 34
Similary to read a floating point number we can have to use float() with input function.
To read multiple values using input we can use split function with input. The syntax to use
split() is as follow.
name, rollno = input("Enter your name & rollno ").split()
output : Enter your name & rollno Rajeev CS001
We can also read an expression by using input and can evaluate it by using eval(). Here is
an example.
x= eval(input('Enter the expression you wish to calculate : '))
output : Enter the expression you wish to calculate : 2*7+6/8-2
Output Statement: To display output in Python we use print() function.
Here is a simple example:
print(' Welcome to Python Learning')

The print function requires parenthesis around its arguments. In the program above, its only
argument is the string ' Welcome to Python Learning '. Anything inside quotes will (with a few
exceptions) be printed exactly as it appears.
The print function can also display the values of variables, expressions. For this we will write
variable name, expression outside the quotes.
Example 1:
subject= 'Python'
print('My favourite subject is ', subject)
Output: My favourite subject is Python

Example 2:
num = 5
print('Square of ', num , ' = ', num*num)
output : Square of 5 = 25

Optional arguments
There are two optional arguments to the print function. sep and end.
sep is used to specify the separator character between the arguments values passed to the
print().

print('Welcome','To','Python', sep='-')
output : Welcome-To-Python

print('cs','python.org', sep='@')
output : cs@python.org

end : print function automatically advance to the next line after displaying the values. For
instance, the output of following lines of code will be displayed on two lines:
print('Welcome to python')
print('Learners')

output:- Welcome to python


Learners

We can use end argument to assign a different value to end the print statement. We can
understand this with the help of following examples.
print('welcome to python', end=' ') # here space is inserted at the end
print('learners')

output: welcome to python learners

print('welcome to python', end='STUDENTS ') # here STUDENTS is added at the end


output: welcome to python STUDENTS

3.11 PYTHON CHARCTER SET


As English language is consisting of A-Z and a-z, similarly Python consists of following
characters which is known as python character set.
1. Letters 2.Digits 3.Special Characters
Letters: - Python comprises A to Z in capital letters and a to z in small letters.
Digits: - Python Language comprises the numbers to associate the letters. 0 to 9 digits.
Special Characters: - The various characters like +,-,*,/,%,(,),<,>,=,!,^,~,”,: etc.
3.12 PYTHON IDENTIFIERS
A Python identifier is a name used to identify a variable, function, class, module or other object.
It is similar to the name given to the persons, institutes, items etc. in real world. In Python the
identifier can contain alphabets A to Z or a to z, digits (0-9) and underscore (_). The rules to
create to create an identifier are as follow :
1. The allowed characters are a-z, A-Z, 0-9 and underscore (_)
2. It should begin with an alphabet or underscore
3. It should not be a keyword
4. It is case sensitive
5. No blank spaces are allowed.
6. It can be of any size
Examples :
Valid Identifiers : num1, b_2, age, _name , emp_id01 , first_number , date_of_birth
Invalid Identifiers : first number, 1stu, name@1, #emp_5 , def
Here are naming conventions for Python identifiers −
1. Variable name and Function names should be lowercase, with words separated by
underscores to improve readability.
2. Constants should be written in uppercase separated by underscore.
3. Class names start with an uppercase letter.
4. Starting an identifier with a single leading underscore indicates that the identifier is
private.
5. Starting an identifier with two leading underscores indicates a strongly private
identifier.
3.13 RESERVED WORDS (Keywords in Python)
Keywords are reserved identifiers that have predefined strict meaning to the Python compiler.
Keywords are also known as reserved words. These are reserved words and you cannot use
them as constant or variable or any other identifier names. There are 36 keywords in Python
language.
To view the keywords in Python, type help() in the Python shell then type keywords in help
prompt.
The list of keywords in Python is as follow :-

We can find the detail about any keyword by typing the name of keyword in the help
prompt.
3.14 VARIABLES
Variable is a data element in the program which has a name, which can have a value, and whose
value may change during the execution of the program. When a variable is created , memory
location for that variable is allotted to that variable. Variable name act as a reference to that
memory location i.e, program can use that memory location with the help of variable name.
Example

Here we have 3 variables P,R,T. These variables may be present in memory at any location.
Suppose the memory location allotted to P is 1050, the memory location allotted to R is 1000,
and the memory location allotted to T is 1150. Then we can access and manipulate the data
stored in these locations by using P,R,T respectively.
In short python variable has a name, it store a value and it refer to a specific memory location.
The variable naming rules in Python are as follow :
1. Variable name can be of any size
2. Variable name can contain characters, which are a-z, A-Z, 0-9 and underscore (_)
3. It should begin with an alphabet or underscore
4. should not be a keyword

It is a good practice to follow these identifier naming conventions:

1. Variable name should be meaningful and short


2. Generally, they are written in lower case letters

Assigning values to a variable


The equal sign (=) is used to assign values to variables.

e.g

stu_name= “Rajat Kumar”

age = 20

Python also allows to assign a single value to several variables simultaneously. For example
a=b=c=1
Here, an integer object is created with the value 1, and all three variables are assigned to the
same memory location. You can also assign multiple objects to multiple variables. For
example −
a,b,c = 1,2,"Python"
Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively, and one
string object with the value "Python" is assigned to the variable c.

3.15. How to write, save and execute Python Program


We can create a python program file by using Python IDLE shell, to create Python program
file follow these steps:
1. Open Python IDLE shell
2. Create a new file by using FILE menu ->New or press Ctrl+n

3. Now, write the code of the program in the program file. For example we want to write a
simple program to display “Welcome to Python Programming”. Write following code.
print("Welcome to Python Programming")

4. Choose File->Save to save the file. Specify the filename, location where you want to save
file. The extension of Python program file is .py
5. To run program select run->run module option or press F5
6. The result of the program is shown on IDLE shell.
EXERCISE:-Some important questions to be asked in Examination:-
[1] Discuss the various feature and uses of Python.
[2] What is Python Interpreter? How it works?
[3] What do you understand by shell ? Discuss the Python shell in brief.
[4] Discuss Python Program Structure and Write Python Syntax Rules?
[5] How input and output is done in Python Program?
[6] What is a variable ? Discuss the variable naming rules.
[7] What do you understand by keywords ? Explain with example.
[8] Differentiate between interpreter and compiler .

Few Very Short Answer Type Questions

[1] What do you understand by Shell ?


[2] Which statement is used to give output to the user in Python ?
[3] Python is compiled language. True/False
[4] Variable name can have any size in Python. True/False.
[5] Python is high level, object oriented, interpreted general purpose programming
language. True/False.
[6] Python is a proprietary programming language. True/False.
[7] Python is loosely typed language. True/False.
[8] ________ statement is used to add library package in the program.
[9] The extension of Python program is ________.
[10] Python has two main versions _______ and ________.
4
DATA TYPES, OPERATOR

4.1 DATATYPES

A data type is a classification of data which tells the compiler or interpreter how much
memory will be allotted for that data element, what can be stored in that and which operations
are allowed on that data element.

There are following native data types in Python.


1. Numbers
2. Strings
3. Lists
4. Tuples
5. Dictionaries

1.Number : Number data type stores Numerical Values for example 34, 75.2, -2300 etc. The
example of the numeric data are : age, salary, rate of interest etc.

These are of three different types:

a) Integer
b) Float
c) Complex

Integers are the whole numbers consisting of + or – sign like 100000, -99, 0, 17.
There is no size limit of integer.

Examples :
age=19
salary=20000

Float: Numbers with fractions or decimal point are called floating point numbers. A
floating point number will consist of sign (+,-) and a decimal sign(.)

e.g. temperature= -
21.9,
growth_rate=
0.98333328

The floating point numbers can be represented in scientific notation such as

-2.0X 105 will be


represented as -2.0e5
2.0X10-5 will be 2.0E-5
Examples :
x = 30e5
y = 15E8
z = -56.9e15

Complex: Complex number is made up of two floating point values, one each for real
and imaginary part. For accessing different parts of a variable x we will use x.real and
x.imag. Imaginary part of the number is represented by j instead of i.

Example
x = 1+0j
>>> print
x.real,x.i
mag
output :
1.0 0.0

None : This is special data type with single value. It is used to signify the absence of value/false
in a situation. It is represented by None.

2.Sequence
A sequence is an ordered collection of items, indexed by positive integers. Five types of
sequence data type available in Python are Strings, Lists, Tuples, Set and Dictionary. We will
learn about these in detail in Chapter no.

2.1String: is an ordered sequence of letters/characters. These datatype is used to store


alphanumeric data elements e.g. name of student, project no., subject code, address etc. We
can create single line strings by using quotes (‘’) or double (“”).

Example

a = 'Computer Science'
b= “Computer Science”

multiline strings are created by using triple quotes


example
a=‘‘‘ Welcome
to Python String
Learning ’’’

Note : Python automatically assign the datatype to a variable when we assign a value to it.
e.g. A=12.4 is a float , B= ”Computer Science” is a string. Programmers can explicitly specify the
datatype of a variable by using casting. Casting in python is therefore done using constructor
functions: int(), float(), and str() for creating integer, float and string respectively.

Examples :

x = int(5) # x will be 5
y = int(4.7) # y will be 4, here float is converted into int
z = int(“3”) # z will be 3, here string is converted into int

x = float(6) # x will be 6.0, here integer is converted into int


y = float(2.8) # y will be 2.8
z = float("3.2") # z will be 3.0, here string is converted into int

2.2 Lists: List is a used to store the collection of data elements of any type. The items of
list are accessed with the help of index (index start from 0).
List elements are written inside square brackets [ ].

Example
student = [“Ajay”, 567, “CS”]
print(student[0])
print(student[1])
print(student[2])
print(student[0:3])
output : Ajay
567
CS
[‘Ajay’, 567, ‘CS’]
2.3 Tuples: Similar to lists Tuples are used to store the collection of elements of any type. a
sequence of values of any type, they are also indexed by integers similar to lists. The only
difference between lists and tuples is that tuples are immutable i.e. we cannot change the
value of items of tuples.

Tuples are created by using round brackets ().

Example :

student = (“Ajay”, 567, “CS”)


print(student[0])
print(student[1])
print(student[2])
print(student[0:3])
output : Ajay
567
CS
(‘Ajay’, 567, ‘CS)
If we try to change the elements of tuple, then error will be raised by Python.
e.g. student[0]= ’Sumit’ # Error: This operation is not be allowed on tuples

2.4 Sets
Set is an unordered collection of values, of any type, with no duplicate entry. Sets are
immutable.
Set is created either by using the set([ ]) constructor or by using the { } brackets
Example
set1 = set ([1,2,3,4])
set2 ={1,2,3,4}

2.5 Dictionaries: Dictionaries store a key – value pairs, which are accessed using key. A
dictionary element is non immutable and also dictionary does not allow duplicate values.
Dictionary elements are enclosed in curly brackets.
Example
d = {‘stu1’:'Raman', ‘stu2’:'Sumit', ‘stu3’:'Kajal'}

here stu1,stu2,stu3 are keys and Raman, Sumit and Kajal are values. The elements of the
dictionary are accessed by using key values. e.g.
print(d[‘stu1’]) # it will print Raman

4.6 LITERALS
Literal is a raw data given in a variable or constant. In Python, there are various types of literals
they are as follows:
1. Numeric Literals
Numeric Literals are immutable (unchangeable). Numeric literals can belong to 3 different
numerical types Integer, Float and Complex.
Integer literals are signed number without decimal points. For example, 1000, -45, +39 etc.
We can also write integer literals in binary, octal and hexadecimal notation. e.g.
0b1010#Binary Literals
0o310#Octal Literal
0x12c#Hexadecimal Literal
Float literals are signed real numbers having both integer part and fraction part. We can also
write float literals in exponent form. e.g.
10.5
1.5e2
Complex literals has real and imaginary part. They are written in the form of a+bj , here a is
real part and b is the imaginary part of complex literal. e.g.
3+14j, -52+3j
2. String literals
A string literal is a sequence of characters surrounded by quotes. We can use single, double or
triple quotes in a string literals. e.g.
‘Welcome to Python’
“Welcome to Python”
The examples given above are single line string literals.
Multiline string literals : The string literals can also spread in multiple lines these are called
multiline string literal. To create multiline string literal use \ after every line. e.g
“Welcome to\
Python learning\
Students”

Triple quotes are used when the literal has multiple lines :
“””Welcome
To
Python”””
We can easily understand different forms of Python string literals with the help of
following examples.
>>> print('welcome to Python')
Output : welcome to Python
>>> print("Welcome to Python")
Output :Welcome to Python
>>> print("Welcome\
... to Python \
... string literals ")
Output : Welcome to Python string literals
>>> print ("""Welcome
... to
... Python String Literals""")
Output : Welcome
to
Python String Literals
3. Boolean literals
A Boolean literal can have any of the two values: True or False.
Example :
x=True
y=False
In Python, True is internally represents by the value 1 and False as 0.

4. Special literals
Python contains one special literal i.e. None. We use it to specify the unknown value. None
represent that there is no valid value. e.g.
stu_name = ”Rajat”
stu_contact_no = none

5. Literal Collections
There are four different types of literal collections List literals, Tuple literals, Dictionary
literals, and Set literals.
e.g.
fruits= ["apple", "mango", "orange"] #list literal
roll_nos= (1, 2, 3) #tuple literal
fruits = {'a':'apple', 'b':'ball', 'c':'cat'} #dictionary literal
vovels= {'a', 'e', 'i' , 'o', 'u'} #set literal
4.2 ATOMS
In Python, an atom is something that has a value. Identifiers, literals, strings, lists, tuples, sets,
dictionaries, etc. are all atoms. An expression in Python, is any valid combination of operators and
atoms

4.3 PYTHON - BASIC OPERATORS


Operators are symbols which are used to represent operations. Consider the expression 4 + 5 =
9. Here, 4 and 5 are called operands and + is called operator.
Types of Operator
Python language supports the following types of operators.
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Assignment Operators
4. Logical Operators
5. Bitwise Operators

6. Membership Operators
7. Identity Operators
Let us have a look on all operators one by one.
PYTHON ARITHMETIC OPERATORS
Arithmetic operators are used to represent the arithmetic operations between the operands. The
list of arithmetic operators along with the examples is as follow :
Assume that variable a=2 and variable b=3, then −

Operator Description Example Result

+ Adds values on either side of the operator. a+b 3

- Subtracts right hand operand from left hand a–b -1


operand.

* Multiplies values on either side of the operator a*b 6

/ Divides left hand operand by right hand b/a 1.5


operand

% Divides left hand operand by right hand b%a 1


operand and returns remainder

** Performs exponential (power) calculation on a**b 8


operators

// Floor Division - The division of operands 9//2 4


where the result is the quotient in which the
-11//3 -4
digits after the decimal point are removed. But
if one of the operands is negative, the result is
floored, i.e., rounded away from zero (towards
negative infinity) −

PYTHON COMPARISON (Relational) OPERATORS


These operators compare the values on either sides of them and decide the relation among
them. They are also called Relational operators. These operators return True or False in the
result. The list of relational operators along with examples is as follow.
Assume that variable a=2 and variable b=3, then −

Operator Description Example Result

== If the values of two operands are equal, then (a == b) False


the condition becomes true.

!= If values of two operands are not equal, then (a != b) True


condition becomes true.

<> If values of two operands are not equal, then (a <> b) True
condition becomes true. This is similar to !=
operator.

> If the value of left operand is greater than the (a > b) False
value of right operand, then condition becomes
true.

< If the value of left operand is less than the (a < b) True
value of right operand, then condition becomes
true.

>= If the value of left operand is greater than or (a >= b) False


equal to the value of right operand, then
condition becomes true.

<= If the value of left operand is less than or equal (a <= b) True
to the value of right operand, then condition
becomes true.
PYTHON ASSIGNMENT OPERATORS
These operators are used to assign/store a value in a variable. The list of assignment operators
along with examples is as follow.
Assume that variable a=2, then −

Operator Description Example Result

= Assigns values from right side operands to left c = 5


side operand

+= It adds right operand to the left operand and c += a equivalent


assign the result to left operand to c = c + a

-= It subtracts right operand from the left operand c -= a equivalent


and assign the result to left operand to c = c - a

*= It multiplies right operand with the left operand c *= a equivalent


and assign the result to left operand to c = c * a

/= It divides left operand with the right operand c /= a equivalent


and assign the result to left operand to c = c / a

%= It takes modulus using two operands and c %= a equivalent


assign the result to left operand to c = c %
a

**= Performs exponential (power) calculation on c **= a equivalent


operators and assign value to the left operand to c = c **
a

//= It performs floor division on operators and c //= a equivalent


assign value to the left operand to c = c // a

PYTHON LOGICAL OPERATORS


Python has 3 logical operators AND, OR, NOT. These operators gives result on the basis
of the truth tables of these logical operations.

AND OR NOT
Value1 Value2 Result Value1 Value2 Result Value1 Result
False False False False False False True False
False True False False True True False True
True False False True False True
True True True True True True

Logical operators receive True or False and give True or False in the result.
The examples of the use of logical operators is as follow :
Assume that variable a=2, b=3 then −
Operator Description Example Result

AND Apply logical AND operation a==2 AND b<3 False

OR Apply logical OR operation a==2 OR b<3 True

NOT Apply logical NOT operation NOT (a==2) False

PYTHON BITWISE OPERATORS

Bitwise operator works on bits and performs bit by bit operation.


Assume if a = 60; and b = 13; To understand the working of the bitwise operators we have to
convert a and b into binary. −
Binary equivalent of a = 0011 1100
Binary equivalent of b = 0000 1101
Note : 0 is equivalent to false and 1 is equivalent to true.
The list of Python bitwise operators along with examples is as follow.

Operator Description Example Result

& Apply AND operation of the binary c= (a & b) c =12


values a 0011 1100
b 0000 1101
---------------------------
c 0000 1100

| Apply OR operation of the binary c= (a | b) c = 61


values a 0011 1100
b 0000 1101
---------------------------
c 0011 1101

^ Apply XOR operation of the binary c=(a ^ b) c =49


values
a 0011 1100
(if there are odd 1’s output will be 1 b 0000 1101
otherwise 0) ---------------------------
c 0011 0001

~ Apply NOT or complement c=(~a ) c = -61


operation of the binary values
a 0011 1100 negative nos.
--------------------------- are stored as
2’s
c 1100 0011 complement.

<< The operand is shifted to left hand c=a << 2 c = 240


side by given no. of steps and 0’s are
a 0011 1100
inserted from the right side.
---------------------------
c 1111 0000

>> The operand is shifted to right hand c=a >> 2 c = 15


side by given no. of steps and 0’s are
a 0011 1100
inserted from the left side.
---------------------------
c 0000 1111

PYTHON MEMBERSHIP OPERATORS

Python’s membership operators test for membership in a sequence, such as strings, lists, or
tuples. These operators give True or False in the result. There are two membership operators
as explained below –
Suppose we have a list named subject = [“CS”, “Phy”, “Maths”] and sub1= “CS”

Operator Description Example Result

in Evaluates to true if it finds a variable sub1 in subjects True


in the specified sequence and false
otherwise.

not in Evaluates to true if it does not finds sub1 not in subjects False
a variable in the specified sequence
and false otherwise.

PYTHON IDENTITY OPERATORS


Identity operators compare the memory locations of two objects. These operators give True or
False in the result There are two Identity operators explained below –
Suppose we have 2 lists named subject1 = [“CS”, “Phy”, “Maths”] and subject2 = [“CS”,
“Phy”, “Maths”] also let subject3=subject1

Operator Description Example Result

is Evaluates to true if the variables on subject1 is subject3 True


either side of the operator point to
Because they
the same object and false
are pointing to
otherwise.
same object in
memory

is not Evaluates to false if the variables subject1 is subject2 False


on either side of the operator point
Because they
to the same object and true
are pointing to
otherwise.
different objects
in memory

PYTHON TERNARY OPERATOR


Ternary operators are more commonly known as conditional expressions in Python. These operators
evaluate something based on a condition being true or not. They became a part of Python in version 2.4
The syntax and example of using conditional expression is as follow.
Syntax:
value_if_true if condition else value_if_false
Example:
age=25
print("you can vote") if age>18 else print("you can't vote")
output : you can vote

4.4 PYTHON EXPRESSION


An expression is a combination of operators , operands and brackets. Expression produce some specific
value as the result. e.g. si = (p*r*t)/100

Here p, r, t, si ,100 are operands and *, / , = are operators. Part of the expression written inside the
brackets is evaluated first. When more than one type of operators in the expression then sequence of
evaluation of operations is decided on the basis of their precedence.

4.5 OPERATOR PRECEDENCE

When an expression can be interpreted in more than one way, there are rules that govern how
the expression gets interpreted. Such expressions follow precedence and Associativity rules.
The precedence of operators determines a rank for the operators. The higher an operator's
precedence, the higher “binding” it has on the operands. If more than one operators are involved
in an expression then, Python language has predefined rule of priority of operators. The order
in which different types of operators in an expression are evaluated is known as operator
precedence. Associativity determines the grouping of operations among operators of the same
precedence. Associativity indicates in which order two operators of same precedence (priority)
executes. Associativity can be left to right or right to left.

The operator precedence and associativity of various Python operators is shown the table given
below. Operators are the top has highest precedence whereas operators at the bottom has lowest
precedence.
Associativity Precedence Operators Meaning
order
Left to Right 1 () Parentheses
Right to Left 2 ** Exponent
Left to Right 3 +,-,~ Unary plus, Unary minus,
Bitwise NOT
Left to Right 4 *, /, //, % Multiplication, Division,
Floor division, Modulus
Left to Right 5 +, - Addition, Subtraction
6 <<, >> Bitwise shift operators
Left to Right 7 & Bitwise AND
Left to Right 8 ^ Bitwise XOR
Left to Right 9 | Bitwise OR
Left to Right 10 ==, !=, >, >=, <, <=, is, is Comparisons, Identity,
not, in, not in Membership operators
Left to Right 11 NOT Logical NOT
Left to Right 12 AND Logical AND
Left to Right 13 OR Logical OR
Right to Left 14 = ,+=, -=,*= /=,%= Assignment operator

Few examples about the operators precedence:

Example 1.
x= 5+3/7*8-6
In this expression there are 5 operators +, -, *, /, =. The precedence of *, / is highest the
precedence of +,- is 2nd highest, = has lowest precedence. Also the associativity of +,-,*,/ is
from left to right whereas the associativity of = is from right to left.
The order of evaluation of elements in this expression will be as follow:
Step 1. 3/7=0.4285
Step 2. 0.4284*8= 3.4285
Step 3. 5+3.4285=8.4285
Step 4. 8.4285-6
Step 5. 2.4285
Example 2.
5<7 OR 6>9 AND 10<12
Here we have <,>,AND,OR operators. The precedence of <,> is highest , the precedence of
AND is 2nd highest, OR has lowest precedence. The associativity of both <, >,AND and OR is
Left to Right. So the order of evaluation of elements in this expression will be as follow:
Step 1. 5<7 = True
Step 2. 6>9 = False
Step 3. 10<12 = True
Step 4. False AND True = False
Step 5. True OR False = True
Practice Questions:
Evaluate following expressions
1. x=2%3-7+4//3

2. x= "Computer" == "compueter" != "COMPUTER"


3. x= 5==5.0 OR 6>7 AND 8<5
Few Programming Problems with Solution
1. Write a program to find the sum of two given numbers.
num1= val(input(“Enter first number : ”))
num2= val(input(“Enter second number : ”))
result= num1+num2
print(“Sum of ”, num1 , “ and ”, num2 , “=”, result)
2. Write the program to find the simple interest.
P = val(input(“Enter principle amount : ”))
R = val(input(“Enter rate of interest : ”))
T = val(input(“Enter Time : ”))
Result= (P*R*T)/100
print(“Simple interest = Rs. ”, result)
3. Write the program to find the area of a triangle.
b = val(input(“Enter the value of base : ”))
h = val(input(“Enter the value of height : ”))
Result= (1/2*b*h)
print(“Area of Triangle = ”, Result)
4. Write a program to convert the temperature from Fahrenheit to Celsius.
F = val(input(“Enter the temperature in Fahrenheit : ”))
C = (F-32)*5/9
print(“Temperature in Celsius = ”, C)
EXERCISE:-Some important questions to be asked in Examination:-
[1] What is difference between Keyword and Identifier?
[2] Define Data Type? Discuss various data types available in Python?
[3] Define Operator. Discuss various Operators available in Python.
[4] What is role of any and all Operators?
[5] Discuss various Lines and Indentation in Programming?
[6] Define Variable? How is it different from Constant?
[7] Write a program in Python to find area of a circle.
[8] Write a program in Python to read the male population, female population of a town and
find the total population and percentage of male and female population.

Few Very Short Answer Type Questions

[1] % is a type of logical operator True/ False ?


[2] Tuples are immutable. True/False ?
[3] Dictionaries are immutable. True/False ?
[4] Write any four relational operators.
[5] +,- has same precedence as *, / True/False ?
[6] input function return a string . True/False ?
[7] Write down any four bitwise operator.
[8] What will be the result of a= 5//2.
[9] What will be the result of 5>6 AND 5>2 OR 5==5
[10] What will be the result of 20 << 3
5
CONTROL STRUCTURE
5.1 PYTHON - DECISION MAKING or FLOW CONTROL
Control structures form the basic entities of a “structured programming language“. Control
structures are used to alter the flow of execution of the program. When control structure is
not used in a program, the statements in the program execute in sequence and every statement
of the program execute once.
Why do we need to alter the program flow? The reason is “decision making“! In life, we may
be given with a set of options and on the basis of the choice made we have to perform some
action. Control Structure is used to make decisions and alter the direction of program flow in
one or the other path(s) available. In real world certain task is also execute again and again
until a condition exist. There are two types of control structures which is given as:-

1. Selection structure (one or many branches), Fig.5.1(a)


2. Loop structure (repetition of a set of activities), Fig 5.1(b)

Entry
Entry

Yes
No
CONDITION
False

Condition

Action 1
Action 2
True
Exit

Action 1
Exit

a. Selection control Structure b. Loop control Structure

Figure 5.1 Types of Control Structure

1. Selection control structure:- In this control structure the execution of the statements
depend upon the result of the condition. In this case we can assign different statements
for execution for the true result of the condition and we can assign different statements
for execution when result of condition is false. In above figure (5.a) either actiont1
statements will execute when the result of condition will be true and actiont2 statements
will be executed if the result of the condition will be false.
2. Loop Structure: - In this control structure the dependent statements executed again
and again until a particular condition remains true. In above figure 5.1(c) actiont1 is
executed again and again until condition which makes the decision is true.

Indentation : Indentation is the white spaces added before the statement.


Indentation play is a very important role in Python programming because
in Python the boundaries of related block of code is not represented with
braces. The statements in the block follow the same indentation. Every
block has it’s own indentation values. Indentation can be done by using
tab key or by using space key. We will learn the use of indentation in
coming topics (controls structure, functions etc.)

In Python there are 3 types of conditional control statements. They are given below:-
1. if statement
2. if else statement
3. if elif else statement

1.Simple if statement:- The general form of a simple if statement is, If the condition or
expression is true, then statement-inside if block will be executed, otherwise statement-inside
the if block will be skipped. i.e. program control goes directly to statements outside the if block.
ENTRY

False
if condition :
Statements which are Condition or expression?

dependent upon if are


written here True
(Statements-outside if block)
Block of Statements which
Note : The statements which depends upon if depend upon if
Follow same indentation.

Next Statements

Figure 5.3: Simple if statement syntax and flowchart

Let’s understand the use of if with the help of a simple examples.


Example:- WAP that read a number from user and it print “Welcome to Python” If the value
of number entered by user in 5.
Soln.
num=eval(input(“Enter any number : ”))
if num==5:
print("Welcome to Python")
print(“Welcome of learning”)
Output:- 1
Enter any number : 5
Welcome to Python
Welcome to learning
Output:- 2
Enter any number : 3
Welcome to learning

Here we can observe that when the value entered by user is equal to 5 then “Welcome to Python
” is executing otherwise it is not executing. Also Welcome to learning is independent from the
if statement.

2. The if-else statement:


In if – else statement when the result of the if condition is true then one set of statements gets
executed and when the condition is
false a different set of statements
will gets executed. The general
syntax of a simple if-else statement
is,

if condition :
The statements written here
will execute if the condition
is true
else:
The statements written here
will execute if the condition
is false
(Statements outside if else block)

Figure 5.4 : if-else Syntax and flowchart

Let’s understand the use of if with the help of a simple examples.

Example:- WAP that read a number from user and it print “Welcome to Python” If the value
of number entered by user is 5 otherwise it will print “Welcome to learning”.
Soln.
num=eval(input(“Enter any number : ”))
if num==5:
print("Welcome to Python")
else:
print(“Welcome of learning”)
Output:- 1
Enter any number : 5
Welcome to Python
Output:- 2
Enter any number : 3
Welcome to learning

Here we can observe that when the value entered by user is equal to 5 then “Welcome to Python
” is executing otherwise “Welcome to learning” is executing.

3. if...elif...else : This control structure is used when we have multiple conditions in the
problem. In this control structure on getting false result of condition we want to check if some
other condition is true. We can increase the levels of elif according to the solution of given
problem. This control structure is also
called laddered elif. The syntax and
flowchart of if-elif-else is as follow:
if condition :
The statements written here
will execute if the condition
is true
elif condition:
The Statements written here
will execute if this
condition is true
.
.
.
else
The Statements written here
will execute if all the above
conditions are false

(Statements outside if-elif-else block)

Figure 5.5 : if-elif-else Syntax and flowchart


Let’s understand the use of if with the help of a simple examples.

Example:- WAP that read a number from user and it print “Welcome to Python” If the value
of number entered by user is 5, it print “Welcome to Python” If the value of number entered is
6 , it print “Welcome to Programming” otherwise it will print “Welcome to learning”.
Soln.
num=eval(input(“Enter any number : ”))
if num==5:
print("Welcome to Python")
elif num==6:
print("Welcome to Programming")
else:
print(“Welcome of learning”)

Output:- 1
Enter any number : 5
Welcome to Python
Output:- 2
Enter any number : 6
Welcome to Programming
Output:- 3
Enter any number : 4
Welcome to learning

FEW PROGRAMS BASED UPON CONDITIONAL CONTROL STRUCTURE

Q1. Write a program to check whether a person is eligible to vote or not.


Sol.
age= eval(input(“Enter you age : ”))
if age>=18:
print(“You Can Vote”)
else:
print(“You Can’t Vote”)

Output :
Enter you age : 23
You Can Vote
Q2. Write a program to check whether a number is odd or even.
Sol.
num= eval(input(“Enter a number : ”))
if num%2==0:
print(“It is even no. ”)
else:
print(“It is odd no.”)
Output :
Enter a number : 34
It is even no.

Q3. Write a program to check whether a year is leap is or not.


Sol.
year= eval(input("Enter a Year : "))
if year%400==0:
print("It is leap year ")
elif year%4==0 and year%100!=0:
print("It is leap year ")
else:
print("It is not a leap year")
Output :
Enter a Year : 2021
It is not a leap year
Q4. Write a program to find the largest no. among three given nos.
Sol.
num1= eval(input("Enter a Year : "))
num2= eval(input("Enter a Year : "))
num3= eval(input("Enter a Year : "))
if num1>num2:
if num1>num3:
print(num1, " is greatest ")
else:
print(num3, " is greatest ")
else:
if num2>num3:
print(num2, " is greatest ")
else:
print(num3, " is greatest ")

Output:
Enter first no. : 23
Enter second no. : 10
Enter third no. : 65
65 is greatest

Q5. Write a program to find the grade of the student, based on following rules.
Percentage from (80-100) : A + grade
Percentage from (60- less than 80) : A grade
Percentage from (50- less than 60) : B grade
Percentage from (40- less than 50) : C grade
Percentage from (35- less than 40) : D grade
Percentage from (0-less than 35) : FAIL
Sol:
per=int(input("Enter value of percentage "))
if per>=80 and per<=100:
print(" Grade = A+ ")
elif:per>=60 and per<80:
print(" Grade = A ")
elif:per>=50 and per<60:
print(" Grade = B ")
elif:per>=40 and per<50:
print(" Grade = C ")
elif:per>=35 and per<40:
print(" Grade = D ")
else:
print(" FAIL ")

Output:
Enter value of percentage 72
Grade = A

5.2 PYTHON – LOOPING CONTROL STRUCTUTRE


Some time User may encounter situations, when a block of code needs to be executed several
number of times. A loop structure is used to execute a certain set of actions for a predefined
number of times or until a particular condition is satisfied. A program loop consists of two
parts: Body of the loop and control statement. The control statement tests certain conditions
and then decides repeated execution or termination of statements in the loop body.

Python programming language 2 types of loops/looping statements.

S.N. Loop Type & Description


1 while loop :- Repeats the statements in the loop body till the loop condition is
TRUE. The condition is tested before executing the loop body.
2 for loop:- For loop is used to process the sequences (List, Tuple, Dictionary
etc.).

1. while loop
A while loop in python programming repeatedly executes a target statement as long as a given
condition is true.
To control the while loop we require a counter. Firstly the counter is initialized, the condition
of the loop is tested (condition expression include counter), if the condition of loop is TRUE
then the body of the while loop is executed. In the loop body the value of the counter is also
altered/updated. After the execution of the while loop body the control is transferred to the start
of the loop where the condition is tested again. If the condition is still true the body of the loop
is executed again. This process is repeated again and again till the condition of the while loop
remains TRUE. When the condition becomes FALSE the control is transferred to the next line
after the while loop body.
The syntax and flow chart of while loop is as follow :
Syntax:- The syntax of a while loop is:-

Previous statements
while (condition) :
(Body of Loop)
The statements written in this section are executed again
and gain till the condition remains true
Statements after loop

Figure 5.6 Syntax and Flow chart

FEW EXAMPLES TO UNDERSTAND THE WORKING OF WHILE LOOP

Q1. Write a program to print Python 5 times.


Soln.
i=1; # this is counter initialization
while i<=5: # this is loop condition
print("Python")
i=i+1 # this is counter updation

Output:
Python
Python
Python
Python
Python

Check yourself :

a. What will be the output of this code


i=1;
while i<=5:
print("Python")

b. What will be the output of this code


i=10;
while i<=5:
print("Python")

c. What will be the output of this code


i=10;
while i<=5:
print("Python")
print("Python Bye")

Q2. Write a program to print n natural numbers.


Soln.
num=int(input("Enter the value of n "))
i=1
while i<=n:
print(i)
i=i+1
Output:
Enter the value of n 50
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50

Q3. Write a program to print odd numbers upto 100.


Soln.
i=1

while i<=100:
print(i)
i=i+2
Output:
Series of odd numbers upto 100
1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 53 55 57 59 61 63
65 67 69 71 73 75 77 79 81 83 85 87 89 91 93 95 97 99

Q4. Write a program to print the sum of first n natural nos.


Soln.
num=int(input("Enter the value of n "))
sum1=0
i=1
while i<=num:
sum1=sum1+i
i=i+1
print("Sum from 1 to ", num ," = ", sum1)

Output:
Enter the value of n 100
Sum from 1 to 100 = 5050

Q5. Write a program to find the factorial of a given number.


Soln.
num=int(input("Enter the value of n "))
if num==0 :
print("Factorial of ", num ," = 1")
elif num>0:
fact=1
i=num
while i>=1:
fact=fact*i
i=i-1
print("Factorial of ", num ," = ", fact)
else:
print("Enter a valid number")
Output:
Enter the value of n 7
Factorial of 7 = 5040

Q6. Write a program in Python to print the Fibonacci series.


0,1,1,2,3,5,8,13,21,34,…….

Sol.
n=int(input("How many elements of the fibonacci series do you want to display : "))
previous=0
present=1
next1=None
i=1
while(i<=n):
if(i==1):
print(previous, end=" ")
elif(i==2):
print(present, end=" ")
else:
next1=previous+present
print(next1, end=" ")
previous=present
present=next1
i=i+1

Output:

How many elements of the fibonacci series do you want to display : 8


0 1 1 2 3 5 8 13

FOR LOOP

For loop has simplified syntax. It is used to access the elements of the sequence (lists, tuples,
dictionaries etc.) step by step. We can also use range() function in for loop to repeat the
iterations depending upon the value of the range().
Syntax:-The syntax of a for loop is −
for <variable> in <sequence>:
(Body of Loop)
statement(s)
Statements outside loop body

FEW EXAMPLES TO UNDERSTAND THE WORKING OF FOR LOOP

Q1. Display the marks obtained (stored in the list) by the student in 5 subjects.
Sol.
marks = [67,78,90,59,79]
print(" Marks obtained : ")
for m in marks:
print(m, end=" ")

Output
67 78 90 59 79

Q2. Find the sum of marks obtained in 5 subjects by a student.


Sol.
marks = [67,78,90,59,79]
sum1=0
print(" Marks obtained : ")
for m in marks:
sum1=sum1+m
print("Sum of the marks obtained by the student in 5 subjects = ", sum1)

Output :
Sum of the marks obtained by the student in 5 subjects = 373

Q3. Count the number of vowels in the given characters (stored in the tuple).
Son.
chars = ('a','p','c','t','r','i')
count=0
for c in chars:
if (c=='a' or c=='e' or c=='i' or c=='o' or c=='u'):
count=count+1
print("No. of vowels in the given characters :", count)

Output :
No. of vowels in the given characters : 2

Q4. Create a dictionary to store the detail about the book and access the various stored
elements with the help of for loop.
Sol.
book = { 'Title' : 'Python Programming', 'Price' : 'Rs. 350', 'ISBN' : '123-678-9086' }
print ("The detail of the book ")
for c in book.items():
print (c, end= " ")

Output:
The detail of the book
('Title', 'Python Programming') ('Price', 'Rs. 350') ('ISBN', '123-678-9086')

We can also use The range() function with for loop : here is the brief information about
range() function.

The range() function is used to create a sequence of numbers. The syntax of range () is as
follow.
range(start, stop, step)
here start and step are optional by default start value is 0 and step value is 1.
Range function create a sequence which start from the value given in the start and stop one step
before the value given in the stop. After each iteration the value is changed w.r.t. the value
mentioned in the step.

Few more examples of for loop with range()


Q5. Print “Python” 5 times.

Soln.
for i in range(5):
print("Python")

Output:
Python
Python
Python
Python
Python
Q6. Write a program in Python to print n natural nos.
Soln.
n=int(input("Enter the value of n : "))
for i in range(1,n+1):
print( i, end=" ")

Output:
Enter the value of n : 100
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
95 96 97 98 99 100

Q7. Write a program in Python to print odd natural nos. up to n.


Soln.
n=int(input("Enter the value of n : "))
for i in range(1,n+1, 2):
print( i, end=" ")

Output:
Enter the value of n : 100
1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 53 55 57 59 61 63
65 67 69 71 73 75 77 79 81 83 85 87 89 91 93 95 97 99

Q8. Write a program in Python to find the sum of even natural nos. up to n.
Soln.
n=int(input("Enter the value of n : "))
sum1=0
for i in range(0,n+1,2):
sum1=sum1+i
print(" The sum of even natural nos. upto ",n," = ",sum1)

Output:
Enter the value of n : 100
The sum of even natural nos. upto 100 = 2550

Q9. Find the factorial of a given no.


Sol.
n=int(input("Enter the value of n : "))
fact=1
for i in range(n,0,-1):
fact=fact*i
print(" The factorial of ",n," = ",fact)

Output:
Enter the value of n : 5
The factorial of 5 = 120

Nested Loops
Nested loop means loop in side another loop. Python programming language allows to use one
loop inside another loop. Nested loops are used in situations where in loop body contains
iterative statements. As discussed in the examples given below.

FEW EXAMPLES OF NESTED LOOPS

Q1. Write a program to print following pattern.


1
11
111
1111
11111
Soln.
#By using nested for loops.
for i in range(1,6):
print()
for j in range(0,i):
print ("1",end=" ")

#By using nested while loops.

i=1
while i<=5:
print()
j=1
while j<=i:
print ("1",end=" ")
j=j+1
i=i+1

#By using nested for and while loops.

i=1
while i<=5:
print()
for j in range(0,i):
print ("1",end=" ")
i=i+1

5.3 LOOP CONTROL STATEMENTS


Loop control statements change execution of Loops from its normal operation Python supports
the following loop control statements:-

S.N. Control Statement & Description


break statement
1 Terminates the loop statement and transfers execution to the statement
immediately following the loop.
continue statement
2 Causes the loop to skip the remainder of its body and immediately retest its
condition prior to reiterating.
pass statement
3 The pass statement in Python is used when a statement is required syntactically
but we do not want any command or code to execute.

5.3.1 break statement


The break command will exit the most immediately surrounding loop regardless of what the
condition of the loop is. Break is useful if we want to exit a loop under special circumstances.
When a break statement comes inside any loop, program control breaks the loop and transfer
the control to next statement after the loop. Break statement is often used with the if statement,
which specifies the condition to terminate the loop. Let us consider the case of an alarm on a
mobile ringing at a particular time. Suppose the phone gets an incoming call in the time the
alarm is ringing, the alarm is stopped immediately and the phone ringer starts ringing.

Example :
i=1
while i<=100:
if i==5:
break
else:
print(i, end=" ")
i=i+1
Output :
1234
Here, we can observe that the control is transferred outside the loop not because of termination
of loop, but because of the break statement. Here break statement is written inside the if, so it
will gets executed when value of i becomes 5.

5.3.2 continue statement


continue statement skips the statements present below the continue statement in a loop and take
the control to the entry point of the loop. Essentially, the continue statement is saying "this
iteration of the loop is done; let's continue with the loop without executing whatever code
comes after me." Like break statement continue is often used with the if statement, which
specifies the condition to continue the loop.
Example
i=1
while i<=5:
print ("Hello to Python")
if i==3:
i=i+1
continue
print ("Bye to Python")
i=i+1
Output:
Hello to Python
Bye to Python
Hello to Python
Bye to Python
Hello to Python
Hello to Python
Bye to Python
Hello to Python
Bye to Python

Here, we can observe that when the value of i become equal to 3 then the statements written
below that point (“Bye to Python” is not displayed when i==3 ) in loop body are skipped and
control is transferred to the starting of the loop.

5.3.3 pass statement


The pass statement, which performs no action, is used used as a placeholder when a statement
is syntactically required but you have nothing specific to do. Pass statement can be used in
conditional control statements and looping control statements.

let us look at a sample program in Python to demonstrate the Pass statement.


for num in range(10, 21):
if num %5==0:
pass
else :
print( num, "is not a multiple of 5 ")
num++

This program prints the multiples of 5, Here we have not specified the statements for if, so we
have used pass statement to fulfil the syntax requirements . The output is as follows.
11 is not a multiple of 5
12 is not a multiple of 5
13 is not a multiple of 5
14 is not a multiple of 5
16 is not a multiple of 5
17 is not a multiple of 5
18 is not a multiple of 5
19 is not a multiple of 5

EXERCISE:-Some important questions to be asked in Examination:-


[1] What you understand by Control Structure? Discuss various types of control structures
in Python.
[2] Define Looping? Explain various looping statements with example?
[3] Discuss control loop statements with examples?
[4] What difference is between continue and break Statements?
[5] Discuss syntax, purpose, flowchart and example of each conditional statement?
[6] Differentiate for and while loop?
[7] Write a program in Python to check whether a number is even or odd.
[8] Write a program in Python to check whether a number is prime or non prime.
[9] Write a program to check whether a no. is palindrome or not.
[10] Write a program to print the table of given no.
[11] Write a program to find the product of given 10 numbers.
[12] Write a program to print following pattern.

1
2 3
4 5 6
7 8 9 10

[13] Write a program in Python to print following pattern


*
* *
* * *
* * * *

Few Very Short Answer Type Questions

[1] __________ and _________ are two types of control structures in Python.
[2] _______ statement is used to skip the statements of a looping control structure.
[3] ________ and _______ are two types of looping control structures.
[4] In python the statements dependent on a control structure are written with same
indentation. True/False.
[5] Pass statement is used as a place holder in control structures to complete syntax
requirements. True/False.

You might also like