MODULE 1-4
MODULE 1-4
INTRODUCTION TO PYTHON
1. INTRODUCTION TO PYTHON
Python was developed by Guido van Rossum at the National Research Institute for Mathematics and
Computer Science in Netherlands during 1985-1990. Python is derived from many other languages, including
ABC, Modula-3, C, C++, Algol-68, SmallTalk, Unix shell and other scripting languages. Rossum was inspired
by Monty Python's Flying Circus, a BBC Comedy series and he wanted the name of his new language to be
short, unique and mysterious. Hence he named it Python. It is a general-purpose interpreted, interactive, object-
oriented, and high-level programming language. Python source code is available under the GNU General
Public License (GPL) and it is now maintained by a core development team at the National Research Institute.
2. FEATURES OF PYTHON
a) Simple and easy-to-learn - Python is a simple language with few keywords, simple structure and its syntax is
also clearly defined. This makes Python a beginner's language.
b) Interpreted and Interactive - Python is processed at runtime by the interpreter. We need not compile the
program before executing it. The Python prompt interact with the interpreter to interpret the programs that we
have written. Python has an option namely interactive mode which allows interactive testing and debugging of
code.
c) Object-Oriented - Python supports Object Oriented Programming (OOP) concepts that encapsulate code
within objects. All concepts in OOPs like data hiding, operator overloading, inheritance etc. can be well written
in Python. It supports functional as well as structured programming.
d) Portable - Python can run on a wide variety of hardware and software platforms, and has the same interface
on all platforms. All variants of Windows, Unix, Linux and Macintosh are to name a few.
e) Scalable - Python provides a better structure and support for large programs than shell scripting. It can be
used as a scripting language or can be compiled to bytecode (intermediate code that is platform independent)
for building large applications.
f) Extendable - you can add low-level modules to the Python interpreter. These modules enable programmers to
add to or customize their tools to be more efficient. It can be easily integrated with C, C++, COM, ActiveX,
CORBA, and Java.
g) Dynamic - Python provides very high-level dynamic data types and supports dynamic type checking. It also
supports automatic garbage collection.
h) GUI Programming and Databases - Python supports GUI applications that can created and ported to
many libraries and windows systems, such as Windows Microsoft Foundation Classes (MFC), Macintosh, and
the X Window system of Unix. Python also provides interfaces to all major commercial databases.
3. IDENTIFIERS
A Python identifier is a name used to identify a variable, function, class, module or any other object. Python
is case sensitive and hence uppercase and lowercase letters are considered distinct. The following are the rules
for naming an identifier in Python.
1
a) Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or an
underscore (_). For example Total and total is different.
b) Reserved keywords cannot be used as an identifier.
c) Identifiers cannot begin with a digit. For example 2more, 3times etc. are invalid
identifiers.
d) Special symbols like @, !, #, $, % etc. cannot be used in an identifier. For example sum@, #total are invalid
identifiers.
• Class names start with an uppercase letter. All other identifiers start with a lowercase letter. Eg: Person
• Starting an identifier with a single leading underscore indicates that the identifier is private.
Eg: _sum
• Starting an identifier with two leading underscores indicates a strongly private identifier. Eg: _sum
• If the identifier also ends with two trailing underscores, the identifier is a language-defined special name.
foo
4. RESERVED KEYWORDS
These are keywords reserved by programming language and prevent the user or the programmer from using
it as an identifier in a program. There are 33 keywords in python. This number can vary with different
versions. To retrieve the keywords in python the following code can be given at the prompt. All keywords
except True, False and None are in lowercase. The following list in Table 1.1 shows the python keywords.
>>> print(keyword.kwlist)
[ „False‟, „None‟, „True‟, 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else',
'except', 'finally', 'for', 'from', 'global', ' if', 'import', 'in', 'is', 'lambda', ‟nonlocal‟, 'not', 'or', 'pass',
'raise', 'return', 'try', 'while', 'with', 'yield']
5. VARIABLES
Variables are reserved memory locations to store values. Based on the data type of a variable, the
interpreter allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning
different data types to variables, you can store integers, decimals or characters in these variables.
Python variables do not need explicit declaration to reserve memory space. The declaration happens
automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables.
The operand to the left of the = operator is the name of the variable and the operand to the right of the =
operator is the value stored in the variable.
Example Program
2
a = 100 # An integer assignment
b = 1000.0 # A floating point
name = "John" # A string
print(a)
print(b)
print(name)
Here, 100, 1000.0 and "John" are the values assigned to a, b, and name variable respectively.
This produces the following result.
100
1000.0
John
Python allows you 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.
6. COMMENTS IN PYTHON
Comments are very important while writing a program. It describes what the source code has done.
Comments are for programmers for better understanding of a program. In Python, we use the hash (#) symbol
to start writing a comment. A hash sign (#) that is not inside a string literal begins a comment. All characters
after the # and up to the end of the physical line are part of the comment. It extends up to the newline character.
Python interpreter ignores comment.
Example Program
>»#DisplayHello
>»print("Hello")
For multiline comments one way is to use (#) symbol at the beginning of each line. The following example
shows a multiline comment. Another way of doing this is to use triple quotes, either '" or """.
Example 1
3
>»#and it ends after
>>>#Threelines
Example 2
>>>and it endsafter
>>>Threelines"""
Both Example 1 and Example 2 given above produces the same result.
7. INPUT, OUTPUTANDIMPORTFUNCTIONS
• Displaying the Output
The function used to print output on a screen is the print statement where you can pass zero or more
expressions separated by commas. The print function converts the expressions you pass into a string and
writes the result to standard output.
Example 1
›››print ("Learning Python is fun and enjoy it.")
Output
E nt e r yo ur na me : Co l l in
M a r k Yo u r na me is : Co l l in M a r k
4
• input function
The input([prompt]) function is equivalent to raw_input, except that it assumes the input is a valid Python
expression and returns the evaluated result to you.
Example 1
print("Thenumberis:",n)
Output
Enter a number : 5
The number is : 5
• Import function
When the program grows bigger or when there are segments of code that is frequently used, it can be stored
in different modules. A module is a file containing Python definitions and statements. Python modules have a
filename and end with the extension .py. Definitions inside a module can be imported to another module or
the interactive interpreter in Python. We use the import keyword to do this. For example, we can import the
math module by typing in import math.
>>> import math
>>> print(math.pi )
3.141592653589793
8. OPERATORS
Operators are the constructs which can manipulate the value of operands. Consider the expression a = b +
c. Here a, b and c are called the operands and +, = , are called the operators. There are different types of
operators. The following are the types of operators supported by Python.
• Arithmetic Operators
• Comparison (Relational) Operators
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Membership Operators
• Identity Operators
5
▪ 1.Arithmetic Operators
Arithmetic operators are used for performing basic arithmetic operations. The following are the arithmetic
operators supported byPython. Table 1.2 showsthe arithmetic operators in Python.
Operator Description
>= If the value of left operand is greater than or equal to the value of right operand,
thenthe condition becomes true.
<= If the value of left operand is less than or equal to the value of right operand, then
the condition becomes true.
Example Program
a, b, c = 10, 5, 2
print("Sum.",(a+b))
print("Difference=",(a-b))
p r int ( " Product =” , ( a * b) )
print ( "Quotient=”,(a/b) )
print (" Remainder=", ( b% c))
print ("Exponent=", ( b**2))
pr int ( " Floor Division= ",( b/ / c) )
Output
Sum= 15
Difference= 5
product = 50
Quotient = 2
Remainder= 1
Exponent = 25
6
Floor Division= 2
▪ 2.Comparison operators
These operators compare values on either sides of them and decide the relation among them. They are also
called relational operators. Python supports the following relational operators. Python supports the following
relational operators. Table 1.3 shows the comparison or relational operators in python.
Table 1.3 Comparison (Relational) operators in python
Operator Description
<= If the value of left operand is less than or equal to the value of right operand, then
the condition becomes true.
Example Program
a, b=10,5
print (“a==b is:”, (a==b))
print (“a!=b is:”, (a!=b))
▪ 3.Assignment Operators
Python provides various assignment operators. Various shorthand operators for addition, subtraction,
multiplication, division, modulus, exponent and floor division are also supported by Python. Table 1.4 provides
the various assignment operators.
Operator Description
/= It divides left operand withthe right operand and assign the result to left operand.
The assignment operator = is used to assign values or values of expressions to a variable. Example: a =
b+ c. For example c+=a is equivalent to c=c+a. Similarly c-=a is equivalent to c=c-a, c*=a is equivalent to
c=c*a, c/=a is equivalent to c=c/a, c%=a is equivalent to c=c%a, c**=a is equivalent to c=c**a and c//=a is
equivalent to c=c//a.
Example Program
a, b, c = 10, 5, 2
print("Sum.",(a+b))
print("Difference=",(a-b))
p r int ( " P r o d u c t =” , ( a * b) )
print ( "Quotient=”,(a/b) )
print (" Remainder=", ( b% c))
print ("Exponent=", ( b**2))
8
pr int ( " Flo o r D iv is io n= " , ( b/ / c) )
F lo o r D iv is io n= 2
Output
Sum= 15
Difference= 5 pro duct = 50 Quo t ie nt = 2 Remainder= 1
E xpo nent = 25
▪ 4.Bitwise Operators
Bitwise operator works on bits and performs bit by bit operation. The following are the bit wise operators
supported by python. Table 1.5 gives a description of bitwise operators in python.
» Binary Right The left operand's value is moved right bythe number of bits specifiedby
Shift the right operand.
Example Program
a, b = 60, 2
9
Consider the first print statement a & b. Here a =0011 1100
b=0000 0010
when a bitwise and is performed, the result is 0000 0000. This is 0 in decimal. Similar is the case for
all the print statements given above.
▪ 5.Logical Operators
Table 1.6 shows the various logical operators supported by Python language.
and Logical AND If both the operands are true then condition becomes true.
or Logical OR If any of the operands are true then condition becomes true.
not Logical NOT Used to reverse the logical state of its operand.
Example Program
a, b, c, d=10, 5, 2, 1
print ( (a>b) and (c>d) ) print ( (a>b) or (d> c) ) print (not (a>b) )
Output
True True False
▪ 6.Membership operators
Python‟s membership operators test for membership in a sequence, such as strings, lists or tuples.
There are two membership operators.
Table 1.7 shows the various membership operators supported by Python language.
Operator Description
▪ 7.Identity Operators
Identity operators compare the memory locations of two objects. There are two identity operators as
given below.
Operator Description
is It is evaluated to be true if the variables present on either sides of the operator point to
the same object and false otherwise.
is not It is evaluated to be false if the variables on either side of the operator point to the
same object and true otherwise.
Example Program
a,b,c=10,10,5
print(a is b) print(a is c)
Operator Precedence
The following table lists all operators from highest precedence to lowest precedence. Operator
associativity determines the order of evaluation, when they are of the same precedence, and are not
grouped by parenthesis. An operator may be left-associative or right associative. In left associative,
the operator falling on the left side will be evaluated first, while in right- associative, operator falling
on the right will be evaluated first. In Python, ‘=’ and ‘**’ are right associative while all other
operators are left associative. The precedence of the operators is important to find out since it
enables us to know which operator should be evaluated first. The precedence table of the operators in
python is given below.
Operator Description
** The exponent operator is given priority over all the others used in the expression.
~, +, - The negation(complement), unary plus and minus.
*, /, %, // The multiplication, divide, modules, reminder, and floor division.
+, - Binary plus and minus
>>, << Left shift and right shift
& Binary AND
^, | Binary XOR and OR
<=, < >, >= Comparison operators (less then, less then equal to, greater then, greater then
equal to).
<>, == ,!= Equality operators.
= ,%= ,/= ,//= Assignment operators
,-= ,+=
*= **=
is, is not Identity operators
11
in ,not in Membership operators
not , or and Logical operators
The data stored in memory can be of many types . For example, a person's name is stored as
alphabets, age is stored as a numeric value and his or her address is stored as alphanumeric characters.
Python has the following standard data types.
•Numbers.
• String
•List ·
•Tuple
•Set
• Dictionary
1.NUMBERS
Number data types store numeric values. Number objects are created when you assign a value to them.
For example a = 1, b = 20. You can also delete the reference to a number object by using the del
statement. The syntax of the del statement is as follows.
Example Program
a, b, c, d=1,1.5, 231456987, 2+9j
print("a", a)
print("b", b)
print("c=",c)
print("d=",d)
Output
a=1
b= 1.5
c= 231456987 d= (2+9j)
12
2.STRINGS
Strings in Python are identified as a contiguous set of characters represented in the quotation marks.
Python allows for either pairs of single or double quotes. Subsets of strings can be taken using the
slice operator ([ ] and [:]) with indexes starting at 0 in the beginning of the string and ending at -1.
The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition operator.
The % operator is used for string formatting.
Example Program
str = “Welcome to Python Programming”
print(str) # Prints complete string print(str[0]) # Prints first
character of the string
print(str[11:17]) # Prints characters starting from 11th to 17th
print(str[11:]) # Prints string starting from 11th character print(str * 2) # Prints string two times
print(str + "Session") # Prints concatenated string
Output
Welcome to Python Programming
W
Python
Python Programming
Welcome to Python Programming Welcome to Python Programming Welcome to Python
Programming Session
3.LIST
List is an ordered sequence of items. It is one of the most used data type in Python and is very flexible.
All the items in a list do not need to be of the same type. Items separated by commas are enclosed
within brackets [ ]. To some extent, lists are similar to arrays in C. One difference between them is
that all the items belonging to a list can be of different data type. The values stored in a list can be
accessed using the slice operator ([ ] and [ : ]) with indices starting at 0 in the beginning of the list
and ending with -1. The plus (+) sign is the list concatenation operator and the asterisk (*) is the
repetition operator.
Example Program
first_list = ['abcd', 147, 2.43, 'Tom', 74.9] small_list = [111,'Tom']
print(first_list)# Prints complete list print(first_list[o]) # Prints first element of the list
print(first_list [1:3]) # Prints elements starting from 2nd till 3rd print(first_list [2:]) # Prints elements
starting from 3rd element print(small_list *2) # Prints list two times
print(first_list + small_list) # Prints concatenated lists
Output
['abcd', 147, 2.43, Tom', 74.9 ]
13
abcd
[147, 2.43]
[2.43, 'Tom', 74.9]
[111, 'Tom', 111, 'Tom']
['abcd', 147, 2.43, 'Tom', 74.9, 111, 'Tom']
We can update lists by using the slice on the left hand side of the assignment operator. Updates can
be done on single or multiple elements in a list.
Example Program
#Demo of List as Stack stack=[10,20,30,40,50]
stack.append(60)
print ("Stack after appending:", stack) stack.pop()
print("Stack after poping:" , stack)
Output
Stack after appending: [10, 20, 30, 40, 50, 60]
Stack after poping: [10, 20, 30, 40, 50 ]
Example Program
#Demo of List as Queue
from collections import deque
14
queue = deque (["apple", "orange", "pear"]) queue. append("cherry") # cherry arrives queue.append(
"grapes") # grapes arrives
queue.popleft() # The first to arrive now leaves
queue.popleft() # The second to arrive now leaves
print (queue) # Remaining queue in order of arrival
Output
deque (['pear', 'cherry', 'grapes'])
4.TUPLE
A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values
separated by commas. The main differences between lists and tuples are lists are enclosed in square
brackets ( [ ] ) and their elements and size can be changed, while tuples are enclosed in parentheses (
( ) ) and cannot be updated. Tuples can be considered as read-only lists.
Example Program
first_tuple = ('abcd', 147, 2.43, 'Tom', 74.9) small_tuple = (111, 'Tom')
print(first_tuple) # Prints complete tuple
print(first_tuple[0]) # Prints first element of the tuple print(first tuple[1:3]) # Prints elements
starting from 2nd till 3rd print(first_tuple[2:]) # Prints elements starting from 3rd element
print(small_tuple * 2) # Prints tuple two times
print(first_tuple + small tuple) # Prints concatenated tuples
Output
('abcd', 147, 2.43, Tom', 74.9)
abcd
(147, 2.43)
(2.43, 'Tom', 74.9)
(111, Tom', 111, 'Tom')
('abcd', 147, 2.43, Tom'. 74.9, 111, 'Tom')
5.SET
Set is an unordered collection of unique items. Set is defined by values separated by comma inside
braces
{ }. It can have any number of items and they may be of different types (integer, float, tuple, string
etc.). Items in a set are not ordered. Since they are unordered we cannot access or change an element
of set using indexing or slicing. We can perform set operations like union, intersection, difference on
15
two sets. Set have unique values. They eliminate duplicates. The slicing operator [ ] does not work
with sets. An empty set is created by the function set( ).
Example Program
# Demo of Set Creation
sl={1,2,3} #set of integer numbers print (s1)
s2= {1,2,3,2,1,2} #output contains only unique values print (s2)
s3={2, 2.4, 'apple', 'Tom', 3}#set of mixed data types print (s3)
#s4={1,2, [3, 4] } #sets cannot have mutable items #print s4 # Hence not permitted
s5=set ([1,2,3,4]) #using set function to create set from a li print (s5)
Output
{1, 2, 3}
{ 1, 2, 3}
{1, 3, 2.4, "apple', 'Tom' }
{1, 2, 3, 4}
6.FROZENSET
Frozenset is a new class that has the characteristics of a set, but its elements cannot be changed once
assigned. While tuples are immutable lists, frozensets are immutable sets. Sets being mutable are
unhashable, so they can‟t be used as dictionary keys. On the other hand, frozensets are hashable and
can be used as keys to a dictionary
Frozensets can be created using the function frozenset(). This datatype supports methods like
difference(), intersection(), isdisjoint() issubset(), issuperset(), symmetric_difference() and union().
Being immutable it does not have methods like add(), remove(), update(),difference_update(),
intersection_update(), symmetric_difference_update() etc.
Example Program
#Demo of frozenset()
set1= frozenset({3, 8, 4,6}) print ("Set 1:", set1)
set 2=frozenset({3,8}) print("Set 2:", set2)
print("Result of set1.intersection (set2):", set1.intersection (set 2))
Output
Set1: frozenset({8, 3, 4, 6})
Set 2: frozenset({8, 3})
Result of set1.intersection (set2): frozenset((8, 3})
16
7.DICTIONARY
Dictionary is an unordered collection of key-value pairs. It is generally used when we have a huge
amount of data. We must know the key to retrieve the value. In Python, dictionaries are defined
within braces { } with each item being a pair in the form key:value. Key and value can be of any
type. Keys are usually numbers or strings. Values, on the other hand, can be any arbitrary Python
object. Dictionaries are sometimes found in other languages as "associative memories" or
"associative arrays".
Dictionaries are enclosed by curly braces ({}) and values can be assigned and accessed using square
braces
([ ]).
Example Program
dict={}
dict['one']= "This is one"
dict [2] ="This is two"
tinydict={'name': 'john', 'code': 6734, „dept':‟ sales‟}
studentdict={'name': 'john', 'marks': [35,80,90]}
print (dict['one')) # Prints value for 'one' key
print (dict [2]) # Prints value for 2 key
print (tinydict) # Prints complete dictionary
print (tinydict. keys ()) # Prints all the keys
print (tinydict.values()) # Prints all the values
print (studentdict) #Prints studentdict
Output
This is one
This is two
{'dept': „sales', 'name': „john', „code': 6734}
dict_keys (['dept', 'name', "code'])
dict_values (['sales', 'John', 67341)
{'marks': [35, 80, 90], 'name': 'john'}
We can update a dictionary by adding a new key-value pair or modifying an existing entry.
17
10. MUTABLE AND IMMUTABLE OBJECTS
Objects whose value can change are said to be mutable and objects whose value is unchangeable
once they are created are called immutable. An object's mutability is determined by its type. For
instance, numbers, strings and tuples are immutable, while lists, sets and dictionaries are mutable.
The following example illustrates the mutability of objects.
Example Program
a=10
print(a) #Value of a before subtraction print(a-2) #value of a - 2
print(a) #Value of a after subtraction #Strings
str="abcde"
print(str) #Before applying upper() function print(str.upper()) #result of upper()
print(str) #After applying upper() function #Lists
list=[1,2,3,4,5]
print(list) #Before applying remove () method list.remove(3)
print(list)#After applying remove() method
Output
10
8
10
abcde ABCDE
abcde
[1, 2, 3, 4, 5]
[1, 2, 4, 5]
From the above example, it is clear that the values of numbers and strings are not even after
applying a function or operation. But in the case of list, the value is changed or the changes are
reflected in the original variable and hence called mutable.
We may need to perform conversions between the built-in types. To convert between different data
types, use the type name as a function. There are several built-in functions to perform conversion
from one data type to another. These functions return a new representing the converted value. Table
2.6 shows various functions and their descriptions used for data type conversion.
Table 2.6 Functions for Data Type Conversions
Function Description
long(x [,base]) Converts x to a long integer. base specifies the base if x is a string
Example Program 1
# Demo of Data Type Conversions X= 12.8
print("Integer x=",int(x)) x=12000
print("Long X=", long(x))
print("Long x=", long(x)) x=12
print("Floating Point x=", float(x)) real, img=5,2
print("Complex number =" , complex(real,img)) x=12
print("String conversion of", X,"is", str(x)) x=12
print("Expression String of", X,"is", repr(x))
Output 1
Integer x= 12
Long x= 12000 Floating Point x= 12.0 Complex number = (5+2j)
String conversion of 12 is 12
Expression String of 12 is 12
Decision making is required when we want to execute a code only if a certain condition is satisfied.
The if...elif...else statement is used in Python for decision making.
19
11.1.if statement Syntax
The following Fig. 3.1 shows the flow chart of the if statement.
Here, the program evaluates the test expression and will execute statement(s) only if the test
expression is True.
If the test expression is False, the statement{s) is not executed. In Python, the body of the if statement
is indicated by the indentation. Body starts with an indentation and ends with the first unintended line.
Python interprets non-zero values as True. None and 0 are interpreted as False.
if test expression:
Body of if
else: :
Body of else
Example Program
Output 1
Enter a number: 5 Positive Number or Zero
Output 2
Enter a number:-2 Negative Number
11.3.if.elif..else statement
Syntax
if test expression:
Body of elif
else:
Body of else
The elif is short for else if. It allows us to check for multiple expressions. If the condition for if is
false, it checks the condition of the next elif block and so on. If all the conditions are false, body of
else is executed. Only one block among the several if... elif... else blocks is executed according to the
condition. An if block can have only one else block. But it can have multiple elif blocks. The following
20
Fig. 3.3 shows the flow chart for if.elif. .else statement
Example Program
num=int (input ("Enter a number: ")) if num> 0:
Output 1
Enter a number: 5 Positive Number
Output 2
Enter a number: 0 Zero
Output 3
Enter a number:-2 Negative Number
11.4.Nested if statement
We have a if...elif...else statement inside another if...elif...else statement. this is called nesting in
computer programming. indentation is the only way to identify the level of nesting.
Example Program
num=int (input ("Enter a number: ")) if num >= 0:
if num == 0:
print (“Zero")
else:
print(“ Positive number")
else:
print "Negative number")
Output 1
13. LOOPS
Generally, statements are executed sequentially. The first statement in a function is executed first,
followed by the second, and so on. There will be situations when we need to execute a block of code
several number of times. Python provides various control structures that allows for repeated
execution. A loop statement allows us to execute a statement or group statements multiple times.
for loop
The for loop in Python is used to iterate over a sequence (list, tuple, string) or other objects that can
be iterated. Iterating over a sequence is called traversal.
Syntax
for item in sequence:
21
Body of for
for each
item in
sequence
test No
expression
Yes
body of for
exit loop
Example Program
#Program to find the sum of all numbers stored in a list numbers = [2,4,6,8,10] #List of numbers
sum = 0 # variable to store the sum for item in numbers: # iterate over the list
sum = sum + item
print(" The sum is", sum) #print the sum
Output
The sum is 30
Python supports to have an else statement associated with a loop statement. If the else statement is
used with a for loop, the else statement is executed when the loop has finished iterating the list. A
break statement can be used to stop a for loop. In this case, the else part is ignored. Hence, a for loop's
else part runs if no break occurs.
Example Program
#Program to find whether an item is present in the list list= [10,12, 13 , 34,27,98]
num = int (input (“Enter the number to be searched in the list: ")) for item in range (len (list) ):
if list [item] == num:
print ("Item found at: ", (item+1)) break
else:
print("Item not found in the list")
Output 1
22
Enter the number to be searched in the list:34 Item found at:4
Output 2
Enter the number to be searched in the list:99 Item not found in the 1ist
while loop
The while loop in Python is used to iterate over a block of code as long as the test expression
(condition) is True. We generally use this loop when we don't know the number of times to iterate in
advance. Fig. 3.5 shows the flow chart of a while loop.
Syntax
while test_expression:
Body of while
In while loop, test expression is checked first. The body of the loop is entered only if the test
expression evaluates to True. After one iteration, the test expression is checked again. This process
is continued until the test_expression evaluates to False. In Python, the body of the
while loop is determined through indentation. Body starts with indentation and the first unintended
line shows the end. When the condition is tested and the result is False, the loop body will be skipped
and the first statement after the while loop will be executed.
Example Program
# Program to find the sum of first N natural numbers n =int (input ("Enter the limit: "))
sum=0 i=1 while i<=n:
sum=sum+1 i-i+1
print (Sum of first" n “natural numbers is", sum)
Output
Enter the 1imit: 5
Sum of first 5 natural numbers is 15
NESTED LOOPS
Sometimes we need to place a loop inside another loop. This is called nested loop. We can have
nested loops for both while and for.
Syntax for nested for loop
for iterating_variable in sequence :
for iterating_ variable in sequence: statements (s)
statements (s)
Q: Write a program to print the prime numbers starting from 1 upto a limit entered by the user.
23
Program using nested for
#Program to generate prime numbers between 2 Limits import math
n =int (input ("Enter a Limit: ")) for i in range (1,n):
k=int (math.sqrt (i)) for j in range (2, k+1) :
if i % j == 0: break
else:
Print (i)
Output
Enter a Limit:12 1
2
3
5
7
11
Control statements change the execution from normal sequence. Loops iterate over a block of code
until test expression is False, but sometimes we wish to terminate the current iteration or even the
whole loop without checking test expression. The break and continue Statements are used in these
cases. Python supports the following three control statements.
1. break
2. continue
3. pass
The break statement terminates the loop containing it. Control of the program flows to the statement
24
immediately after the body of the loop. It is inside a nested loop( loop inside another loop), break will
terminate the innermost loop. It can be used with both for and while loops. Fig. 3.6 shows the flow
chart of break statement.
Example Program1
#Demo of break statement in Python for i in range (2, 10,2) :
if i==6:
break print (i)
print (" End of Program")
Output 1
2
4
End of Program
The continue statement is used to skip the rest of the code inside a loop for the current iteration only.
Loop does not terminate but continues on with the next iteration. Continue returns the control to the
beginning of the loop. The continue statement rejects all the remaining statements in the current
iteration of the loop and moves the control back to the top of the loop. The continue statement can be
used in both while and for loops. Fig. 3.7 shows the flow chart of continue statement.
Example Program
# Demo of continue in Python for letter in 'abcd':
if letter = ='c':
continue print (letter)
Output
abd
It is used as a placeholder. Suppose we have a loop or a function that is not implemented yet, but we
want to implement it in the future. The function or loop cannot have an empty body. The interpreter
will not allow this. So, we use the pass statement to construct a body that does nothing.
Example
for val in sequence: pass
25
26