Unit – 2
CONTROL STRUCTURES :
2.1 DECISION MAKING & BRANCHING
Decision making is about deciding the order of execution of statements based on certain conditions.
Decision structures evaluate multiple expressions which produce TRUE or FALSE as outcome.
1
There are three types of conditions in python:
if statement
if-else statement
elif statement
if statement: It is a simple if statement. When condition is true, then code which isassociated with if
statement will execute.
Example:
a=40b=20
if a>b:
print(“a is greater than b”)
if-else statement: When the condition is true, then code associated with if statement willexecute,
otherwise code associated with else statement will execute.
Example:
a=10b=20
if a>b:
print(“a is greater”)
else:
print(“b is greater”)
elif statement: It is short form of else-if statement. If the previous conditions were not true,then do
this condition". It is also known as nested if statement.
Example:
a=input(“Enter first number”) b=input("Enter Second Number:")
if a>b:
print("a is greater")elif a==b:
print("both numbers are equal")
else:
print("b is greater")
2
2.2 LOOPS in PYTHON
Loop: Execute a set of statements repeatedly until a particular condition is satisfied.
There are two types of loops in python:
while loop
for loop
while
Loops in loop
Python
for loop
3
With the while loop we can execute a set of statements as long as a condition istrue. It while loop:
requires to define an indexing variable.
Example: To print table of number 2i=2
while i<=20:
print(i)i+=2
for loop : The for loop iterate over a given sequence (it may be list, tuple or string).
Note: The for loop does not require an indexing variable to set beforehand, as the for commanditself
allows for this.
primes = [2, 3, 5, 7]for x in primes:
print(x)
The range( ) function:
it generates a list of numbers, which is generally used to iterate over with for loop. range( )
function uses three types of parameters, which are:
start: Starting number of the sequence.
stop: Generate numbers up to, but not including last number.
step: Difference between each number in the sequence. Python use range( ) function in three ways:
range(stop)
range(start, stop)
range(start, stop, step)
Note:
All parameters must be integers.
All parameters can be positive or negative.
4
range(stop): By default, It starts from 0 and increments by 1 and ends up to stop,but not
including stop value.
Example:
for x in range(4):
print(x)
Output:
0
1
2
3
range(start, stop): It starts from the start value and up to stop, but not including stop value.
Example:
for x in range(2, 6):
print(x)
Output:
2
3
4
5
range(start, stop, step): Third parameter specifies to increment or decrement the value byadding or
range(start, stop, step): subtracting the value.
Example:
for x in range(3, 8, 2):
print(x)
Output:
3
5
7
5
Explanation of output: 3 is starting value, 8 is stop value and 2 is step value. First print 3 and increase
it by 2, that is 5, again increase is by 2, that is 7. The output can’t exceed stop-1 valuethat is 8 here. So,
the output is 3, 5, 8.
Difference between range( ) and xrange( ):
S. range( ) xrange( )
No.
1 returns the list of numbers returns the generator object that can be usedto
display numbers only by looping
2 The variable storing the range takes more variable storing the range takes less memory
memory
3 all the operations that can be applied on operations associated to list cannot be
the list can be used on it applied on it
4 slow implementation faster implementation
2.3 JUMP STATEMENTS:
There are two jump statements in python:
break
continue
break statement : With the break statement we can stop the loop even if it is true.
Example:
in while loop in for loop
i=1 languages = ["java", "python", "c++"]for
while i < 6:print(i) if i == 3: x in languages:
break if x == "python":break
i += 1 print(x)
Output: Output:
1 java
2
3
Note: If the break statement appears in a nested loop, then it will terminate the very loop it is in i.e. if
the break statement is inside the inner loop then it will terminate the inner loop only and the outer loop
will continue as it is.
6
continue statement : With the continue statement we can stop the current iteration, and
continue with the next iteration.
Example:
in while loop in for loop
i=0 languages = ["java", "python", "c++"]for
while i < 6:i += 1 x in languages:
if i == 3:continue if x == "python":continue
print(i) print(x)
Output: Output:java c++
1
2
4
5
6
Loop else statement:
The else statement of a python loop executes when the loop terminates normally. The else
statement of the loop will not execute when the break statement terminates the loop.
The else clause of a loop appears at the same indentation as that of the loop keyword while or
for.
Syntax:
for loop while loop
for <variable> in <sequence>: while <test condition>:
statement-1 statement-1 statement-2
statement-2 .
. .
. else:
else: statement(s)
statement(s)
7
Nested Loop :
A loop inside another loop is known as nested loop.
Syntax:
for <variable-name> in <sequence>:
for <variable-name> in <sequence>:statement(s)
statement(s)
Example:
for i in range(1,4):
for j in range(1,i):
print("*", end=" ")print(" ")
Programs related to Conditional, looping and jumping statements
Write a program to check a number whether it is even or odd.
Num=int(input(“Enter the number: “))if num%2==0:
print(num, “ is even number”)else:
print(num, “ is odd number”)
Write a program in python to check a number whether it is prime or not.
Num=int(input(“Enter the number: “))for I in range(2,num):
if num%i==0:
print(num, “is not prime number”)break;
else:
print(num,”is prime number”)
Write a program to check a year whether it is leap year or not.
year=int(input("Enter the year: ")) if year%100==0 and year%400==0:
print("It is a leap year")elif year%4==0:
print("It is a leap year")else:
print("It is not leap year")
8
Write a program in python to convert °C to °F and vice versa.
A=int(input(“Press 1 for C to F \n Press 2 for F to C \n”))if a==1:
c=float(input(“Enter the temperature in degree celcius: “))f= (9/5)*c+32
print(c, “Celcius = “,f,” Fahrenheit”)elif a==2:
f=float(input(“Enter the temperature in Fahrenheit: “))c= (f-32)*5/9
print(f, “Fahrenheit = “,c,” Celcius”)
else:
print(“You entered wrong choice”)
Write a program to check a number whether it is palindrome or not.
num=int(input("Enter a number : "))n=num
res=0
while num>0: rem=num%10
res=rem+res*10num=num//10
if res==n:
print("Number is Palindrome")else:
print("Number is not Palindrome")
A number is Armstrong number or not.
num=input("Enter a number : ") length=len(num)
n=int(num)num=n sum=0 while n>0:
rem=n%10 sum=sum+rem**lengthn=n//10
if num==sum:
print(num, "is armstrong number")else:
print(num, "is not armstrong number")
9
To check whether the number is perfect number or not
num=int(input("Enter a number : "))sum=0
for i in range(1,num):if(num%i==0):
sum=sum+i
if num==sum:
print(num, "is perfect number")else:
print(num, "is not perfect number")
Write a program to print Fibonacci series.
n=int(input("How many numbers : ")) first=0
second=1i=3
print(first, second, end=" ")while i<=n:
third=first+second print(third, end=" ")first=second second=third
i=i+1
To print a pattern using nested loops
for i in range(1,5): 1
for j in range(1,i+1): print(j," ", 1 2
end=" ") 1 2 3
prin('\n') 1 2 3 4
2.4 STRING
A string is a sequence of characters.(i.e) it can be a letter , a number, or a backslash.
Python strings are immutable, which means they cannot be changed after they are created.
STRING SLICES:
A segment of a string is called a slice. Selecting a slice is similar to selecting a character.
The operator [n:m] returns the part of the string from the “n-eth” character to the “m- eth”
10
character,including the first but excluding the last.
If you omit the first index (before the colon), the slice starts at the beginning of the string. If
youomit the second index, the slice goes to the end of the string.
If the first indexes is greater than or equal to the second the result is an empty string,
represented by two quotation marks.
An empty string contains no characters and has length 0, but other than that, it is the same as
anyother string.
STRINGS ARE IMMUTABLE:
It is tempting to use the [] operator on the left side of an assignment, with the intention of
changing a character in a string.
For example:
>>> greeting = 'Hello, world!'
>>>greeting[0] = 'J'
TypeError: object does not support item assignment.
The “object” in this case is the string and the “item” is the character you tried to assign.
An object is the same thing as a value, but we will refine that definition later. An item is one of
the values in a sequence.
The reason for the error is that strings are immutable, which means you can’t change an existing
string.
11
The best is to create a new string that is a variation on the original:
>>> greeting = 'Hello, world!'
>>>new_greeting = 'J' + greeting[1:]
>>> print new_greeting
Output:
Jello, world!
This example concatenates a new first letter onto a slice of greeting. It has no effect on the
original string.
2.4.1 STRING FUNCTIONS AND METHODS:
A method is similar to a function—it takes arguments and returns a value—but the syntax is
different.
For example, the method upper takes a string and returns a new string with all uppercase letters:
Instead of the function syntax upper(word), it uses the method syntax [Link]().
>>>word = 'banana'
>>>new_word = [Link]()
>>> print new_word BANANA
This form of dot notation specifies the name of the method, upper, and the name of the string to
apply the method to, word. The empty parentheses indicate that this method takes no argument.
A method call is called an invocation; in this case, we would say that we are invoking upper on
the word.
>>>word = 'banana'
>>>index = [Link]('a')
>>>print index
1
The find method is more general than our function; it can find substrings, not just
characters:
>>>[Link]('na')
12
2.5 Python List
In Python, the sequence of various data types is stored in a list.
• A list is a collection of different kinds of values or items. Since Python lists are mutable, we
can change their elements after forming. The comma (,) and the square brackets [enclose the
List's items] serve as separators.
• Although six Python data types can hold sequences, the List is the most common and reliable
form. A list, a type of sequence data, is used to store the collection of data. Tuples and Strings
are two similar data formats for sequences.
• Lists written in Python are identical to dynamically scaled arrays defined in other languages,
such as Array List in Java and Vector in C++. A list is a collection of items separated by
commas and denoted by the symbol [].
List Declaration
Code
# a simple list
list1 = [1, 2, "Python", "Program", 15.9]
list2 = ["Amy", "Ryan", "Henry", "Emma"]
# printing the list
print(list1)
print(list2)
# printing the type of list
print(type(list1))
print(type(list2))
Output:
[1, 2, 'Python', 'Program', 15.9]
['Amy', 'Ryan', 'Henry', 'Emma']
< class ' list ' >
< class ' list ' >
Characteristics of Lists
The characteristics of the List are as follows:
The lists are in order.
The list element can be accessed via the index.
The mutable type of List is
The rundowns are changeable sorts.
13
The number of various elements can be stored in a list.
Ordered List Checking
Code
# example
a = [ 1, 2, "Ram", 3.50, "Rahul", 5, 6 ]
b = [ 1, 2, 5, "Ram", 3.50, "Rahul", 6 ]
a == b
Output:
False
The indistinguishable components were remembered for the two records; however, the
subsequent rundown changed the file position of the fifth component, which is against the
rundowns' planned request. False is returned when the two lists are compared.
Code
Example1
a = [ 1, 2, "Ram", 3.50, "Rahul", 5, 6]
b = [ 1, 2, "Ram", 3.50, "Rahul", 5, 6]
a == b
Output:
True
Records forever protect the component's structure. Because of this, it is an arranged collection of
things.
Let's take a closer look at the list example.
Code
List example 2
emp = [ "John", 102, "USA"]
Dep1 = [ "CS",10]
Dep2 = [ "IT",11]
HOD_CS = [ 10,"Mr. Holding"]
HOD_IT = [11, "Mr. Bewon"]
print("printing employee data ...")
print(" Name : %s, ID: %d, Country: %s" %(emp[0], emp[1], emp[2]))
print("printing departments ...")
print("Department 1:\nName: %s, ID: %d\n Department 2:\n Name: %s, ID: %s"%( Dep1[0], De
p2[1], Dep2[0], Dep2[1]))
print("HOD Details ....")
print("CS HOD Name: %s, Id: %d" %(HOD_CS[1], HOD_CS[0]))
print("IT HOD Name: %s, Id: %d" %(HOD_IT[1], HOD_IT[0]))
print(type(emp), type(Dep1), type(Dep2), type(HOD_CS), type(HOD_IT))
14
Output:
printing employee data...
Name : John, ID: 102, Country: USA
printing departments...
Department 1:
Name: CS, ID: 11
Department 2:
Name: IT, ID: 11
HOD Details ....
CS HOD Name: Mr. Holding, Id: 10
IT HOD Name: Mr. Bewon, Id: 11
<class ' list '> <class ' list '> <class ' list '> <class ' list '> <class ' list '>
2..5.1 List Indexing and Splitting
• The indexing procedure is carried out similarly to string processing. The slice operator []
can be used to get to the List's components.
• The index ranges from 0 to length -1. The 0th index is where the List's first element is
stored; the 1st index is where the second element is stored, and so on.
15
Methods over Python Lists
Method Description
append() add an item to the end of the list
add all the items of an iterable to the end of the
extend()
list
insert() inserts an item at the specified index
remove() removes item present at the given index
returns and removes item present at the given
pop()
index
clear() removes all items from the list
index() returns the index of the first matched item
count() returns the count of the specified item in the list
sort() sort the list in ascending/descending order
reverse() reverses the item of the list
copy() returns the shallow copy of the list
16
List sample program
Lst=[1,2,3,4,5]
print(“the list is”, Lst)
[Link](6,9)
print(“after inserting the list”, Lst)
print(“Indexing the element of 5 is”, [Link](5))
[Link](4)
print(“list after removing the list “,Lst)
[Link](9)
print(“after the appending the value of 9 in list”, Lst)
Lst2=[‘a’,’b’,’c’,’a’]
print(“the number of occurrence of a in the list “,Lst2,”are”, [Link][‘a])
[Link]()
print(“the sorted element of the list are”, Lst)
[Link]()
print(“to remove the right most element in the list”, Lst)
[Link]()
print(“The revrsal list is”, Lst)
[Link](Lst2)
print(“combining the list – Lst and Lst2 we get “,Lst)
Python list traversal
We can use square bracket in Index and print each element of a list as we traverse the same
Example :
cheeses = ["Gouda", "Swiss", "Provolone", "Cheddar"]
for cheese in cheeses:
print(cheese)
17
2.6 DICTIONARY IN PYTHON
Keys are unique within a dictionary while values may not be.
• The values of a dictionary can be of any type, but the keys must be of an immutable data
type such as strings, numbers, or tuples.
• Dictionary is one of the compound data type like strings, list and tuple. Every element in
a dictionary is the key-value pair.
• An empty dictionary without any items is written with just two curly braces, like this: {}.
Creating a Dictionary:
A dictionary can be Created by specifying the key and value separated by colon(:) and the
elements are separated by comma (,).The entire set of elements must be enclosed by curly braces
{}.
Syntax:
Example:
#Keys-Value can have mixed datatype
Dict1 = {1: “Fruit”, 2: “Vegetabe”,3: “Fish”}
Dict2={“Name”: “Zara”, “Subject”:[“Maths”, “Phy”, “Chemistry”], “Marks”:[198,192,193],
“Avg”:92}
Accessing Elements in Dictionary:
To access dictionary elements, you can use the familiar square brackets along with the key to
obtain its value.
Since Dictionary is an unordered Data type. Hence the indexing operator cannot be used to
access the Values.
18
To access the data, we have to use key which is associated with the Value.
Example:
>>Dict2={“Name”: “Zara”, “Subject”:[“Maths”, “Phy”, “Chemistry”],
“Marks”:[198,192,193], “Avg”:92}
>>Dict2[“Name”]
>>Dict2[“Avg”]
>>Dict2[“Subject”]
Output:
Zara 20.1
[“Maths”, “Phy”, “Chemistry”]
Deleting Element in Dictionary:
The element in the dictionary can be deleted by using Del statement.
The entire dictionary can be deleted by specifying the dictionary variable name.
Syntax:
Example:
>>> dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
>>> del dict['Name']
>>> dict{'Age': 7, 'Class': 'First'
}
Updating Element in Dictionary:
In Dictionary the Keys are immutable, however the values are mutable.
Hence only the Value pair can be Updated
Example
>>> My_dict={'Name':'Nivetha','rank':5,'Average':78.9}
>>> My_dict['rank']=3
>>> My_dict
{'Name': 'abi', 'rank': 3, 'Average': 78.9}
19
Operation Description Input Function Output
Dict1={“Name”:”zara”,”Age”:14,”se Cmp(dict1,d 1
cmp(dict1 Compares x”:”M ”} i ct2) 0
, dict2) elements of both Dict2={“Name”:”zara”,”Age”:14} Cmp(dict2,d
dict. Dict3={“Name”:”zara”,”Age”:14} ict3)
len(dict) Gives the total Dict1={“Name”:”zara”,”Age”:14,”se Len(dict1) 2
length of the x”:”M ”} Len(dict2) 3
dictionary. Dict2={“Name”:”zara”,”Age”:14}
str(dict) Produces a Dict1={“Name”:”zara”,”Age”:14,”se Str(dict1) {“Name”:
printable string x”:”M ”} ”zara”,”A
representation of ge”:14,
a dictionary ,”sex”:”M
”}
type Returns the type Dict1={“Name”:”zara”,”Age”:14,”se Type(dict1) <type
(variable) of the passed x”:”M ”} ‘dict’>
variable. If
passed variable
is dictionary,
then it would
return a
dictionary type.
DICTIONARY METHODS:
[Link] Method Description
1 [Link]() Removes all elements of dictionary dict
2 [Link]() Removes all elements of dictionary dict
3 [Link]() Returns a list of dict's (key, value) tuple pairs
4 [Link]() Returns list of dictionary dict's keys
5 [Link]() Returns list of dictionary dict's values
6 [Link](dict2) Adds dictionary dict2's key-values pairs to dict
7 [Link]() Create a new dictionary with keys from seq and values
set to value.
8 [Link](key, default=None) For key, returns value or default if key not in
dictionary
9 dict.has_key(key) Returns true if key in dictionary dict, false otherwise
20
DICTIONARY OPERATION:
Example:
>>>dict1 = {1: “Fruit”, 2: “Vegetabe”,3: “Fish”}
>>>Print(dict1)
>>>{1: “Fruit”, 2: “Vegetabe”,3: “Fish”}
>>> del dict[1]
>>>print(dict1)
>>>{ 2: “Vegetabe”,3: “Fish”}
The len function also works on dictionaries; it returns the number of key:value pairs:
>>> len(dict1) 3
# demo for all dictionary methods
dict1 = {1: "Python", 2: "Java", 3: "Ruby", 4: "Scala"}
# copy() method
dict2 = [Link]()
print(dict2)
# clear() method
[Link]()
print(dict1)
# get() method
print([Link](1))
# items() method
print([Link]())
# keys() method
print([Link]())
# pop() method
[Link](4)
print(dict2)
# popitem() method
[Link]()
21
print(dict2)
# update() method
[Link]({3: "Scala"})
print(dict2)
# values() method
print([Link]())
Output:
{1: 'Python', 2: 'Java', 3: 'Ruby', 4: 'Scala'}
{}
Python
dict_items([(1, 'Python'), (2, 'Java'), (3, 'Ruby'), (4, 'Scala')])
dict_keys([1, 2, 3, 4])
{1: 'Python', 2: 'Java', 3: 'Ruby'}
{1: 'Python', 2: 'Java'}
{1: 'Python', 2: 'Java', 3: 'Scala'}
dict_values(['Python', 'Java', 'Scala'])
Building Blocks Of Python Programs, Understanding And Using Ranges
WAP AREA OF RECTANGLE
CODE OUTPUT
22
WAP AREA OF CIRCLE
CODE OUTPUT
WAP AREA OF CUBOID
CODE OUTPUT
23
WAP AREA OF CUBE
CODE OUTPUT
WAP AREA OF CSA OF CYLINDER
CODE OUTPUT
WAP AREA OF TSA OF CYLINDER
CODE OUTPUT
24
WAP AREA OF CSA OF CONE
CODE OUTPUT
WAP AREA OF TSA OF RIGHT CIRCULAR CONE
CODE OUTPUT
WAP TSA OF SPHERE
CODE OUTPUT
25
WAP VOLUME OF CUBOID
CODE OUTPUT
WAP VOLUME OF CUBE
CODE OUTPUT
WAP VOLUME OF CYLINDER
CODE OUTPUT
26
WAP VOLUME OF CONE
CODE OUTPUT
WAP VOLUME OF SPHERE
CODE OUTPUT
WAP PERIMETER OF RECTANGLE
CODE OUTPUT
27
WAP AREA OF SQUARE
CODE OUTPUT
WAP AREA OF TRIANGLE
CODE OUTPUT
WAP GREATEST NO. IN THREE NO.
CODE OUTPUT
28
WAP PERIMETER OF TRIANGLE
CODE OUTPUT
29
WAP GREATEST NO. IN FOUR [Link] OUTPUT
30
WAP TO CHECK DIVISION IN RESULT
CODE OUTPUT
WAP TO CHEAK AGE CRITERIA
31
WAP SUM OF NTH NO.
CODE OUTPUT
WAP TO CHEAK THE VALUE OF FACTORIAL
OUTPUT CODE
32
WAP TO PRINT MULTIPLICATION TABLE
CODE OUTPUT
WAP TO PRINT OPPOSITE RIGHT ANGLETRIANGLE
CODE OUTPUT
33
27- WAP TO PRINT 1,22,333,444
CODE
OUTPUT
WAP TO PRINT STAR PATTERN OF OPPOSITETRIANGLE
CODE OUTPUT
34
WAP TO PRINT PATTERN 1,12,123
CODE OUTPUT
WAP TO PRINT FIBONACCI SERIES USE WHILE LOOP
CODE OUTPUT
35
WAP TO PRINT PATTERN A,AB,ABC
CODE
WAP TO CALCULATION OF Xn BY FOR LOOP
CODE
36
33- WAP TO CALCULATION OF Xn
CODE
WAP TO PRINT THE INTEGER IS PALINDROME ORNOT PALINDROME
CODE
37
WAP TO PRINT FACTORIAL OF LIST
38
WAP TO PRINT PASCAL TRIANGLE
TO CREATE A LIST OF VALUES INPUTTED BYUSER
CODE OUTPUT
39
WAP TO CREATE A LIST OF VALUES INPUTTED BYUSER AND SORT IN INCREASING
ORDER
CODE OUTPUT
SORTING IN ACCENDING ORDER USE BUBBLE SORT
CODE
40
WAP in Python to create a phone dictionary
OUTPUT
41
WAP TO FIND GIVEN NUMBER IS PRIME OR NOT
CODE
OUTPUT
42
WAP TO FIND GIVEN NUMBER IS EVEN OR ODD
CODE
OUTPUT
43
WAP TO CREATE A TUPLE OF VALUES INPUTED BYUSER
CODE
OUTPUT
44
WAP TO REVERSE AN INTEGER
CODE
OUTPUT