Python Notes - Unit 2
Python Notes - Unit 2
if condition :
block
Example :
if x < 10:
y=x
could be written
if x < 10: y = x
if x < 10:
y=x
Example :
can be rewritten as
if condition :
if block
else:
else block
➢ The reserved word if begins the if/else statement.
➢ The condition is a Boolean expression that determines whether or not the if block or the
else block will be executed. A colon (:) must follow the condition.
Example :
>>> a=2
>>> b=4
>>> print (a) if a>b else print (b)
4
Iteration
Iteration repeats the execution of a sequence of code. Iteration is useful for solving many
programming problems.
(i) The while Statement The while statement has the general form:
while condition :
block
range( [begin],end,[step] )
where
• begin is the first value in the range; if omitted, the default value is 0
• end is one past the last value in the range; the end value may not be omitted
• change is the amount to increment or decrement; if the change parameter is omitted, it defaults
to 1 (counts up by ones)
Note : begin, end, and step must all be integer values; floating-point values and other types are
not allowed.
The following examples show how range can be used to produce a variety of sequences:
The break statement : Python provides the break statement to implement middle-exiting control logic. The
break statement causes the immediate exit from the body of the loop.
n=5
for i in range(1,n+1):
if i==3:
break
print (i)
print ("end of Prog")
The continue statement : the continue statement stop the current iteration of the
loop, and continue with the next iteration.
n=5
for i in range(1,n+1):
if i==3:
continue
print (i)
print ("end of Prog")
Else in For Loop : The else keyword in a for loop specifies a block of code to
be executed when the loop is finished:
Example1 :
n=5
for i in range(1,n+1):
print (i)
else:
print ("end of for loop")
print("End of Prog")
Example 2:
n=5
for i in range(1,n+1):
if i==3:
break
print (i)
else:
print ("end of for ")
print ("end of Prog")
(ii) List
Lists are just like the arrays, declared in other languages which is an ordered
collection of data. It is very flexible as the items in a list do not need to be of the
same type. List items can be accessed using a zero-based index in the
square brackets []. Indexes start from zero and increment by one
for each item. Accessing an item using a large index than the list's
total items would result in IndexError.
Example
mylist=[] # empty list
print(mylist)
print(nums[0]) # returns 1
print(nums[1]) # returns 2
print(nums[3]) # returns [4, 5, 6, [7, 8, [9]]]
print(nums[4]) # returns 10
print(nums[3][0]) # returns 4
print(nums[3][3]) # returns [7, 8, [9]]
print(nums[3][3][0]) # returns 7
print(nums[3][3][2]) # returns [9]
List Methods
List Method Description
list.clear() Removes all the items from the list and make it empty.
list.extend() Adds all the items of the specified iterable (list, tuple, set, dictionary, string) to the end of
the list.
list.index() Returns the index position of the first occurance of the specified item. Raises a ValueError if
there is no item found.
list.pop() Returns an item from the specified index position and also removes it from the list. If no
index is specified, the list.pop() method removes and returns the last item in the list.
list.remove() Removes the first occurance of the specified item from the list. It the specified item not
found then throws a ValueError.
list.reverse() Reverses the index positions of the elements in the list. The first element will be at the last
index, the second element will be at second last index and so on.
Operator Example
The + operator returns a list containing all the elements of the first and >>> L1=[1,2,3]
the second list. >>> L2=[4,5,6]
>>> L1+L2
[1, 2, 3, 4, 5, 6]
The * operator concatenates multiple copies of the same list. >>> L1=[1,2,3]
>>> L1*3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
The slice operator [] returns the item at the given index. A negative >>> L1=[1, 2, 3]
index counts the position from the right side. >>> L1[0]
1
>>> L1[-3]
1
>>> L1[1]
2
>>> L1[-2]
2
>>> L1[2]
3
>>> L1[-1]
3
The range slice operator [FromIndex : Untill Index - 1] fetches items >>> L1=[1, 2, 3, 4, 5, 6]
in the range specified by the two index operands separated by : symbol. >>> L1[1:]
If the first operand is omitted, the range starts from the index 0. If the [2, 3, 4, 5, 6]
second operand is omitted, the range goes up to the end of the list. >>> L1[:3]
[1, 2, 3]
>>> L1[1:4]
[2, 3, 4]
>>> L1[3:]
[4, 5, 6]
>>> L1[:3]
[1, 2, 3]
>>> L1[-5:-3]
[2, 3]
The in operator returns true if an item exists in the given list. >>> L1=[1, 2, 3, 4, 5, 6]
>>> 4 in L1
True
>>> 10 in L1
False
The not in operator returns true if an item does not exist in the given >>> L1=[1, 2, 3, 4, 5, 6]
list. >>> 5 not in L1
False
>>> 10 not in L1
True
Q. Write a program to input n names in a list and print it.
Q Write a program to input n data items in a list and perform sequencial search
n=int(input("Input value of N : "))
data=[] # create empty list
for i in range(1,n+1):
a=input('Input data item : ')
data.append(a)
s=input("Input data to search in list : ")
found=False
for i in range(0,n):
if data[i]==s :
found=True
break
if found==True :
print ("Data Found ")
else :
print ("Data Not Found ")
Q Write a program to input n data items in a list and perform sequencial search
n=int(input("Input value of N : "))
data=[] # create empty list
for i in range(1,n+1):
a=input('Input data item : ')
data.append(a)
s=input("Input data to search in list : ")
if s in data:
print("Data Found")
else:
print("Data Not Found")
(iii) Tuples
Tuple is an immutable (unchangeable) collection of elements of
different data types. It is an ordered collection, so it preserves the
order of elements in which they were defined.
nums = (1, 2, 3, 4, 5)
print(nums[0]) # prints 1
print(nums[1]) # prints 2
print(nums[4]) # prints 5
print(nums[-1]) # print 5
Tuple Operations
Like string, tuple objects are also a sequence. Hence, the operators
used with strings are also available for the tuple.
Operator Example
The + operator returns a tuple containing all the elements of the >>> t1=(1,2,3)
first and the second tuple object. >>> t2=(4,5,6)
>>> t1+t2
(1, 2, 3, 4, 5, 6)
>>> t2+(7,)
(4, 5, 6, 7)
The * operator Concatenates multiple copies of the same tuple. >>> t1=(1,2,3)
>>> t1*4
(1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3)
The [] operator Returns the item at the given index. A negative >>> t1=(1,2,3,4,5,6)
index counts the position from the right side. >>> t1[3]
4
>>> t1[-2]
5
The [:] operator returns the items in the range specified by two >>> t1=(1,2,3,4,5,6)
index operands separated by the : symbol. >>> t1[1:3]
Operator Example
If the first operand is omitted, the range starts from zero. If the (2, 3)
second operand is omitted, the range goes up to the end of the >>> t1[3:]
tuple. (4, 5, 6)
>>> t1[:3]
(1, 2, 3)
The in operator returns true if an item exists in the given tuple. >>> t1=(1,2,3,4,5,6)
>>> 5 in t1
True
>>> 10 in t1
False
The not in operator returns true if an item does not exist in the >>> t1=(1,2,3,4,5,6)
given tuple. >>> 4 not in t1
False
>>> 10 not in t1
True
Tuple Methods
List Method Description
Tuple.index() Searches the tuple for a specified value and returns the position of
first occurrence.
Python - Dictionary
The dictionary is an unordered collection that
contains key:value pairs separated by commas inside curly brackets.
Dictionaries are optimized to retrieve values when the key is known.
The key should be unique and an immutable object. A number,
string or tuple can be used as key.
Example: Dictionary
d = {} # empty dictionary
numNames={1:"One", 2: "Two", 3:"Three"} # int key, string value
The same key cannot appear more than once in a collection. If the
key appears more than once, only the last will be retained. The
value can be of any data type.
>>> type(numNames)
<class 'dict'>
dict.fromkeys() Creates a new dictionary from the given iterable (string, list, set, tuple) as keys and
Method Description
dict.items() Returns a dictionary view object that provides a dynamic view of dictionary
elements as a list of key-value pairs. This view object changes when the dictionary
changes.
dict.keys() Returns a dictionary view object that contains the list of keys of the dictionary.
dict.pop() Removes the key and return its value. If a key does not exist in the dictionary, then
returns the default value if specified, else throws a KeyError.
dict.popitem() Removes and return a tuple of (key, value) pair from the dictionary. Pairs are
returned in Last In First Out (LIFO) order.
dict.setdefault() Returns the value of the specified key in the dictionary. If the key not found, then it
adds the key with the specified defaultvalue. If the defaultvalue is not specified
then it set None value.
dict.update() Updates the dictionary with the key-value pairs from another dictionary or another
iterable such as tuple having key-value pairs.
dict.values() Returns the dictionary view object that provides a dynamic view of all the values in
the dictionary. This view object changes when the dictionary changes.
dict={}
while True:
print ("\n\n")
print ("1. Add Course and Fee")
print ("2. Course Fee")
print ("3. All Courses")
print ("4. Exit")
print ("============")
n=int(input("Input choice between 1-4 : "))
if n==4:
break
if n==2:
s=input("Input course name : ")
print ("Course Fee : ",dict[s])
if n==1:
cc=input("Input course name : ")
cn=input("Course Fee : ")
dict.setdefault(cc,cn)
if n==3:
for i in dict.keys():
print(i)
print("end of prog")