Unit Ii, PPS PDF
Unit Ii, PPS PDF
Unit Ii, PPS PDF
1. if statement
The If statement is similar to other languages like
in Java, C, C++, etc.
It is used when we have to take some decision like
the comparison between anything or to check the
presence and gives us either TRUE or FALSE.
The syntax for IF Statement is as:
if (expression): # condition check(T/F)
statement1
statement2
Expression is evaluated and result of
expression is checked True(1) or False(0)
Page | 1
1. Write a python program to check number is even and if even then display it.
num = int(input("enter the number?"))
if num%2 == 0:
print("Number is even")
Output:
enter the number? 4
Number is even
Output:
Enter number? 25
Odd no
3. if…..elif….else statement
The elif statement enables us to check multiple conditions and execute the specific block of
statements depending upon the true condition among them.
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.
Page | 3
The if block can have only one else block.
But it can have multiple elif blocks.
The syntax for elif Statement is
as:
if expression:
statement1
elif expression:
statement1
elif expression:
statement1
else:
statement1
Page | 4
Python Nested if statements:
Any number of these statements can be nested inside one another.
Indentation is the only way to figure out the level of nesting.
This can get confusing, so must be avoided if we can.
Output:
Enter a number: 5
Positive number
Page | 5
Advantages of loops
1. It provides code re-usability.
2. Using loops, we do not need to write the same code again and again.
3. Using loops, we can traverse over the elements of data structures (array or linked lists).
1. While loop:
while loop is used to execute a block of statements repeatedly until a given a condition is satisfied
(True).
And when the condition becomes false, the line immediately after the loop in program is executed.
Syntax:
while expression:
statement1
statement2
Here, the statements can be a single statement or the group of statements.
The expression should be any valid python expression resulting into true or false.
The true is any non-zero value and false is zero value.
If expression never get false in while loop, then this loop becomes infinite.
1. Write a python program to print series of number from 1 to 10 using while loop.
i=1;
while i<=10:
print(i);
i=i+1;
Output:
1 2 3 4 5 6 7 8 9 10
3. Write a python program for displaying even or odd numbers between 1 to n using while
loop.
n=int(input("Enter the number:")) Output:
i=1 Enter the number:5
while(i<=n): 1 is odd no
if(i%2==0): 2 is even no
print(+i,"is even no") 3 is odd no
else: 4 is even no
print(+i,"is odd no") 5 is odd no
i=i+1
Page | 6
4. Write a python program to compute sum of n natural numbers and find average of that
numbers using while loop.
n=int(input("Enter the n value"))
i=1
sum=0
while(i<=n):
sum=sum+I #body of while loop
i+=1
avg=sum/n;
print("sum of {0} natural number is {1}".format(n, sum))
print("Average of {0} natural number is {1}".format(n, avg))
Output:
Enter the n value 10
sum of 10 natural number is 55
Average of 10 natural number is 5.5
5. Write a python program to compute square of n natural numbers using while loop.
n=int(input("Enter the n value"))
i=1
while(i<=n):
square=i*i #body of while loop
i+=1
print("Square of {0} is {1}".format(i,square))
Output:
Enter the n value5
Square of 2 is 1
Square of 3 is 4
Square of 4 is 9
Square of 5 is 16
Square of 6 is 25
Page | 7
6. Write a python program to display Fibonacci numbers for sequence of length n using while
loop.
n=int(input("Enter the n value")) Output:
i=0 Enter the n value10
a=0 Fibonacci sequence is:
b=1 0
print("Fibonacci sequence is:") 1
while(i<n): 1
print(a) 2
c=a+b 3
a=b #While loop 5
b=c 8
i=i+1 13
21
34
7. Write a python program to check number is Armstrong number or not using while loop.
A number is called Armstrong number if it is equal to the sum of the cubes of its own digits.
For example: 153 is an Armstrong number since 153 = 1*1*1 + 5*5*5 + 3*3*3.
The Armstrong number is also known as narcissistic number.
if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")
Output:
Enter a number: 153
153 is an Armstrong number
Page | 8
The range( ) function
Can generate a sequence of numbers using range() function
range(10) will generate numbers from 0 to 9 (10 numbers)
Can also define the start, stop and step size as range(start,stop,stepsize)
Step size defaults to 1 if not provided.
Does not store all the values in memory, it would be inefficient
So it remembers the start, stop, step size and generates the next number on the go
>> print(range(10))
range(0, 10)
>> print(list(range(10)))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>> print(list(range(2,10,2))
[2, 4, 6, 8]
>> print(list(range(2,10)))
[2, 3, 4, 5, 6, 7, 8, 9]
>> print(list(range(20,10,-2)))
[20, 18, 16, 14, 12]
>> print(list(range(2,10,-2)))
[]
2. For loop:
The for loop in Python is used to iterate the statements
or a part of the program several times.
It is frequently used to traverse the data structures
like list, tuple, or dictionary.
Syntax:
for val in sequence:
Body of for loop
The variable takes the value of item inside the sequence
on each iteration.
Loop is continued until the last item in the sequence.
Ex: To print series of 5
n=5
for i in range(1,11):
print(i*n)
Output:
5 10 15 20 25 30 35 40 45 50
Page | 9
1. Write a python program to compute sum of n natural numbers using for loop.
n=int(input("Enter the n value"))
sum=0
for i in range(1,n+1):
sum=sum+i
print(sum)
Output:
Enter the n value5
15
Output:
Enter the number3
3 is a prime number
Page | 10
4. Write a python program to perform factorial of a number (5!=(5*4*3*2*1)=120).
n=int(input("Enter the number"))
factorial=1
for i in range(1,n+1):
factorial=factorial*i
1. Pre-test loop:
The pre-test loop also called as entry controlled loop.
This is type of loop for which the condition is tested before start of loop.
If condition of entry controlled loop is not met then loop will not get executed.
There are two commonly used loop- for loop and while loop. we can use both loop for pre-test
loop.
2.Post-test loop:
The post-test loop also called as exit controlled loop.
This is type of loop for which the condition is tested after loop is executed.
In exit controlled loop, loop will get executed at least once then condition is tested. if condition
is true then loop is executed till condition becomes false .
There are two commonly used loop- for loop and while loop. we can use both loop for post-test
loop.
Sr
Pre-test loop Post-test loop
No.
The condition is specified at beginning
1 The condition is specified at bottom of loop
of loop
If condition becomes false, then loop Even if condition is false, the loop executes at
2
does not get executed at all. least one time
3 There are n+1 number of test There are n number of test
4 Minimum number of iteration is 0 Minimum number of iteration are 1
5 The loop is initialized only once The loop gets initialized twice
Page | 11
3. Condition controlled loop:
When we do not know for how many number of times the loop will be executed, then we use
condition controlled loop.
The condition controlled loop is also called as sentinel controlled loop or indefinite loop.
The condition controlled loop is normally implemented using while loop, we also use for loop,
but while loop is better choice.
Sr
Condition controlled loop: Counter controlled loop:
No.
we do not know for how many number we know for how many number of times the loop
1
of times the loop will be executed will be executed
2 No counter is used Counter is used
3 indefinite loop definite loop
4 Generally while loop is used Generally for loop is used
i=1
while(i<=10): for i in range(1,11):
5
print(i) print(i)
i=i+1
Nested Loop:
Page | 12
1. Write a python program to display the star pattern
*
**
***
****
Program:
n=int(input("Enter the number"))
for i in range(0,n):
for j in range(0,i+1):
print("*", end="")
print("")
Output:
Enter the number4
*
**
***
****
Page | 13
2. Write a python program to display the pattern
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Program:
n=int(input("Enter the number"))
for i in range(1,n+1):
for j in range(1,i+1):
print(j, end=" ")
print("")
Output:
Enter the number5
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Page | 14
break Statement:
Break statement is used to transfer the control to out of loop.
The break statement breaks the loops one by one, i.e., in the case of nested loops, it breaks the
inner loop first and then proceeds to outer loops.
In other words, we can say that break is used to abort the current execution of the program and
the control goes to the next line after the loop.
The break is commonly used in the cases where we need to break the loop for a given condition.
syntax:
break # used in loop
Ex:
for i in range(0, 7):
if(i==5):
break
print("Value of i is :",+i)
Output:
Value of i is : 0
Value of i is : 1
Value of i is : 2
Value of i is : 3
Value of i is : 4
Ex:
for val in "string":
if val == "i":
break
print(val)
print("The end")
Output:
s
t
r
The end
Page | 15
continue statement:
The continue statement in python is used to bring the program control to the beginning of the
loop.
The continue statement skips the remaining lines of code inside the loop and start with the next
iteration.
It is mainly used for a particular condition inside the loop so that we can skip some specific code
for a particular condition.
syntax:
continue #used in loop
Ex:
for i in range(0, 7):
if(i==5):
break
print("Value of i is :",+i)
Output:
Value of i is : 0
Value of i is : 1
Value of i is : 2
Value of i is : 3
Value of i is : 4
Value of i is : 6
Ex:
for val in "string":
if val == "i":
continue
print(val)
print("The end")
Output:
s
t
r
n
g
The end
Page | 16
pass statement:
In Python, pass keyword is used to execute nothing; it means, when we don't want to execute code,
the pass can be used to execute empty.
It is same as the name refers to. It just makes the control to pass by without executing any code.
If we want to bypass any code pass statement can be used.
Syntax:
pass #used in loop
Ex:
for i in range(0, 7):
if(i==5):
pass
print("we got pass ")
print("Value of i is :",+i)
Output:
Value of i is : 0
Value of i is : 1
Value of i is : 2
Value of i is : 3
Value of i is : 4
we got pass
Value of i is : 5
Value of i is : 6
1. Tuple
Tuple is an ordered sequence of items same as list.
Tuple can contain data of different types.
Tuple are immutable means it can not be modified.
The items of the tuple are separated with a comma (,) and enclosed in parentheses ( ).
Ex: : >> tuple = ('aman', 678, 20.4, 'saurav')
>> tuple1 = (456, 'rahul')
>> tuple # To Print list
( 'aman', 678, 20.4, 'saurav' )
>> list[1:3] #To print list from 1 to 2
(678, 20.4)
>> tuple + tuple1 #To concatenate 2 tuple
Output ('aman', 678, 20.4, 'saurav', 456, 'rahul')
>>> tuple1*2 # To repeat tuple 2 times
(456, 'rahul', 456, 'rahul')
Page | 18
Operator Description Example
The repetition operator enables the tuple elements to be T1*2 = (1, 2, 3, 4, 5, 1,
Repetition 2, 3, 4, 5)
repeated multiple times.
It concatenates the tuple mentioned on either side of T1+T2 = (1, 2, 3, 4, 5, 6,
Concatenation 7, 8, 9)
the operator.
It returns true if a particular item exists in the tuple print (2 in T1) prints
Membership True.
otherwise false.
for i in T1:
print(i)
Output
1
Iteration The for loop is used to iterate over the tuple elements. 2
3
4
5
Length It is used to get the length of the tuple. len(T1) = 5
SN Function Description
It compares two tuples and returns true if tuple1 is greater than tuple2
1 cmp(tuple1, tuple2)
otherwise false.
2 len(tuple) It calculates the length of the tuple.
3 max(tuple) It returns the maximum element of the tuple.
4 min(tuple) It returns the minimum element of the tuple.
5 tuple(seq) It converts the specified sequence to the tuple.
2. List
List is an ordered sequence of items. List are mutuable means it can be modified.
list can contain data of different types.
The items stored in the list are separated with a comma (,) and enclosed within square brackets [ ].
We can use slice [:] operators to access the data of the list.
The concatenation operator (+) are used to join lists and repetition operator (*) are used to multiply
list.
Ex: >> list=[ 'aman', 678, 20.4, 'saurav' ]
>> list1=[ 456, 'rahul' ]
>> list # To Print list
[ 'aman', 678, 20.4, 'saurav' ]
>> list[1:3] #To print list from 1 to 2
[678, 20.4]
>> list + list1 #To concatenate 2 list
Output ['aman', 678, 20.4, 'saurav', 456, 'rahul']
>>> list1*2 # To repeat list 2 times
[456, 'rahul', 456, 'rahul']
Page | 19
Consider a List l1 = [1, 2, 3, 4], and l2 = [5, 6, 7, 8]
Operator Description Example
The repetition operator enables the list elements to be L1*2 = [1, 2, 3, 4, 1,
Repetition 2, 3, 4]
repeated multiple times.
It concatenates the list mentioned on either side of the l1+l2 = [1, 2, 3, 4, 5,
Concatenation 6, 7, 8]
operator.
It returns true if a particular item exists in a particular list print(2 in l1) prints
Membership True.
otherwise false.
for i in l1:
print(i)
Output
Iteration The for loop is used to iterate over the list elements. 1
2
3
4
Length It is used to get the length of the list len(l1) = 4
Iterating a List
List = ["John", "David", "James", "Jonathan"]
for i in List:
print(i);
Output:
John
David
James
Jonathan
Page | 21
11 list.sort([func]) It sorts the list by using the specified compare function if given.
List VS Tuple
SN List Tuple
1 The literal syntax of list is shown by the []. The literal syntax of the tuple is shown by the ().
2 The List is mutable. The tuple is immutable.
3 The List has the variable length. The tuple has the fixed length.
The list provides more functionality than
4 The tuple provides less functionality than the list.
tuple.
The list Is used in the scenario in which we The tuple is used in the cases where we need to store
need to store the simple collections with no the read-only collections i.e., the value of the items
5
constraints where the value of the items can can not be changed. It can be used as the key inside
be changed. the dictionary.
3. Dictionary
Dictionary is an a collection which is unordered, changeable and indexed.
In Python dictionaries are written with curly brackets { }, and they have keys and values.
Ex:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
Output: {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
To access dictionary, You can access the items of a dictionary by referring to its key name,
inside square brackets:
Get( ) method also gives same result.
Ex: >> x = thisdict["model"]
Mustang
>> x = thisdict.get("model")
Mustang
To Update dictionaries, You can change the value of a specific item by referring to its key
name:
Ex: thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018
print(thisdict)
>> {'brand': 'Ford', 'model': 'Mustang', 'year': 2018}
Iterating Dictionary
# for loop to print all the keys of a dictionary #for loop to print all the values of the dictionry
Employee={"Name":"John","Age":29, Employee={"Name":"John","Age":29,
"salary":25000,"Company":"GOOGLE"} "salary":25000,"Company":"GOOGLE"}
for x in Employee: for x in Employee:
print(x); print(Employee[x]);
Output: Output:
Name 29
Company GOOGLE
salary John
Age 25000
Page | 23