3 Introduction To Python: National Research Institute For Mathematics and Computer Science
3 Introduction To Python: National Research Institute For Mathematics and Computer Science
3 Introduction To Python: National Research Institute For Mathematics and Computer Science
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
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.
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.
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.
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
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')
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')
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
e.g
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. 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 .
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.
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.
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
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.
Example
a = 'Computer Science'
b= “Computer Science”
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
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.
Example :
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
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 −
<> 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 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 −
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
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”
not in Evaluates to true if it does not finds sub1 not in subjects False
a variable in the specified sequence
and false otherwise.
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.
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
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
Entry
Entry
Yes
No
CONDITION
False
Condition
Action 1
Action 2
True
Exit
Action 1
Exit
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.
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?
Next Statements
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.
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)
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
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
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.
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
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
Output:
Python
Python
Python
Python
Python
Check yourself :
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
Output:
Enter the value of n 100
Sum from 1 to 100 = 5050
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:
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
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
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.
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
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
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.
i=1
while i<=5:
print()
j=1
while j<=i:
print ("1",end=" ")
j=j+1
i=i+1
i=1
while i<=5:
print()
for j in range(0,i):
print ("1",end=" ")
i=i+1
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.
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.
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
1
2 3
4 5 6
7 8 9 10
[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.