Unit Ii, PPS PDF

Download as pdf or txt
Download as pdf or txt
You are on page 1of 23

Unit-II: Problem Solving, Programming and Python Programming

Decision Control Statements

 Decision Control Statements:


 The decision control statements are the decision making statements that decides the order of
execution of statements based on the conditions.
 In the decision making statements the programmer specify which conditions are to be executed or
tested with the statements to be executed if the condition is true or false.
 Condition checking is the backbone of decision making.
 We have the two types of Control statement in Python:
1. Selection/Decision Control Statement: If, If..else, if…elif….else.
2. Flow Control Statement: for, while break, continue
3. Other Data Types : List, Tuple, Dictionary

 Selection/conditional branching Statements:


1. if statement
2. if..else statement
3. if…elif….else statement

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

2. Write a python program to print the largest of the three numbers.


a = int(input("Enter a? "));
b = int(input("Enter b? "));
c = int(input("Enter c? "));
if a>b and a>c:
print("a is largest");
if b>a and b>c:
print("b is largest");
if c>a and c>b:
print("c is largest");
Output:
Enter a? 15
Enter b? 35
Enter c? 25
b is largest

3. Write a python program to check number is even or odd.


num = int(input("enter the number?"))
if num%2 == 0:
print("Number is even")
if num%2 == 1:
print(“Number is odd”)
Output:
enter the number? 5
Number is odd

4. Write a python program to check number is positive or negative or zero.


num = int(input("enter the number?"))
if num < 0: Output:
print("Number is negative") enter the number? 0
if num > 0: Number is zero
print(“Number is Positive”)
if num == 0:
print(“Number is zero”)
Page | 2
2. if..else statement
 The else statement can be used with the if statement.
 If expression in if statement is becomes true,
then if block is executed
otherwise (false) else block is executed.
 It is optional to use the else statement with if statement it
depends on your expression.
 The syntax for If….Else Statement is as:
if (expression): #body of if
statement1
statement2
else: #body of else
statement1
statement2

1. Write a python program to print the number is even or odd


num = int(input("Enter number? "));
if num%2==0:
print(“even no");
else:
print(“Odd no");

Output:
Enter number? 25
Odd no

2. Write a python Program to check whether a person is eligible to vote or not.


age = int (input("Enter your age? "))
if age>=18:
print("You are eligible to vote !!");
else:
print("Sorry! you have to wait !!");
Output:
Enter your age? 25
You are eligible to vote !!

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

1. Write a python Program to check number is 10 , 50 , 100 or not.


number = int(input("Enter the number?"))
if number==10:
print("number is equals to 10")
elif number==50:
print("number is equal to 50");
elif number==100:
print("number is equal to 100");
else:
print("number is not equal to 10, 50 or 100");
Output:
Enter the number? 25
number is not equal to 10, 50 or 100

2. Write a python Program to take marks and display grades


marks = int(input("Enter the marks? "))
if marks > 85 and marks <= 100:
print("Congrats ! you scored grade A ...")
elif marks > 60 and marks <= 85:
print("You scored grade B + ...")
elif marks > 40 and marks <= 60:
print("You scored grade B ...")
elif (marks > 30 and marks <= 40):
print("You scored grade C ...")
else:
print("Sorry you are fail ?")
Output:
Enter the marks? 55
You scored grade B ...

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.

1. Write a python program to check number is positive, negative, or zero.


num = float(input("Enter a number: "))
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")

Output:
Enter a number: 5
Positive number

Basic loop structures/ iterative statements


 The flow of the programs written in any programming language is sequential by default.
 Repeated execution of set of statements is called iteration.
 The execution of a specific code may need to be repeated several numbers of times.
 For this purpose, The programming languages provide various types of loops which are capable of
repeating some specific code several numbers of times.

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

2. Write a python program to print series of number of 2 using while loop.


i=2;
while i<=20:
print(i);
i=i+2;
Output:
2 4 6 8 10 12 14 16 18 20

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.

num = int(input("Enter a number: "))


sum = 0
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10

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

2. Write a python program to print 1 + ½ + 1/3 + ¼ + ……. + 1/N series.


n=int(input("Enter the n value"))
sum=0
for i in range (1,n+1):
sum=sum+1/i

print("The sum is: ",+sum)


Output:
Enter the n value5
The sum is: 2.283333333333333

3. Write a python program to check given number is prime number or not.


1. Prime numbers:
 A prime number is a natural number greater than 1 and having no positive divisor other than 1 and
itself.
 For example: 3, 7, 11 etc are prime numbers.
2. Composite number:
 Other natural numbers that are not prime numbers are called composite numbers.
 For example: 4, 6, 9 etc. are composite numbers.

num=int(input("Enter the number"))


if num>1:
for i in range(2,num):
if (num % i) == 0:
print(num,"is not a prime number")
break
else:
print(num,"is a prime number")
else:
print(num,"is not a prime number")

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

print("Factorial of {0} number is: {1} ".format(n,factorial))


Output:
Enter the number5
Factorial of 5 number is: 120

 Selecting Appropriate Loop:


 There are various types of loops
1. Pre-test loop
2. Post-test loop
3. Condition controlled loop
4. Counter controlled loop

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.

4. Counter controlled loop:


 When we know for how many number of times the loop will be executed, then we use counter
controlled loop.
 The counter controlled loop is also called as definite repetition loop.
 The counter controlled loop is normally implemented using for loop, we also use while loop, but
for 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
*
**
***
****

2. Write a python program to display the star pattern


*****
****
***
**
*
Program:
n=int(input("Enter the number"))
for i in range(n+1,0,-1):
for j in range(0,i-1):
print("*", end="")
print("")
Output:
Enter the number5
*****
****
***
**
*

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

2. Write a python program to display the pattern


1
1 2
1 2 3
1 2 3 4
Program:
n=int(input("Enter the number"))
for i in range(1,n):
for j in range(n,i,-1):
print(" ", end=" ")
for k in range(1, i+1):
print(k, end=" ")
print("")
Output:
Enter the number 5
1
1 2
1 2 3
1 2 3 4

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

 Else statement used with Loops:


 else block is placed after the for or while loop
 else statement is executed only when loop is not terminated by break statement.
1. else statement with for loop
2. else statement with while loop

1. else statement with for loop


syntax:
for variable in sequence:
Body of for loop
else: # else with for loop
statement1
Ex: without using break statement with using break statement
for i in range(0,5): for i in range(0,5):
print(i) print(i)
else: break
print("no break.") else:
print("break exist.")
Output: Output:
0 1 2 3 4 no break 0
Page | 17
1. else statement with while loop
syntax:
while expression:
Body of while loop
else: # else with for loop
statement1
Ex: without using break statement with using break statement
i=1; i=1;
while i<=5: while i<=5:
print(i) print(i)
i=i+1 i=i+1
else: break
print("no break"); else:
print("break exist ");
Output: Output:
1 2 3 4 5 6 no break 1

 Other Data Types: Tuple, List, Dictionaries

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')

 Tuple are immutable means it can not be modified


Ex: : >> tuple = ('aman', 678, 20.4, 'saurav')
>> tuple[2]= 758
TypeError: 'tuple' object does not support item assignment

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

Python Tuple inbuilt functions:

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

Adding elements to the list


 Python provides append( ) function by using which we can add an element to the list.
 However, the append( ) method can only add the value to the end of the list.
 Consider the following example in which, we are taking the elements of the list from the user and
printing the list on the console.
Ex:
l =[];
n = int(input("Enter the number of elements in the list"));
for i in range(0,n): # for loop to take the input
l.append(input("Enter the item?"));
print("printing the list items....");
for i in l:
print(i, end = " ");
Output:
Enter the number of elements in the list4
Enter the item?12
Enter the item?5
Page | 20
Enter the item?6
Enter the item?8
printing the list items....
12 5 6 8

Removing elements from the list


List = [0,1,2,3,4]
print("printing original list: ");
for i in List:
print(i,end=" ")
List.remove(0)
print("\nprinting the list after the removal of first element...")
for i in List:
print(i,end=" ")
Output:
printing original list:
0 1 2 3 4
printing the list after the removal of first element...
1 2 3 4

Python List Built-in functions :


SN Function Description
1 cmp(list1, list2) It compares the elements of both the lists.
2 len(list) It is used to calculate the length of the list.
3 max(list) It returns the maximum element of the list.
4 min(list) It returns the minimum element of the list.
5 list(seq) It converts any sequence to the list.

Python List built-in methods:


SN Function Description
1 list.append(obj) The element represented by the object obj is added to the list.
2 list.clear() It removes all the elements from the list.
3 List.copy() It returns a shallow copy of the list.
4 list.count(obj) It returns the number of occurrences of the specified object in the list.
5 list.extend(seq) The sequence represented by the object seq is extended to the list.
6 list.index(obj) It returns the lowest index in the list that object appears.
7 list.insert(index, obj) The object is inserted into the list at the specified index.
8 list.pop(obj=list[-1]) It removes and returns the last object of the list.
9 list.remove(obj) It removes the specified object from the list.
10 list.reverse() It reverses the list.

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}

 To delete element in dictionaries, use del keyword


Page | 22
>> del thisdict["year"]

Built-in Dictionary functions:


SN Function Description
It compares the items of both the dictionary and returns true if the first
1 cmp(dict1, dict2) dictionary values are greater than the second dictionary, otherwise it returns
false.
2 len(dict) It is used to calculate the length of the dictionary.
3 str(dict) It converts the dictionary into the printable string representation.
4 type(variable) It is used to print the type of the passed variable.

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

You might also like