Python Unit - II
Python Unit - II
UNIT - II
Conditional Statement
if Statement
The if statement contains a logical expression using which data is compared and a
decision is made based on the result of the comparison.
Syntax:
if expression:
statement(s)
If the expression evaluates to TRUE, then the block of statement(s) inside the if
statement is executed. If expression evaluates to FALSE, then the first set of code after the end
of the if statement(s) is executed.
if…else… Statement
An else statement can be combined with an if statement. An else statement contains the
block of code that executes if the conditional expression in the if statement resolves to 0 or a
FALSE value.
The else statement is an optional statement and there could be at most only one else
statement following if.
Syntax:
if expression:
statement(s)
else:
statement(s)
Example:
a = 33
b = 200
if b > a:
print("b is greater than a")
else
print("a is greater than b")
elif Statement
The elif statement allows to check multiple expressions for TRUE and execute a block
of code as soon as one of the conditions evaluates to TRUE.
Similar to the else, the elif statement is optional. However, unlike else, for which there
can be at most one statement, there can be an arbitrary number of elif statements following an
if.
Syntax:
if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)
Example:
var = 100
if var == 200:
print ("Executes 1st Expression, Var is : ",var)
elif var == 150:
print ("Executes 2nd Expression, Var is : ",var)
elif var == 100:
print ("Executes 3rd Expression, Var is : ",var)
else:
print ("Executes Last Expression, Var is : ",var)
nested if Statement
There may be a situation need to check for another condition after a condition resolves
to true. In such a situation, the nested if construct is used.
In a nested if construct, an if... elif... else construct inside another if... elif... else
construct.
Syntax:
if expression1:
statement(s)
if expression2:
statement(s)
elif expression3:
statement(s)
elif expression4:
statement(s)
else:
statement(s)
else:
statement(s)
Example:
var = 100
if var < 200:
print "Expression value is less than 200"
if var == 150:
print "Which is 150"
elif var == 100:
print "Which is 100"
elif var == 50:
print "Which is 50"
else var < 50:
print "Expression value is less than 50"
else:
print "Could not find true expression"
String Operations
Python Strings
Strings in python are surrounded by either single quotation marks, or double quotation
marks.
Example: 'hello' is the same as "hello".
Assign String
a = "Hello"
print(a)
Multiline String
It can assign to a variable by using three double quotes or single qutoes
a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)
Check String
To check if a certain phrase or character is present in a string, we can use the keyword
in.
txt = "The best things in life are free!"
print("free" in txt) #Present
Slicing String
Return a range of characters by using the slice syntax.
Specify the start index and the end index, separated by a colon, to return a part of the
string.
b = "Hello, World!"
print(b[2:5])
Built in Methods
➢ Upper Case
➢ Lower Case
➢ Replace String
➢ Remove Whitespace
➢ Split String
Upper Case
It returns the string in Upper Case, upper()
a = "Hello, World!"
print(a.upper())
Lower Case
It returns the string in Lower Case, lower()
a = "Hello, World!"
print(a.lower())
Replace String
Replace the string with another string, replace()
a = "Hello, World!"
print(a.replace("H", "J"))
Remove Whitespace
Removes any whitespace from the beginning or the end, strip()
a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"
Split String
Splits the string into substrings if it finds instances of the separator
a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']
String Concatenation
To concatenate or combine two strings by using the + operator
a = "Hello"
b = "World"
c=a+b
print(c)
Format Strings
Combine strings and number by using format() method.
The format() methods takes the passed arguments, formats them, and places them in
the string where the placeholders {} are
age = 36
txt = "My name is Roy, and I am {}"
print(txt.format(age))
The format() method takes unlimited number of arguments, and are placed into the
respective placeholders
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))
Use index numbers {0} to be sure the arguments are placed in the correct placeholders
quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))
Escape Character
✓ To insert characters that are illegal in a string, use an escape character.
✓ An escape character is a backslash \ followed by the character you want to insert.
txt = "We are the so-called "Vikings" from the north." #Illegal Format
✓ To fix this problem use escape characters \”
txt = "We are the so-called \"Vikings\" from the north."
\t Tab
\b Backspace
\f Form Feed
\ooo Octal Value
\xhh Hex Value
Looping Statements
In general, statements are executed sequentially: The first statement in a function is
executed first, followed by the second, and so on. There may be a situation when you need to
execute a block of code several number of times.
Programming languages provide various control structures that allow for more
complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple times.
Python programming language provides following types of loops: while, for
break Statement
It terminates the current loop and resumes execution at the next statement, just like the
traditional break statement in C.
The most common use for break is when some external condition is triggered requiring
a hasty exit from a loop. The break statement can be used in both while and for loops.
In nested loops, the break statement stops the execution of the innermost loop and start
executing the next line of code after the block.
for letter in 'Python': # First Example
if letter == 'h':
break
print ('Current Letter :', letter)
continue Statement
It returns the control to the beginning of the while loop. The continue statement rejects
all the remaining statements in the current iteration of the loop and moves the control back to
the top of the loop.
The continue statement can be used in both while and for loops.
pass Statement
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.
for letter in 'Python':
if letter == 'h':
pass
print 'This is pass block'
print 'Current Letter :', letter
LISTS
The most basic data structure in Python is the sequence. Each element of a sequence is
assigned a number - its position or index. The first index is zero, the second index is one, and
so forth.
Python has some built-in types of sequences, but the most common ones are lists and
tuples.
Python Lists
The list is a most versatile datatype available in Python which can be written as a list
of comma-separated values (items) between square brackets. Important thing about a list is that
items in a list need not be of the same type. list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d"]
List Items
List items are ordered, changeable, and allow duplicate values.
List items are indexed, the first item has index [0], the second item has index [1] etc.
Ordered
Lists are ordered, it means that the items have a defined order, and that order will not
change.
New items to a list, the new items will be placed at the end of the list.
Changeable
The list is changeable, meaning that we can change, add, and remove items in a list
after it has been created.
Allow Duplicates
Since lists are indexed, lists can have items with the same value
list1 = ['physics', 'chemistry', 1997, 2000, 'chemistry'];
List Length
To determine how many items a list has, use the len() function
list1 = ['physics', 'chemistry', 1997, 2000, 'chemistry'];
print(len(list1))
Negative Indexing
Negative indexing means start from the end
-1 refers to the last item, -2 refers to the second last item etc.
thislist = ["apple", "banana", "cherry"]
print(thislist[-1])
Range of Indexes
A range of indexes specifies where to start and where to end the range.
When specifying a range, the return value will be a new list with the specified items.
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])
The search will start at index 2 (included) and end at index 5 (not included)
By leaving out the start value, the range will start at the first item.
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[:4])
By leaving out the end value, the range will go on to the end of the list.
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:])
thislist[1] = "blackcurrant"
print(thislist)
Insert Items
To insert a new list item, without replacing any of the existing values, we can use the
insert() method.
The insert() method inserts an item at the specified index
thislist = ["apple", "banana", "cherry"]
thislist.insert(2, "watermelon")
print(thislist)
print(thislist)
Insert Items
To insert a list item at a specified index, use the insert() method.
The insert() method inserts an item at the specified index
thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
print(thislist)
Extend List
To append elements from another list to the current list, use the extend() method
thislist = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
thislist.extend(tropical)
print(thislist)
Loop Lists
Loop Through a List
Loop through the list items by using a for loop
thislist = ["apple", "banana", "cherry"]
for x in thislist:
print(x)
List Comprehension
List comprehension offers a shorter syntax when you want to create a new list based on
the values of an existing list.
Example:
Based on a list of fruits, you want a new list, containing only the fruits with the letter
"a" in the name.
Without list comprehension you will have to write a for statement with a conditional
test inside
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []
for x in fruits:
if "a" in x:
newlist.append(x)
print(newlist)
With list comprehension you can do all that with only one line of code
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x for x in fruits if "a" in x]
print(newlist)
Sort Lists
Sort List Alphanumerically
List objects have a sort() method that will sort the list alphanumerically, ascending, by
default
Alphabetical Sort
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort()
print(thislist)
Numerical Sort
thislist = [100, 50, 65, 82, 23]
thislist.sort()
print(thislist)
Sort Descending
To sort descending, use the keyword argument reverse = True
thislist = [100, 50, 65, 82, 23]
thislist.sort(reverse = True)
print(thislist)
Copy Lists
Copy a List
You cannot copy a list simply by typing list2 = list1, because: list2 will only be a
reference to list1, and changes made in list1 will automatically also be made in list2.
There are ways to make a copy, one way is to use the built-in List method copy().
thislist = ["apple", "banana", "cherry"]
mylist = thislist.copy()
print(mylist)
Join Lists
There are several ways to join, or concatenate, two or more lists in Python.
One of the easiest ways are by using the + operator.
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
list3 = list1 + list2
print(list3)
Another way to join two lists are by appending all the items from list2 into list1, one
by one
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
for x in list2:
list1.append(x)
print(list1)
Use the extend() method, which purpose is to add elements from one list to another list.
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
list1.extend(list2)
print(list1)
TUPLES
A tuple is a collection of objects which ordered and immutable. Tuples are sequences,
just like lists. The differences between tuples and lists are, the tuples cannot be changed unlike
lists and tuples use parentheses, whereas lists use square brackets.
thistuple = ("apple", "banana", "cherry")
print(thistuple)
Tuple Items
Tuple items are ordered, unchangeable, and allow duplicate values.
Tuple items are indexed, the first item has index [0], the second item has index [1] etc.
Ordered
When we say that tuples are ordered, it means that the items have a defined order, and
that order will not change.
Unchangeable
Tuples are unchangeable, meaning that we cannot change, add or remove items after
the tuple has been created.
Allow Duplicates
Since tuple are indexed, tuples can have items with the same value
thistuple = ("apple", "cherry", "apple", "cherry")
print(thistuple)
Tuple Length
To determine how many items a tuple has, use the len() function
thistuple = ("apple", "banana", "cherry")
print(len(thistuple))
#NOT a tuple
thistuple = ("apple")
print(type(thistuple))
Negative Indexing
Negative indexing means start from the end. -1 refers to the last item, -2 refers to the
second last item etc.
thistuple = ("apple", "banana", "cherry")
print(thistuple[-1])
Range of Indexes
Specify a range of indexes by specifying where to start and where to end the range.
When specifying a range, the return value will be a new tuple with the specified items.
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[2:5])
By leaving out the start value, the range will start at the first item.
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[:4])
By leaving out the end value, the range will go on to the end of the list.
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[2:])
Add Items
Once a tuple is created, cannot add items to it.
thistuple = ("apple", "banana", "cherry")
thistuple.append("orange") # This will raise an error
print(thistuple)
Just like the workaround for changing a tuple, convert it into a list, add your item(s),
and convert it back into a tuple.
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
y.append("orange")
thistuple = tuple(y)
Remove Items
Tuples are unchangeable, so cannot remove items from it, but can able to use the same
workaround as used for changing and adding tuple items
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
y.remove("apple")
thistuple = tuple(y)
delete tuple
thistuple = ("apple", "banana", "cherry")
del thistuple
print(thistuple) #this will raise an error because the tuple no longer exists
Using Asterisk*
If the number of variables is less than the number of values, add an * to the variable
name and the values will be assigned to the variable as a list to collect the remaining.
fruits = ("apple", "banana", "cherry", "strawberry", "raspberry")
(green, yellow, *red) = fruits
print(green)
print(yellow)
print(red)
If the asterix is added to another variable name than the last, Python will assign values
to the variable until the number of values left matches the number of variables left
fruits = ("apple", "mango", "papaya", "pineapple", "strawberry", "cherry")
(green, *tropic, red) = fruits
print(green)
print(tropic)
print(red)
for x in thistuple:
print(x)
Multiply Tuples
Multiply the content of a tuple a given number of times, can use the * operator.
fruits = ("apple", "banana", "cherry")
mytuple = fruits * 2
print(mytuple)
Sets
Sets are used to store multiple items in a single variable.
Set is one of 4 built-in data types in Python used to store collections of data.
A set is a collection which is both unordered and unindexed. Sets are written with curly
brackets.
thisset = {"apple", "banana", "cherry"}
print(thisset)
Set Items
Set items are unordered, unchangeable, and do not allow duplicate values.
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.
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.
Length of a Set
To determine how many items a set has, use the len() method.
thisset = {"apple", "banana", "cherry"}
print(len(thisset))
Add Sets
To add items from another set into the current set, use the update() method.
pop()
Use the pop() method to remove an item, but this method will remove the last item.
Remember that sets are unordered, so will not know what item that gets removed.
The return value of the pop() method is the removed item.
thisset = {"apple", "banana", "cherry"}
x = thisset.pop()
print(x)
print(thisset)
clear()
The clear() method empties the set
thisset = {"apple", "banana", "cherry"}
thisset.clear()
print(thisset)
del
The del keyword will delete the set completely
thisset = {"apple", "banana", "cherry"}
del thisset
print(thisset)
The intersection() method will return a new set, that only contains the items that are
present in both sets.
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.intersection(y)
print(z)
The symmetric_difference() method will return a new set, that contains only the
elements that are NOT present in both sets.
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.symmetric_difference(y)
print(z)
Dictionaries
Dictionaries are used to store data values in key:value pairs.
A dictionary is a collection which is ordered*, changeable and does not allow
duplicates.
Dictionaries are ordered from python 3.7 version, in earlier versions Dictionaries are
unordered
Dictionaries are written with curly brackets, and have keys and values.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
Dictionary Items
Dictionary items are ordered, changeable, and does not allow duplicates.
Dictionary items are presented in key:value pairs, and can be referred to by using the
key name.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])
Ordered or Unordered?
The dictionaries are ordered, it means that the items have a defined order, and that order
will not change.
Unordered means that the items does not have a defined order, you cannot refer to an
item by using an index.
Changeable
Dictionaries are changeable, meaning that we can change, add or remove items after
the dictionary has been created.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict)
Duplicate values will overwrite existing values
Dictionary Length
To determine how many items a dictionary has, use the len() function
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
}
print(len(thisdict))
}
x = thisdict["model"]
There is also a method called get() that will give you the same result
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict.get("model")
print(x)
Get Keys
The keys() method will return a list of all the keys in the dictionary.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict.keys()
print(x)
The list of the keys is a view of the dictionary, meaning that any changes done to the
dictionary will be reflected in the keys list.
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.keys()
print(x) #before the change
car["color"] = "white"
print(x) #after the change
Get Values
The values() method will return a list of all the values in the dictionary.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict.values()
print(x)
The list of the values is a view of the dictionary, meaning that any changes done to the
dictionary will be reflected in the values list.
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.values()
print(x) #before the change
car["year"] = 2020
print(x) #after the change
Add a new item to the original dictionary, and see that the values list gets updated as
well.
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.values()
print(x) #before the change
car["color"] = "red"
print(x) #after the change
Get Items
The items() method will return each item in a dictionary, as tuples in a list.
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.items()
print(x)
The returned list is a view of the items of the dictionary, meaning that any changes done
to the dictionary will be reflected in the items list.
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.items()
print(x) #before the change
car["year"] = 2020
print(x) #after the change
Add a new item to the original dictionary, and see that the items list gets updated as
well
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.items()
print(x) #before the change
car["color"] = "red"
print(x) #after the change
Update Dictionary
The update() method will update the dictionary with the items from the given argument.
The argument must be a dictionary, or an iterable object with key:value pairs.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"year": 2020})
Adding Items
Adding an item to the dictionary is done by using a new index key and assigning a value
to it
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)
Update Dictionary
The update() method will update the dictionary with the items from a given argument.
If the item does not exist, the item will be added.
The argument must be a dictionary, or an iterable object with key:value pairs.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"color": "red"})
pop()
The pop() method removes the item with the specified key name.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)
popitem()
The popitem() method removes the last inserted item. (in versions before 3.7, a random
item is removed instead)
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.popitem()
print(thisdict)
del
The del keyword removes the item with the specified key name.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)
clear()
The clear() method empties the dictionary
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.clear()
print(thisdict)
Loop Dictionaries
Loop through a dictionary by using a for loop.
When looping through a dictionary, the return value are the keys of the dictionary, but
there are methods to return the values as well.
Print all key names in the dictionary, one by one
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in thisdict:
print(x)
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in thisdict.values():
print(x)
Use the keys() method to return the keys of a dictionary
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in thisdict.keys():
print(x)
Loop through both keys and values, by using the items() method
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x,y in thisdict.items():
print(x, y)
Copy Dictionary
A dictionary simply cannot copy by typing dict2 = dict1, because: dict2 will only be a
reference to dict1, and changes made in dict1 will automatically also be made in. dict2.
There are ways to make a copy, one way is to use the built-in Dictionary method copy().
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = thisdict.copy()
print(mydict)
Nested Dictionaries
A dictionary can contain dictionaries, this is called nested dictionaries.
myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004
},
"child2" : {
"name" : "Tobias",
"year" : 2007
},
"child3" : {
"name" : "Linus",
"year" : 2011
}
}
Or, create three dictionaries, then create one dictionary that will contain the other three
dictionaries
child1 = {
"name" : "Emil",
"year" : 2004
}
child2 = {
"name" : "Tobias",
"year" : 2007
}
child3 = {
"name" : "Linus",
"year" : 2011
}
myfamily = {
"child1" : child1,
"child2" : child2,
"child3" : child3
}