Cse90d Unit2
Cse90d Unit2
Example-
a) Input: if 5 > 2: Output: Five is greater than two!
print("Five is greater than two!“)
Example-
Input: i=10
if (i>15):
print (“10 is less than 15”)
print (“I am not in if”)
Output: I am not in if
Relational Operators
Logical operators perform Logical AND, Logical OR and Logical NOT operations.
and: Logical AND- True if both the operands are true.
or: Logical OR- True if either of the operands are true.
not: Logical NOT- True if operand is false.
Bitwise Operators
With the while loop we can execute a set of statements as long as a condition is true.
Print i as long as i is less than 6:
i=1
while i<6:
print(i)
i+=1
While Loop- Break Statement
With the break statement we can stop the loop even if the while condition is true:
Exit the loop when i is 3:
i=1
while i<6:
print(i)
if i==3:
break
i+=1
While Loop- Continue Statement
With the continue statement we can stop the current iteration, and continue with the next:
Continue to the next iteration if i is 3:
i=0
while i<6
i+=1
if i==3:
continue
print (i)
While Loop- Else Statement
With the else statement we can run a block of code once when the condition no longer is true:
Print a message once the condition is false:
i=1
while i<6:
print(i)
i+=1
else:
print(“i is no longer less than 6”)
For Loop
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a
set, or a string).
With the for loop we can execute a set of statements, once for each item in a list, tuple,
set etc.
The for loop does not require an indexing variable to set beforehand.
Print each fruit in a fruit list:
fruits=[“apple”, “banana”, “cherry”]
for x in fruits:
print(x)
For Loop- Through String
With the break statement we can stop the loop before it has looped through all the items:
Exit the loop when x is “banana”:
fruits=[“apple”, “banana”, “cherry”]
for x in fruits:
print(x)
if x==“banana”:
break
For Loop- Continue Statement
With the continue statement we can stop the current iteration of the loop, and continue
with the next:
Does not print banana:
fruits=[“apple”, “banana”, “cherry”]
for x in fruits:
if x==“banana”:
continue
print(x)
For Loop- Range() Function
The else keyword in a for loop specifies a block of code to be executed when the loop is
finished.
Print all numbers from 0 to 5, and print a message when the loop has ended.
for x in range(6):
print(x)
else:
print(“Finally finished!”)
For Loop- Nested Loop
If for loop, for some reason, has no content, put in pass statement to avoid getting an
error.
for x in [0, 1, 2]:
pass
Collections
Introduction
Python programming language has four collection data types- list, tuple, set and dictionary.
But python also comes with a built-in module known as collections which has specialized
data structures which basically covers for the shortcomings of the four data types.
List
When we say that lists are ordered, it means that the items have a defined order, and that
order will not change.
If we add new items to a list, the new items will be placed at the end of the list.
List Items- Changeable
The list is changeable, meaning that we can change, add, and remove items in a list after it
has been created.
List Items- Allow Duplicates
Since lists are indexed, lists can have items with the same value:
Lists allow duplicate values:
thislist=[“apple”, “banana”, “cherry”, “apple”, “cherry”]
print(thislist)
List Length
From Python's perspective, lists are defined as objects with the data type 'list':
mylist=[“apple”, “banana”, “cherry”]
print(type(mylist))
list() constructor
It is also possible to use the list() constructor when creating a new list.
To use this, we mandatorily enclose the values of list in double round-brackets.
thislist=list((“apple”, “banana”, “cherry”))
print(thislist)
Tuple
When we say that tuples are ordered, it means that the items have a defined order, and that
order will not change.
Tuple Items- Unchangeable
Tuples are unchangeable, meaning that we cannot change, add or remove items after the
tuple has been created.
Tuple Items- Allow Duplicates
Since tuple are indexed, tuples can have items with the same value.
Tuples allow duplicate values:
thistuple=(“apple”, “banana”, “cherry”, “apple”, “cherry”)
print(thistuple)
Tuple Length
To create a tuple with only one item, we have to add a comma after the item.
thistuple=(“apple”,)
print(type(thistuple))
Tuple type()
From Python's perspective, tuples are defined as objects with the data type 'tuple':
mytuple=(“apple”, “banana”, “cherry”)
print(type(mytuple))
tuple() Construtor
Set items are unordered, unchangeable, and do not allow duplicate values.
Set items can be of any data type:
set1={“apple”, “banana”, “cherry”}
set2={1, 5, 7, 9, 3}
Set3={True, False, False}
A set can contain different data types:
set1={“abc”, 34, True, 40, “male”}
Set Items- 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.
Set Items- Unchangeable
Sets are unchangeable, meaning that we cannot change the items after the set has
been created.
Once a set is created, you cannot change its items, but you can add new items.
Set Items- Duplicates not Allowed
From Python's perspective, sets are defined as objects with the data type 'set„.
myset={“apple”, “banana”, “cherry”}
print(type(myset))
set() Constructor
Dictionary items are unordered, changeable, and does not allow duplicates.
Dictionary items are presented in key:value pairs, and can be referred to by using the key
name.
Print the "brand" value of the dictionary:
thisdict={
“brand”: ”Ford”,
“model”: ”Mustang”,
“year”: 1964
}
print(thisdict[“brand”])
Dictionary Items (Contd.)
When we say that dictionaries are unordered, it means that the items does not have a
defined order, we cannot refer to an item by using an index.
Dictionary Items- Changeable
Dictionaries are changeable, meaning that we can change, add or remove items after the
dictionary has been created.
Dictionary Items- Duplicates not Allowed
From Python's perspective, dictionaries are defined as objects with the data type 'dict„.
Print the data type of a dictionary:
thisdict={
“brand”: “Ford”,
“model”: “Mustang”,
“year”: 1964
}
print(type(thisdict))
Sorting Dictionaries
Python dictionary is the collection of data which stored in the key-value form. Each key is
associated with its value. It is mutable in nature, which means we can change data after
its creation.
It is the unordered collection of the data and allows storing duplicate values, but the key
must be unique.
Dictionary is declared using the curly braces {}, and the key-value pair is separated by a
comma.
dict1 = {'name': 'Devansh', 'age': 22, 'Rollno':90014}
print(dict1)
Cont..
Sorting by keys
Sorting by values
Sorting Algorithm
Reversing the sorted order
Sorting By Keys and Values
Python offers the built-in keys functions keys() and values() functions to sort the dictionary.
It takes any iterable as an argument and returns the sorted list of keys.
We can use the keys to sort the dictionary in the ascending order. Let's understand the
following example.
names = {1:'Alice' ,2:'John' ,4:'Peter' ,3:'Andrew' ,6:'Ruffalo' ,5:'Chris' }
#print a sorted list of the keys
print(sorted(names.keys()))
#print the sorted list with items.
print(sorted(names.items()))
Output of Example
[1, 2, 3, 4, 5, 6]
[(1, 'Alice'), (2, 'John'), (3, 'Andrew'), (4, 'Peter'), (5, 'Chris'), (6, 'Ruffalo')]
Sorting Algorithm
There are various sorting algorithm to sort a dictionary; we can use other arguments in the
sorted method. Let's understand the following example.
daynames = { 'one' : 'Monday' , 'six' : 'Saturday' ,'three' : 'Wednesday' , 'two' : 'Tuesday' , 'fi
ve': 'Friday' , 'seven': 'Sunday' }
print(daynames)
number = { 'one' : 1 , 'two' : 2 , 'three' : 3 , 'four' : 4 , 'five' : 5 , 'six' : 6 , 'seven' : 7}
print(sorted(daynames , key=number.__getitem__))
print([daynames[i] for i in sorted(daynames , key=number.__getitem__)])
Output
{'one': 'Monday', 'six': 'Saturday', 'three': 'Wednesday', 'two': 'Tuesday', 'five': 'Friday', 'seven':
'Sunday'}
['one', 'two', 'three', 'five', 'six', 'seven']
['Monday', 'Tuesday', 'Wednesday', 'Friday', 'Saturday', 'Sunday']
Reverse the sorted Order
The dictionary can be reversed using the reverse argument. Let's understand the following
example.
Example -
a = {'a':2 ,'b':1 ,'c':3 ,'d':4 ,'e':5 ,'f':6 }
print(sorted(a.values() , reverse= True))
Output:
[6, 5, 4, 3, 2, 1]
Copying Collections
Copy in Python
The assignment operator is used to create the copy of the Python object, but this is not
true; it only create the binding between a target and object. When we use the
assignment operator, instead of creating a new object, it creates a new variable that
shares the old object's reference.
The copies are helpful when a user wants to make changes without modifying the original
object at the same time. A user also prefers to create a copy to work with mutable
objects.
Example -