Department of First Year Engineering Programming and Problem Solving
Department of First Year Engineering Programming and Problem Solving
2.1.1 Tuples
Q. What is tuple? Explain how to access, add and remove elements in a tuple
Tuple is a data structure supported by python.
A tuple is a sequence of immutable objects. That means you cannot change the
values in a tuple.
Tuples use parentheses to define its elements.
Tup1=(1,2,3,4,5,6,7,8,9,10)
print(“Tup[3:6]=”,Tup1[3:6])
1
print(“Tup[:8]=”,Tup1[:8])
print(“Tup[4:]=”, Tup1[4:])
output:
Tup[3:6]=(4,5,6)
Tup[:8]=(1,2,3,4,5,6,7,8)
Tup[4:]=(5,6,7,8,9,10)
Tuples are immutable means we cannot add new element into it.
Also it is not possible to change the value of tuple.
Program:
tup1=(“Kunal”,”Ishita”,”Shree”,”Pari”,“Rahul”)
tup1[5]=”Raj”
print(tup1)
Output:
It will raise an error because new element cannot be added.
Since tuple is an immutable data structure, you cannot delete value(s) from it.
Program:
Tup1=(1,2,3,4,5)
del Tup1[3]
print(Tup1)
output: It will raise error as ‘tuple’ object doesn’t support item deletion.
2
However, we can delete the entire tuple by using the “del” statement.
Example:
Tup1=(1,2,3,4,5)
del Tup1
Operations on Tuple
3
Length – len() -It will return length of X=(10,11,12,13,14, 6
given tuple 15)
print(len(X))
Maximum – -It will return X=(10,11,12,13,14, 15
max() maximum value from 15)
tuple print(max(X))
-
X=(10,11,12,13,14, 10
Minimum()- It will return minimu 15)
min() value from tuple print(min(X))
2.1.2 Lists
Q. What is list? Explain how elements are accessed, added and removed from list.
List is a data type in python.
List is a collection of values (items / elements).
The items in the list can be of different data types.
The elements of the list are separated by comma (,) and written between square
brackets [ ].
List is mutable which means the value of its elements can be changed.
Syntax:
List = [value1, value2, …]
Example1:
List1 = [1,2,3,4]
print(List1)
Output:
[1, 2, 3, 4]
Example 2:
List2 = ['John','PPS',94]
print(List2)
Output:
4
['John','PPS',94]
print(List2[0:2])
Output:
PPS
['John', 'PPS']
Example:
print(List2)
List2.remove(List2[0])
print(List2)
List2.remove(94)
print(List2)
Output:
['Sam', 'PPS', 94, 'FE']
['Sam', 94, 'FE']
[94, 'FE']
['FE']
Operations on list
Q. Explain various operations on list.
List behave like similar way as string when operators like concatenation (+), and
repetition (*) are used and returns new list rather a string.
List supports various operations as listed below:
6
Slice [] - It will give you Example: PPS
element from a List2 =
specified index. ['John','PPS',94]
print(List2[1])
Range slice[:] -It will give you X=[10,11,12,13,14, [10,11,12]
elements from 15]
specified range slice. Z=X[0:3]
-Range slice contains print(z)
inclusive and
exclusive slices
Memebership(in) -It will check whether X=[10,11,12,13,14, TRUE
given value present in 15]
list or not. – print(11 in X)
accordingly it will
return Boolean value
Length – len() -It will return length of X=[10,11,12,13,14, 6
given list 15]
print(len(X))
2.1.3 Sets
1. Create a Set:
thisset = {"apple", "banana", "cherry"}
print(thisset)
2. Set Items
Set items are unordered, unchangeable, and do not allow duplicate values.
7
3. Unordered
Unordered means that the items in a set do not have a defined order.
Set items can appear in a different order every time you use them, and cannot be referred to
by index or key.
4. Unchangeable
Set items are unchangeable, meaning that we cannot change the items after the set has been
created.
NOTE –
Once a set is created, you cannot change its items, but you can remove
items and add new items.
2. Removing Elements
my_set.remove(2) # Removes the element (throws an error if not found)
print (my_set)
output :
{1, 3, 4}
3. Clear Elements
my_set.clear() # Empties the set
print (my_set)
output :
set( )
9. Membership Testing
my_set = {1, 2, 3}
print(1 in my_set) # True
print(5 in my_set) # False
Output :
True
False
9
Q. What is dictionary? Explain how to create dictionary, access, add and remove elements
from dictionary.
2.1.4 Dictionary
Dict = {key1: value1, key2: value2, key3: value3 ............. keyN: valueN.}
Creating Dictionary
The syntax to create an empty dictionary can be given as:
Dict = { }
The syntax to create a dictionary with key value pair is:
Dict = {key1: value1, key2: value2, key3: value3}
Example1:
Dict = { }
Print(Dict)
Output:
{}
Example2:
Dict = {1: "PPS", 2: "PHY"}
10
print(Dict)
Output:
{1: 'PPS', 2: 'PHY'}
11
{1: 'PPS', 2: 'SME'}
Operations on Dictionary:
Method Description
2.2.1 if
1. If statements:
If statement is a simplest form of decision control statements that is frequently
used in decision making.
If statements may include one statement or N statements enclosed within the if
block
If the expression is true the statements of if block get executed, otherwise these
statements will be skipped and the execution will be jump to statement just
outside if block.
Syntax:
if (expression/condition):
Block of statements
Statements ouside if
Flowchart:
13
Example:
a=2
if (a<3):
print(a);
if (a>3):
print('Hi')
Output: 2
2.2.2 if-else
In simple if statement, test expression is evaluated and if it is true the statements
in if block get executed, But if we want a separate statements to be get executed
if it returns false in this case we have to use if..else control statement.
if else statement has two blocks of codes, each for if and else.
The block of code inside if statement is executed if the expression in if statement
is TRUE, else the block of code inside else is executed.
Syntax:
if (expression/condition):
Block of statements
else:
Block of statements
Flowchart:
Example:
x=5
if (x<10):
print (“Condition is TRUE”)
14
else:
print (“Condition is FALSE”)
output:
Condition is TRUE
2.2.3 if-elif-else
Python supports if..elif..else to test additional conditions apart from the initial test
expression.
It work just like a if…else statement.
The programmer can have as many elif statements/branches as he wants depending
on the expressions that have to be tested.
A series of if..elif statements can have a final else block, which is called if none of
the if or elif expression is true.
Syntax:
if (expression/condition):
Block of statements
elif (expression/condition):
Block of statements
elif (expression/condition):
Block of statements
else:
Block of statements
Flowchart:
15
Example:
x=5
if (x == 2):
Output:
x is greater than 2
2.2.4 nested if
In nested if else statements, if statement is nested inside an if statements. So, the nested if
statements will be executed only if the expression of main if statement returns TRUE.
Syntax:
if (expression/condition):
16
if (expression/condition):
statements
else:
statements
else:
statements
Flowchart
Example
x=5
if (x<=10):
if(x==10):
print (“Number is Ten”)
else:
print (“Number is less than Ten”)
else:
print (“Number is greater than Ten”)
17
2.3 Basic loop Structures/Iterative statements:
Q. Explain looping statements with flowchart.
Iterative statements are decision control statements that are used to repeat the
execution of a list of statements.
Python language supports two types of statements while loop and for loop.
As shown in the syntax above, in the while loop condition is first tested.
If the condition is True, only then the statement block will be executed.
Otherwise, if the condition is False the control will jump to statement y, that is the
immediate statement outside the while loop block.
Flowchart:
18
Example:
Program to print numbers from 0 to 10.
i=0
while (i<10):
print(i, end=” “)
i=i+1
Output: 0 1 2 3 4 5 6 7 8 9
Syntax:
for loop_control_var in sequence:
statement block1
statement x
19
The range( ) function produces a sequence of numbers starting with
beginning(inclusive) and ending with one less than the number end. The step
argument is optional
Flowchart:
Example:.
Output: Output:
1 2 3 4 1 35 7 9
20
controlled loop, tests the condition after the loop is executed.
If condition is not met in entry-controlled loop, then the loop will never execute.
However, in case of post-test, the body of the loop is executed unconditionally for
the first time.
If the requirement is to have a pre-test loop, then choose a for loop or a while loop.
The table below shows comparison between ore-test loop and post-test loop.
Feature Pre-test Loop Post-test Loop
Initialization 1 2
Number of tests N+1 N
Statements executed N N
Loop control variable update N N
Minimum Iterations 0 1
21
Comparison between condition-controlled and counter controlled loop:
Attitude Counter-controlled loop Condition Controlled loop
Number of execution Used when number of times Used when number of times
the loop has to be executed is the loops has to be executed
known in advance. is not known in advance.
Condition Variable In counter-controlled loops, In condition-controlled
we have a counter variable. loops, we use a sentinel
variable.
Value and limitation of The value of the counter The value of the counter
variable variable and the condition variable and the condition
for loop execution, both are for loop execution, both are
strict. strict.
Example i=0 i=1
while (i<=10): while(i>0):
print(i,end= " ") print(i,end= " ")
i+=1 i+=1
if (i==10):
break
Example:
for i in range(0, 5):
for j in range(0, i+1):
22
print("* ",end="")
print("\r")
Output
*
**
***
****
*****
Example 2:
lastNumber = 6
for row in range(1, lastNumber):
for column in range(1, row + 1):
print(column, end=' ')
print("")
Output
1
12
123
1234
12345
Output:
w
e
l
2.5.2 continue
Continue statement can appear only in the body of loop.
When the continue statement encounters, then the rest of the statements in the loop
are skipped
The control is transferred to the loop-continuation portion of the nearest enclosing
loop.
Its syntax is simple just type keyword continue as shown below
continue
Example:
for i in "welcome": w
if(i=="c"): e
continue l
print(i) o
m
e
24
We can say continue statement forces the next iteration of the loop to take place,
skipping the remaining code below continue statement.
while(…): for(…):
… …
if condition: if condition:
continue continue
…. …
……. …
2.5.3 pass
25
It is used when a statement is required syntactically but you do not want any command
or code to execute.
The pass statement is a null operation.
Nothing happens when it executes.
It is used as placeholder.
In a program where for some conditions you don’t want to execute any action or what
action to be taken is not yet decided, but we may wish to write some code in future, In
such cases pass can be used.
Syntax:
Pass
Example:
for i in “welcome”:
if (i == 'c'):
pass
print (i)
Output:
w
e
l
c
o
m
e
2.5 else statement used with loops
In for loop, the else keyword is used to specify a block of code to be executed after
completion of loop.
If the else statement is used with a for loop, the else statement is executed when the
loop has completed iterating.
But when used with the while loop, the else statement is executed when the
condition becomes false.
Example 1 (For ‘for loop’): Print numbers from 0 to 10 and print a message when
the loop is ended.
for x in range(11):
26
print(x)
else:
print(“Loop is finished”)
Output:
27