Python Unit -2 (2)
Python Unit -2 (2)
UNIT –II
STRING
A string consists of a sequence of characters, which includes letters, numbers, punctuation marks
and spaces. To represent strings, you can use a single quote, double quotes or triple quotes.
create_string = str()
type(create_string) // returns type as <class 'str'>
. Page 1
Python Programming
OUTPUT
'facebook'
Ex: rs = "wow" * 5
print(rs)
OUTPUT
‘wowwowwowwowwow’
The presence of a string in another string can check by using in and not in membership operators.
It returns either a Boolean True or False. The in operator evaluates to True if the string value in
the left operand appears in the sequence of characters of string value in right operand. The not in
operator evaluates to True if the string value in the left operand does not appear in the sequence
of characters of string value in right operand.
Ex: fg = "apple is a fruit"
fsg = "apple"
print(fsg in fg)
afs = "orange"
print(afs not in fg)
OUTPUT
True
True
. Page 2
Python Programming
STRING COMPARISON
The <, <=, >=, ==, != are used to compare two strings resulting in either Boolean True or False
value. Python compares strings using ASCII value of the characters. For example,
Ex: "january" == "jane" // False
"january" != "jane" //True
"january" < "jane" // False
"january" > "jane" //True
"january" <= "jane" // False
"january" >= "jane" //True
"filled" > "" //True
String equality is compared using = = (double equal sign). String inequality is compared using !
= sign. Strings are compared based on the ASCII value.
OUTPUT
6
max() : The max() function returns a character having highest ASCII value.
Ex: m = max("axel")
print(m)
OUTPUT
'x'
min(): The min() function returns character having lowest ASCII value.
Ex: n = min("brad")
print(n)
OUTPUT
'a'
. Page 3
Python Programming
By referring to the index numbers in square bracket, you can access individual characters in a
string.
The index number starts with zero corresponding to the first character in the string.
The index number increases by one as we move to access the next letter to the right of the
current letter.
The whitespace character between be and yourself has its own index number, i.e., 2.
The last character in the string is referenced by an index value which is the (size of the string
– 1) or (len(string) – 1).
If you try to specify an index number more than the number of characters in the string, then it
results in IndexError: string index out of range error.
. Page 4
Python Programming
Access individual characters in a string using negative indexing. By count backward from the
end of the string starting from an index number of −1. The negative index break down for the
string “be yourself” assigned to word_phrase string variable is shown below.
. Page 5
Python Programming
The negative index can be used to access individual characters in a string. Negative indexing
starts with −1 index corresponding to the last character in the string and then the index decreases
by one as we move to the left.
Output:
ny
ny e
Write Python Code to Determine Whether the Given String is a Palindrome or Not Using
Slicing
def main():
user_string = input("Enter string: ")
if user_string == user_string[::-1]:
print(f"User entered string is palindrome")
else:
print(f"User entered string is not a palindrome")
if __name__ == "__main__":
main()
. Page 6
Python Programming
OUTPUT
Enter string: madam
User entered string is palindrome
If the sequence is a string, then join() function inserts string_name between each character of
the string sequence and returns the concatenated string.
Ex: numbers = "123"
characters = "amy"
password = numbers.join(characters)
print(password)
OUTPUT:
'a123m123y'
If the sequence is a list, then join() function inserts string_name between each item of list
sequence and returns the concatenated string. All the items in the list should be of string type.
Ex: date_of_birth = ["17", "09", "1950"]
a = ":".join(date_of_birth)
print(a)
OUTPUT:
17:09:1950
. Page 7
Python Programming
OUTPUT:
'instagram is an photo sharing application'
OUTPUT:
['edison', ' tesla', ' marconi', ' newton']
OUTPUT:
['rolex', 'hublot', 'cartier', 'omega']
. Page 8
Python Programming
STRING TRAVERSING
String is a sequence of characters, each of these characters can be traversed using the for loop.
OUTPUT
In the string 'google'
Character 'g' has an index value of 0
Character 'o' has an index value of 1
Character 'o' has an index value of 2
Character 'g' has an index value of 3
Character 'l' has an index value of 4
Character 'e' has an index value of 5
Write Python Program to Calculate the Length of a String without Using Built-In len()
Function
def main():
user_string = input("Enter a string: ")
count_character = 0
for each_character in user_string:
count_character += 1
print(f"The length of user entered string is {count_character} ")
if __name__ == "__main__":
main()
. Page 9
Python Programming
OUTPUT
Enter a string: To answer before listening that is folly and shame
The length of user entered string is 50
FORMAT SPECIFIERS
Format specifiers may also contain evaluated expressions. The syntax for f-string formatting
operation is,
f'string_statements {variable_name [: {width}.{precision}]}’
The f character should be prefixed during f-string formatting. The string_statement is a string
consisting of a sequence of characters. Within curly braces, specify the variable_name whose
value will be displayed. Specifying width and precision values are optional. By default, strings
are left-justified and numbers are right-justified. Precision refers to the total number of digits that
will be displayed in a number.
Ex: width = 10
precision = 5
value = 12.34567
print(f'result: {value:{width}.{precision}}')
print(f'result: {value:{width}}')
print(f'result: {value:.{precision}}')
OUTPUT:
result: 12.346
result: 12.34567
result: 12.346
ESCAPE SEQUENCES
Escape Sequences are a combination of a backslash (\) followed by either a letter or a
combination of letters and digits. Escape sequences are also called as control sequences. The
backslash (\) character is used to escape the meaning of characters that follow it by substituting
their special meaning with an alternate interpretation. So, all escape sequences consist of two or
more characters.
. Page 10
Python Programming
OUTPUT
You can break … single line to … multiple lines
print backslash \ inside a string
print single quote ' within a string
print double quote " within a string
First line
Second line
tab spacing
. Page 11
Python Programming
RAW STRINGS
A raw string is created by prefixing the character r to the string. In Python, a raw string ignores
all types of formatting within a string including the escape characters.
Ex: print(r"The Internet, \"is a vast network that connects computers all over the world\"")
OUTPUT:
The Internet, \"is a vast network that connects computers all over the world\"
UNICODES
The Unicode Standard provides a unique number for every character Unicode can be
implemented by different character encodings. The Unicode Standard defines Unicode
Transformation Formats like UTF-8, UTF-16, and UTF-32, and several other encodings are in
use.
To create a Unicode string, use the 'u' prefix on the string literal.
Ex: unicode_string = u'A unicode \u018e string \xf1'
print(unicode_string)
OUTPUT:
A unicode string ñ'
STRING METHODS
capitalize(): This method returns a copy of the string with its first character capitalized and
the rest lowercased.
Syntax: string_name.capitalize()
center():It align sting in center by taking width parameter. Padding is specified by parameter
fillchar. Default filler is a space
Syntax: string_name.center(width[,fillchar])
. Page 12
Python Programming
startswith():returns Boolean True if the string starts with the prefix, otherwise return False.
With optional start, test string_name beginning at that position. With optional end, stop
comparing string_name at that position.
Syntax: string_name.startswith(prefix[,start[, end]]) Output: False
Ex: warriors = "ancient gladiators were vegetarians"
print(warriors.startswith("A"))
endswith():returns True if the string_name ends with the specified suffix substring,
otherwise returns False.
Syntax: string_name.endswith(suffix[,start[, end]]) Output:True
Ex: warriors = "ancient gladiators were vegetarians"
print(warriors.endswith("s"))
find():Checks if substring appears in string_name and return position of the first character of
the first instance of string substring in string_name, otherwise return –1 if substring not
found
in string_name.
Syntax: string_name. find(substring[,start[, end]]) Output: 9
Ex: str=”I like python”
print(str.find(“thon”)
isalnum(): returns Boolean True if all characters in the string are alphanumeric and there is
at
least one character, else it returns Boolean False.
Syntax: string_name.isalnum()
. Page 13
Python Programming
isdecimal():returns Boolean True if all characters in the string are decimal characters and
there is at least one character, else it returns Boolean False.
Syntax: string_name.isdecimal()
Ex: str="345” Output: True
print(str.isdecimal())
isdigit(): returns Boolean True if all characters in the string are digits and there is at least one
character, else it returns Boolean False.
Syntax: string_name.isdigit()
Ex: str=" \u00b2'” Output: True
print(str.isdigit())
isidentifier(): returns Boolean True if the string is a valid identifier, else it returns Boolean
False.
Syntax: string_name.isidentifier() Output: True
Ex: str="char”
print(str.isidentifier())
islower(): returns Boolean True if all characters in the string are lowercase, else it returns
Boolean False.
Syntax: string_name.islower() Output: True
Ex: str="shruthi”
print(str.islower())
isspace(): returns Boolean True if there are only whitespace characters in the string and there
is at least one character, else it returns Boolean False.
Syntax: string_name.isspace()
. Page 14
Python Programming
istitle():returns Boolean True if the string is a title cased string and there is at least one
character, else it returns Boolean False.
Syntax: string_name.istitle()
Ex: X=" Program'” Output: True
print(X.istitle())
isupper(): returns Boolean True if all cased characters in the string are uppercase and there is
at least one cased character, else it returns Boolean False.
Syntax: string_name.isupper()
Ex: X=" Program'” Output: False
print(X.isupper())
ljust() : it returns the string left justified. Total length of string is defined in first parameter of
method width. Padding is done as defined in second parameter fillchar. Default is space.
Syntax: string_name.ljust(width[,fillchar])
Ex: quote = "Python" Output: Python$$$$
print(quote.ljust(10,"$"))
. Page 15
Python Programming
rjust(): it returns the string right justified. The total length of string is defined in the first
parameter of the method, width. Padding is done as defined in second parameter fillchar.
Default is space
Syntax: string_name.rjust(width[,fillchar])
Ex: quote = "Python" Output: &&&&&&&&&Python
print(quote.ljust(15,"&"))
title(): returns “titlecased” versions of string, that is, all words begin with uppercase
characters and the rest are lowercase.
Syntax: string_name.title()
Ex: name= "python" Output: Python
print(name.title())
swapcase():The method swapcase() returns a copy of the string with uppercase characters
converted to lowercase and viceversa.
Syntax: string_name.swapcase()
Ex: name= "python" Output:PYTHON
print(name.swapcase())
strip(): returns a copy of the string_name in which specified chars have been stripped from
both side of the string. If char is not specified then space is taken as default.
Syntax: string_name.strip([chars])
Ex: quote = " Never Stop Dreaming " Output: Never Stop Dreaming
print(quote.strip())
. Page 16
Python Programming
replace(): replaces all occurrences of old in string_name with new. If the optional argument
max is given, then only the first max occurrences are replaced.
Syntax: string_name. replace(old, new[, max])
LISTS
Lists are used to store multiple items in a single variable.
CREATING LISTS
Lists are constructed using square brackets [ ] where in it include a list of items separated by
commas.
Syntax: list_name= [item1,item2,item3 ...... itemn]
The presence of an item in the list can check using in and not in membership operators. It returns
a Boolean True or False.
If an item is present in the list then using in operator results in True else returns False. If the item
is not present in the list using not in operator results in True else False.
Where the sequence can be a string, tuple or list itself. If the optional sequence is not specified
then an empty list is created.
Ex: quote = "How you doing?"
string_to_list = list(quote)
print(string_to_list)
friends = ["j", "o", "e", "y"]
string = friends + list(quote)
print(string)
OUTPUT
['H', 'o', 'w', ' ', 'y', 'o', 'u', ' ', 'd', 'o', 'i', 'n', 'g', '?']
['j', 'o', 'e', 'y', 'H', 'o', 'w', ' ', 'y', 'o', 'u', ' ', 'd', 'o', 'i', 'n', 'g', '?']
. Page 18
Python Programming
Index Value 0 1 2 3 4 5 6
OUTPUT
4
6
9
IndexError: list index out of range
Index Value -3 -2 -1
. Page 19
Python Programming
SLICING OF LISTS
Slicing of lists is allowed in Python wherein a part of the list can be extracted by specifying
index range along with the colon (:) operator which itself is a list.
Where both start and stop are integer values (positive or negative values). List slicing returns a
part of the list from the start index value to stop index value which includes the start index value
but excludes the stop index value. Step specifies the increment value to slice by and it is
optional.
OUTPUT
['pineapple', 'blueberries']
['grapefruit', 'pineapple', 'blueberries']
['blueberries', 'mango', 'banana']
['pineapple', 'mango']
. Page 20
Python Programming
sum():it takes parameter as list name and returns the sum of numbers in the list.
Syntax: sum(list_name)
Ex: num= [3, 5, 3.5, 6.7, 4]
print(sum(num)) Output: 22.2
any() : it takes parameter as list name and returns True if any of the Boolean values in the list
is True.
Syntax: any (list_name)
Ex: num=[1, 1, 0, 0, 1, 0] Output:True
print(any(num))
all(): it takes parameter as list name and returns True if all the Boolean values in the list are
True, else returns False.
Syntax: all (list_name)
Ex: num=[ 1, 1, 1, 1] Output:True
print(all(num))
sorted():it takes parameter as list name and returns a modified copy of the list while leaving
the original list untouched.
Ex: lakes = ['superior', 'erie', 'huron', 'ontario', 'powell']
lakes_new = sorted(lakes)
print(lakes_new)
. Page 21
Python Programming
Output:
['erie', 'huron', 'ontario', 'powell', 'superior']
LIST METHODS
The list size changes dynamically whenever you add or remove the items. All the methods
associated with the list can be obtained by passing the list function to dir().
Ex: print(dir(list))
append(): It adds a single item to the end of the list. This method does not return new list
and it just modifies the original.
Syntax:list.append(item)
Ex: cities = ["dehi", "washington", "london", "paris"]
cities.append(“newyork”)
print(cities)
Output:
['dehi', 'washington', 'london', 'paris', 'newyork']
count(): counts the number of times the item has occurred in the list and returns it.
Syntax: list.count(item)
Ex: cities = ["oslo", "delhi", "washington", "london", "seattle", "paris", "washington"]
print(cities.count("washington"))
Output:
2
insert(): inserts the item at the given index, shifting items to the right.
Syntax: list.insert(index, item)
Ex: cities = ["delhi", "washington", "seattle", "paris"]
print(cities.insert(1,"landon"))
Output:
["delhi", "landon", "washington", "seattle", "paris"]
. Page 22
Python Programming
Output:
["delhi", "washington", "seattle", "paris", brussels", "copenhagen"]
index(): It searches for the given item from the start of the list and returns its index. If the
value appears more than once, the index of the first one it returns. If the item is not present in
the list then ValueError is thrown by this method.
Syntax: list.index(item)
Ex: cities = ["oslo", "delhi", "washington", "london", "seattle", "paris", "washington"]
print(cities.index("washington"))
Output:
2
remove(): It searches for the first instance of the given item in the list and removes it. If the
item is not present in the list then ValueError is thrown by this method.
Syntax: list. remove (item)
Ex: cities = ["delhi", "washington", "seattle", "paris"]
cities.remove(“seattle”))
print(cities)
Output: ["delhi", "washington", "paris"]
sort():It sorts the items in ascending order in the list. This method modifies the original list
and it does not return a new list.
Syntax: list.sort()
Ex: cities = ["delhi", "washington", "seattle", "paris"]
cities.sort()
print(cities)
. Page 23
Python Programming
reverse(): It reverses the items in the list. This method modifies the original list and it does
not return a new list.
Syntax: list.reverse()
Ex: cities = ["delhi", "washington", "seattle", "paris"]
cities.reverse()
print(cities)
pop():It removes and returns the item at the given index.This method returns the rightmost
item if the index is omitted.
Syntax: list.pop([index])
Ex: cities = ["delhi", "washington", "seattle", "paris"]
cities.pop()
print(cities)
cities.pop(0)
print(cities)
Output:
["delhi", "washington", "seattle"]
["washington", "seattle”]
Output:
['Asia', 'Europe', 'Africa']
. Page 24
Python Programming
Output
Enter list items separated by a space Asia Europe Africa
List items are ['Asia', 'Europe', 'Africa']
TRAVERSING OF LISTS
Using a for loop traversing of lists can iterate through each item in a list.
Output
I like to eat waffles
I like to eat sandwich
I like to eat burger
. Page 25
Python Programming
. Page 26
Python Programming
print("1.push()","2.pop()","3.display()")
choice=int(input("enter your choice="))
if choice==1:
push()
elif choice==2:
pop()
elif choice==3:
display()
else:
print("invalid choice")
break
. Page 27
Python Programming
OUTPUT
Queue items are deque(['Eric', 'John', 'Michael'])
Adding few items to Queue
Queue items are deque(['Eric', 'John', 'Michael', 'Terry', 'Graham'])
Removed item from Queue is Eric
Removed item from Queue is John
Queue items are deque(['Michael', 'Terry', 'Graham'])
NESTED LISTS
A list inside another list is called a nested list and the behavior of nested lists can get in Python
by storing lists within the elements of another list. We can traverse through the items of nested
lists using the for loop.
Syntax: Nested_list_name =[[ item1,item2,item3],
[item4, item5, item6],
[item7, item8, item9]]
Access an item inside a list that is itself inside another list by chaining two sets of square
brackets together. For example, in the above list variable asia have three lists which represent a 3
× 3 matrix. To display the items of the first list then specify the list variable followed by the
index of the list within the brackets, like asia[0]
Ex: print(asia[0]) //prints ["India", "Japan", "Korea"]
To access "Japan" item inside the list then need to specify the index of the list within the list and
followed by the index of the item in the list like asia[0][1]
Ex: print(asia[0][1]) //prints “Japan”
Modify the contents of the list within the list. For example, to replace "Thailand" with
"Philippines" use the code in asia[1][2] = "Philippines" then it results in
. Page 28
Python Programming
OUTPUT:
Transposed Matrix is
[10, 30, 50]
[20, 40, 60]
DICTIONARIES
A dictionary is a collection of an unordered set of key:value pairs, with the requirement that the
keys are unique within a dictionary.
CREATING DICTIONARY
Dictionaries are constructed using curly braces { }, wherein include a list of key : value pairs
separated by commas. Also, there is a colon (:) separating each of these key and value pairs,
where the words to the left of the colon operator are the keys and the words to the right of the
. Page 29
Python Programming
colon operator are the values. Dictionaries are indexed by a range of numbers, dictionaries are
indexed by keys. Here a key along with its associated value is called a key:value pair. Dictionary
keys are case sensitive.
Syntax:dictionary_name={key_1:value_1,key_2:value_2,key_3:value_3,
………,key_n:value_n}
Ex: fish = {"g": "goldfish", "s":"shark", "n": "needlefish", "m":"mackerel"}
In dictionaries, the keys and their associated values can be of different types.
Ex: mixed_dict = {"portable":"laptop", 9:11, 7:"julius"}
Determine the type of mixed_dict by passing the variable name as an argument to type()
function.
Ex: type(mixed_dict) // The dictionary type is called as dict.
An empty dictionary can be created by specifying a pair of curly braces and without any
key:value pairs.
Syntax: dictionary_name = { }
Ex: empty_dictionary = {}
In dictionaries, the order of key:value pairs does not matter. For example,
Ex: pizza = {"pepperoni":3, "calzone":5, "margherita":4}
fav_pizza = {"margherita":4, "pepperoni":3, "calzone":5}
pizza = = fav_pizza // True
. Page 30
Python Programming
OUTPUT
{'g': 'goldfish', 's': 'starfish', 'n': 'needlefish', 'm': 'mackerel'}
{'g': 'goldfish', 's': 'starfish', 'n': 'needlefish', 'm': 'mackerel', 'E': 'Eel'}
Keyword arguments of the form kwarg = value are converted to key:value pairs for numbers
dictionary
You can specify an iterable containing exactly two objects as tuple, the key and value in the
dict() function.
Output:
The dict() function builds dictionaries directly from sequences of key, value tuple pairs
. Page 31
Python Programming
all(): returns Boolean True value if all the keys in the dictionary are True else returns False.
Ex: func = {0:True, 2:False}
print all(func) // Output: False
any(): returns Boolean True value if any of the key in the dictionary is True else returns
False.
Ex: func = {1:True, 2:False}
print all(func) // Output: True
sorted(): The sorted() function by default returns a list of items, which are sorted based on
dictionary keys.
Ex: color={"B":"Blue", "W”:"white" , "R":"Red"}
print(sorted(color)) // Output: {'B', 'R', 'W'}
DICTIONARY METHODS
Dictionary allows to store data in key:value format without depending on indexing. A list of all
the methods associated with dict() can obtained by passing the dict function to dir().
Syntax: dir(dict)
. Page 32
Python Programming
fromkeys():creates a new dictionary from the given sequence of elements with a value
provided by the user.
Syntax: dictionary_name.fromkeys(seq [, value])
Ex: movies = {"avatar":2009, "titanic":1997, "starwars":2015, "harrypotter":2011}
X=movies.fromkeys(movies,”2000”)
print(X)
Output:
{'avatar': 2000, 'titanic': 2000, 'starwars': 2000, 'harrypotter': 2000}
get() : method returns the value associated with the specified key in the dictionary. If the key
is not present then it returns the default value. If default is not given, it defaults to None, so
that this method never raises a KeyError.
Syntax: dictionary_name. get(key[, default])
Ex: movies = {"avatar":2009, "titanic":1997, "starwars":2015, "harrypotter":2011}
print(movies.get(“titanic”)) // Output: 1997
items() : returns a new view of dictionary’s key and value pairs as tuples.
Syntax: dictionary_name.items()
Ex: movies = {"avatar":2009, "titanic":1997, "starwars":2015, "harrypotter":2011}
print(movies.items())
keys() : method returns a new view consisting of all the keys in the dictionary.
Syntax: dictionary_name.keys()
Ex: movies = {"avatar":2009, "titanic":1997, "starwars":2015, "harrypotter":2011}
print(movies.keys())
pop() : removes the key from the dictionary and returns its value. If the key is not present,
then it returns the default value. If default is not given and the key is not in the dictionary,
then it results in KeyError.
. Page 33
Python Programming
popitem() : removes and returns an arbitrary (key, value) tuple pair from the dictionary. If
the dictionary is empty, then calling popitem() results in KeyError.
Syntax: dictionary_name.popitem()
Ex: movies = {"avatar":2009, "titanic":1997, "starwars":2015, "harrypotter":2011}
print(movies.popitem()) Output: "harrypotter":2011
setdefault() : returns a value for the key present in the dictionary. If the key is not present,
then insert the key into the dictionary with a default value and return the default value. If key
is present defaults to None, so that this method never raises a KeyError.
Syntax: dictionary_name setdefault(key[, default])
Ex: movies = {"avatar":2009, "titanic":1997, "starwars":2015, "harrypotter":2011}
movies.setdefault("minions")
print(movies)
Output:
{'avatar': 2009, 'titanic': 1997, 'starwars': 2015, 'harrypotter': 2011, 'minions': None}
update() : updates the dictionary with the key:value pairs from other dictionary object and it
returns None.
Syntax: dictionary_name.update([other])
Ex: movies = {"avatar":2009, "titanic":1997, "starwars":2015, "harrypotter":2011}
movies.update({"avengers":2012})
print(movies)
Output:
{'avatar': 2009, 'titanic': 1997, 'starwars': 2015, 'harrypotter': 2011, 'avengers': 2012}
values() : returns a new view consisting of all the values in the dictionary.
Syntax: dictionary_name.values()
Ex: movies = {"avatar":2009, "titanic":1997, "starwars":2015, "harrypotter":2011}
print(movies.values())
. Page 34
Python Programming
Output:
dict_values([2009, 1997, 2015, 2011])
OUTPUT
{'Asia': 'India', 'Europe': 'Germany', 'Africa': 'Sudan'}
TRAVERSING OF DICTIONARY
A for loop can be used to iterate over keys or values or key:value pairs in dictionaries. If iterate
over a dictionary using a for loop, then, by default, iterate over the keys. If we want to iterate
over the values, use values () method and for iterating over the key:value pairs, specify the
dictionary’s items() method explicitly.
The dict_keys, dict_values, and dict_items data types returned by dictionary methods can be
used in for loops to iterate over the keys or values or key:value pairs.
OUTPUT
List of Countries
India
USA
Russia
Japan
List of Currencies in different Countries
Rupee
Dollar
Ruble
Yen
'India' has a currency of type 'Rupee'
'USA' has a currency of type 'Dollar'
'Russia' has a currency of type 'Ruble'
'Japan' has a currency of type 'Yen'
TUPLES
A tuple is a finite ordered list of values of possibly different types.
CREATING TUPLES
A tuple is a finite ordered list of values of possibly different types which is used to bundle related
values together without having to create a specific type to hold them. Tuples are immutable.
Once a tuple is created, cannot change its values.
A tuple is defined by putting a comma-separated list of values inside parentheses ( ). Each value
inside a tuple is called an item.
Syntax: tuple_name = (item_1, item_2, item_3, ................... , item_n)
Ex: internet = ("cern", "timbernerslee", "www", 1980)
print(internet)
Output:
('cern', 'timbernerslee,' 'www', 1980)
. Page 36
Python Programming
An empty tuple can create without any values. The syntax is,
Syntax : tuple_name = ()
Ex: empty_tuple = ()
print( empty_tuple) Output:( )
Any item of type string, number, object, another variable and even another tuple itself can be
store in tuple. they need not be homogeneous.
Ex: air_force = ("f15", "f22a", "f35a")
fighter_jets = (1988, 2005, 2016, air_force)
print(fighter_jets)
Output:
(1988, 2005, 2016, ('f15', 'f22a', 'f35a'))
The presence of an item in a tuple using in and not in membership operators. It returns a Boolean
True or False.
Ex: tuple_items = (1, 9, 8, 8)
X= 1 in tuple_items // Output: True
print(X)
Y= 25 in tuple_items // Output: False
print(Y)
The in operator returns Boolean True if an item is present in the tuple or else returns False
Boolean value.
. Page 37
Python Programming
Comparison operators like <, <=, >, >=, == and != are used to compare tuples.
Ex: tuple_1 = (9, 8, 7)
tuple_2 = (9, 1, 1)
print(tuple_1 > tuple_2) // Output: True
print(tuple_1 != tuple_2) True
. Page 38
Python Programming
0 1 2 3
Index Value -4 -3 -2 -1
Tuple items can be access using a negative index number, by counting backwards from the end
of the tuple, starting at −1. Negative indexing is useful when large number of items in the tuple
are present.
Ex: places = ("Mysore", “Bangalore", "Mangalore", "Hassan")
print(places[-2]) // Output: Mangalore
print(places[4)) // IndexError: tuple index out of range
SLICING OF TUPLES
Slicing of tuples is allowed in Python wherein a part of the tuple can be extracted by specifying
an index range along with the colon (:) operator, which itself results as tuple type.
Syntax : tuple_name[start:stop[:step]]
Where both start and stop are integer values (positive or negative values). Tuple slicing returns a
part of the tuple from the start index value to stop index value, which includes the start index
value but excludes the stop index value. The step specifies the increment value to slice by and it
is optional.
Ex: colors = ("v", "i", "b", "g", "y", "o", "r")
. Page 39
Python Programming
print (colors[::])
print (colors[1:5:2])
print (colors[::2])
print (colors[::-1])
print (colors[-5:-2])
OUTPUT
('v', 'i', 'b', 'g', 'y', 'o', 'r')
('i', 'b', 'g')
('v', 'i', 'b', 'g', 'y')
('g', 'y', 'o', 'r')
('v', 'i', 'b', 'g', 'y', 'o', 'r')
('v', 'i', 'b', 'g', 'y', 'o', 'r')
('i', 'g')
('v', 'b', 'y', 'r')
('r', 'o', 'y', 'g', 'b', 'i', 'v')
('b', 'g', 'y')
sorted(): This function returns a sorted copy of the tuple as a list while leaving the original
tuple untouched.
Syntax: sum(tuple_name)
. Page 40
Python Programming
TUPLE METHODS
The methods associated with the tuple can be obtained by passing the tuple function to dir().
Syntax: dir(tuple)
count():This method counts the number of times the item has occurred in the tuple and
returns it.
Syntax: tuple_name.count(item)
Ex: channels = ("ngc", "discovery", "animal_planet", "history", "ngc")
print(channels.count("ngc")) // Output: 2
index(): This method searches for the given item from the start of the tuple and returns its
index. If the value appears more than it returns index of the first one. If the item is not
present in the tuple, then ValueError is thrown by this method.
Syntax: tuple_name.index(item)
Ex: channels = ("ngc", "discovery", "animal_planet", "history", "ngc")
print(channels.index("history")) // Output: 3
TRAVERSING OF TUPLES
Traversing of tuples can iterate through each item in tuples using for loop.
. Page 41
Python Programming
OUTPUT
eel is an ocean animal
jelly_fish is an ocean animal
shrimp is an ocean animal
turtles is an ocean animal
blue_whale is an ocean animal
OUTPUT
Enter the total number of items: 3
Enter a number: 4
Enter a number: 6
Enter a number: 1
Items added to tuple are (4, 6, 1)
Enter the total number of items: 3
. Page 42
Python Programming
SETS
Python also includes a data type for sets. A set is an unordered collection with no duplicate
items. Primary uses of sets include membership testing and eliminating duplicate entries. Sets
also support mathematical operations, such as union, intersection, difference, and symmetric
difference.
Curly braces { } or the set() function can be used to create sets with a comma-separated list of
items inside curly brackets { }.
Ex: a = set('abracadabra')
print(a) Output: {'d', 'a', 'b', 'r', 'c'}
The presence of an item in a set can be obtained by using in and not in membership operators.
Ex: basket = {'apple', 'orange', 'pear', 'banana'}
print('orange' in basket) Output: True
print('crabgrass' in basket) False
print('crabgrass' not in basket) True
OPERATIONS ON SET
Ex: A = {'d', 'a', 'b', 'r', 'c'}
B = {'m', 'l', 'c', 'z', 'a'}
. Page 43
Python Programming
print(A - B)
print(A | B)
print(A & B)
print(A ^ B)
OUTPUT
{'d', 'r', 'b'}
{'r', 'b', 'z', 'd', 'l', 'c', 'm', 'a'}
{'c', 'a'}
{'z', 'l', 'd', 'r', 'm', 'b'}
SET METHODS
A list of all the methods associated with the set can be obtained by passing the set function to
dir().
Syntax: dir(set)
. Page 44
Python Programming
difference(): This method returns a new set with items in the set that are not in the others
sets.
Syntax: set_name.difference(*others)
Ex: flowers = {"sunflowers", "roses", "lavender", "tulips"}
american_flowers = {"roses", "tulips", "lilies", "daisies"}
print(flowers.difference(american_flowers)) Output:{'sunflowers', 'lavender'}
intersection():This method returns a new set with items common to the set and all others
sets.
Syntax: set_name.intersection(*others)
Ex: flowers = {"sunflowers", "roses", "lavender", "tulips"}
american_flowers = {"roses", "tulips", "lilies", "daisies"}
print(flowers.intersection(american_flowers)) Output: {'tulips', 'roses'}
isdisjoint():This method returns True if the set has no items in common with other set. Sets
are disjoint if and only if their intersection is the empty set.
Syntax: set_name.isdisjoint(other)
Ex: flowers = {"sunflowers", "roses", "lavender", "tulips"}
american_flowers = {"roses", "tulips", "lilies", "daisies"}
print(flowers.isdisjoint(american_flowers)) Output: False
. Page 45
Python Programming
issubset():This method returns True if every item in the set is in other set.
Syntax: set_name.issubset(other)
Ex: flowers = {"roses","tulips"}
american_flowers = {"roses", "tulips"}
print(flowers.issubset(american_flowers)) Output:True
issuperset():This method returns True if every element in other set is in the set
Syntax: set_name.issuperset(other)
Ex: flowers = {"roses","tulips"}
american_flowers = {"roses", "tulips", "sunflower"}
print(flowers.issuperset(american_flowers)) Output: False
pop():This method removes and returns an arbitrary item from the set. It raises KeyError if
the set is empty.
Syntax: set_name.pop()
Ex: flowers = {"sunflowers", "roses", "lavender", "tulips"}
flowers.pop()
print(flowers) Output: {'lavender', 'tulips', 'roses'}
remove():This method removes an item from the set. It raises KeyError if the item is not
contained in the set.
Synatx: set_name.remove(item)
Ex: flowers = {"sunflowers", "roses", "lavender", "tulips"}
flowers.remove("sunflowers")
print(flowers) Output: {'roses', 'lavender', 'tulips}
symmetric_difference():It returns a new set with items in either the set or other but not both.
Synatx: set_name.symmetric_difference(other)
Ex: flowers = {"sunflowers", "roses", "lavender", "tulips"}
american_flowers = {"roses", "tulips", "lilies", "daisies"}
print(american_flowers.difference(flowers)) Output: {'lilies', 'daisies'}
. Page 46
Python Programming
union():This method returns a new set with items from the set and all others sets.
Synatx: set_name.union(*others)
Ex: flowers = {"sunflowers", "roses", "lavender", "tulips"}
american_flowers = {"roses", "tulips", "lilies", "daisies"}
print(american_flowers.union(flowers))
update(): Update the set by adding items from all others sets.
Synatx: set_name.update(*others)
Ex: flowers = {"sunflowers", "roses", "lavender", "tulips"}
american_flowers = {"roses", "tulips", "lilies", "daisies"}
american_flowers.update(flowers)
print(american_flowers)
TRAVERSING OF SETS
Traversing of Sets iterate through each item in a set using a for loop.
FILES
A file is the common storage unit in a computer, and all programs and data are “written” into a
file and “read” from a file.
. Page 47
Python Programming
FILE TYPES
Python supports two types of files.
1. Text files :
The text files contain data stored as a series of bits (binary values of 1s and 0s), the bits
in text files represent characters
Common extensions for text file formats:
Web standards: html, xml, css, svg, json,...
Source code: c, cpp, h, cs, js, py, java, rb, pl, php, sh,...
Documents: txt, tex, markdown, asciidoc, rtf, ps,...
Configuration: ini, cfg, rc, reg,...
Tabular data: csv, tsv,...
2. Binary files:
The binary files contain data stored as a series of bits (binary values of 1s and 0s), bits in
binary files represent custom data.
Binary files contain a sequence of bytes or ordered groupings of eight bits. Binary file
formats may include multiple types of data in the same file, such as image, video, and
audio data.
Common extensions for binary file formats:
Images: jpg, png, gif, bmp, tiff, psd,...
Videos: mp4, mkv, avi, mov, mpg, vob,...
Audio: mp3, aac, wav, flac, ogg, mka, wma,...
Documents: pdf, doc, xls, ppt, docx, odt,...
Archive: zip, rar, 7z, tar, iso,...
Database: mdb, accde, frm, sqlite,...
Executable: exe, dll, so, class,...
. Page 48
Python Programming
The following fundamental rules to create and process valid names for files and directories in
both Windows and Linux operating systems unless explicitly specified:
Use a period(.) to separate the base file name from the extension in the file name.
In Windows use backslash (\) and in Linux use forward slash (/) to separate the components
of a path.
The backslash (or forward slash) separates one directory name from another directory name
in a path and it also divides the file name from the path leading to it. Backslash ( \) and
forward slash (/) are reserved characters and you cannot use them in the name for the actual
file or directory.
File and Directory names in Windows are not case sensitive while in Linux it is case
sensitive. For example, the directory names ORANGE, Orange, and orange are the same in
Windows but are different in Linux Operating System.
In Windows, drive letters are case-insensitive. For example,"D:\" and "d:\" refer to the
same drive.
The reserved characters that should not be used in naming files and directories are < (less
than), > (greater than),: (colon), " (double quote), / (forward slash), \ (backslash), | (vertical
bar or pipe), ? (question mark) and * (asterisk).
In Windows Operating system reserved words like CON, PRN, AUX, NUL, COM1,
COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9, LPT1, LPT2, LPT3,
LPT4, LPT5, LPT6, LPT7, LPT8, and LPT9 should not be used to name files and
directories.
. Page 49
Python Programming
RELATIVE PATH
A path is said to be a relative path if it contains “double-dots”( . . ) together as one of the
directory components in a path or “single-dot”( . ) as one of the directory components in a path.
These two consecutive periods are used to denote the directory above the current directory,
otherwise known as the “parent directory.” Use a single period as a directory component in a
path to represent the current directory.
Ex: "..\langur.txt" specifies a file named "langur.txt" located in the parent of the current
directory fauna.
".\bison.txt" specifies a file named "bison.txt" located in a current directory named fauna.
"..\..\langur.txt" specifies a file that is two directories above the current directory india.
The following figure shows the structure of sample directories and files
OPERATIONS ON FILE
1. Opening Text Files: A file is opened using open() function, it returns a file object called a
file handler that provides methods for accessing the file.
Synatx: file_handler = open(filename, mode)
The open() function is used with two arguments, where the first argument is a string
containing the file name to be opened, the second argument is mode which describe purpose
of the file to open. It is optional , if it is not mention it will take default value as r.
Ex: file_handler = open("example.txt")
file_handler = open("moon.txt","r")
file_handler = open("C:\langur.txt",""w)
. Page 50
Python Programming
2. Closing Text Files: It is important to close the file once the processing is completed. After
the file handler object is closed, file cannot further read or write from the file. Any attempt to
use the file handler object after being closed will result in an error.the close() function is used
to close the file.
Syntax: file_handler.close()
Ex: file_handler = open("moon.txt","r")
file_handler.close()
If an exception occurs while performing some operation on the file, then the code exits without
closing the file. In order to overcome this problem, you should use a try-except finally block to
handle exceptions. For example,
try:
f = open("file", "w")
try:
f.write('Hello World!')
finally:
f.close()
except IOError:
print('oops!')
. Page 51
Python Programming
Program to Read and Print Each Line in "japan.txt" File Using with Statement.
def read_file():
print("Printing each line in text file")
with open("japan.txt") as file_handler:
for each_line in file_handler:
print(each_line, end ="")
read_file()
. Page 52
Python Programming
OUTPUT
File Name is computer.txt
File State is False
File Opening Mode is w
. Page 53
Python Programming
3. readlines():This method is used to read all the lines of a file as list items.
Syntax: file_handler.readlines()
Ex: f = open("example.txt", "r")
f.readlines()
write():This method will write the contents of the string to the file, returning the number of characters
written. If you want to start a new line, must include the new line character
Synatx: file_handler.write(string)
Ex: file_handler = open("moon.txt","w")
file_handler.write("Moon is a natural satellite")
tell(): This method returns an integer giving the file handler’s current position within the file,
measured in bytes from the beginning of the file.
Syntax: file_handler.tell()
Ex: file_handler = open("moon.txt","w")
file_handler.tell()
. Page 54
Python Programming
seek():This method is used to change the file handler’s position. The position is computed from
adding offset to a reference point.
Synatx: file_handler. seek(offset, from_what)
The reference point is selected by the from_what argument. A from_what value of 0 measures from
the beginning of the file, 1 uses the current file position, and 2 uses the end of the file as the reference
point. If the from_what argument is omitted, then a default value of 0 is used, indicating that the
beginning of the file itself is the reference point.
Ex: f = open('workfile', 'w')
f.write('0123456789abcdef')
f.seek(2)
f.seek(2, 1)
FORMAT OPERATOR
The format operator, % allows us to construct strings, replacing parts of the strings with the data stored in
variables.
Ex: print('In %d years I have spotted %g %s.' % (3, 0.1, 'camels'))
The following example uses "%d" to format an integer, "%g" to format a floating-point number,
and "%s" to format a string:
Output:
In 3 years I have spotted 0.1 camels.
Ex: a = "anu"
b ="sonu"
print(“%s and %s are good friend” %(a,b))
Output:
anu and sonu are good friend
. Page 55