Python Books
Python Books
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
❖ What is Python?
Python is a popular programming language. It was created by Guido van Rossum, and
released in 1991.
It is used for:
❖ Why Python?
Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
Python has a simple syntax similar to the English language.
Python has syntax that allows developers to write programs with fewer lines than
some other programming languages.
Python runs on an interpreter system, meaning that code can be executed as soon as it
is written. This means that prototyping can be very quick.
Python can be treated in a procedural way, an object-oriented way or a functional way.
If you know Python nicely, then you have a great career ahead. Here are just a few of the
career options where Python is a key skill:
Game developer
Web designer
Python developer
Full-stack developer
Machine learning engineer
Data scientist
Data analyst
Data engineer
DevOps engineer
Software engineer
Many more other roles
2
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
Python uses new lines to complete a command, as opposed to other programming
languages which often use semicolons or parentheses.
Python relies on indentation, using whitespace, to define scope; such as the scope of
loops, functions and classes. Other programming languages often use curly-brackets for
this purpose.
❖ Python Indentation
Where in other programming languages the indentation in code is for readability only, the
indentation in Python is very important.
Example:-
if 5 > 2:
print("Five is greater than two!")
❖ Python Comments
Example:-
#This is a comment
print("Hello, World!")
Comments can be placed at the end of a line, and Python will ignore the rest of the line:
Example:-
3
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
Python will ignore string literals that are not assigned to a variable, you can add a multiline
string (triple quotes) in your code, and place your comment inside it:
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
As long as the string is not assigned to a variable, Python will read the code, but then ignore
it, and you have made a multiline comment.
❖ Python Variables
Creating Variables
Example:-
x=5
y = "John"
print(x)
print(y)
Casting
If you want to specify the data type of a variable, this can be done with casting.
You can get the data type of a variable with the type() function.
x=5
y = "John"
print(type(x))
print(type(y))
4
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
x = "John"
# is the same as
x = 'John'
Variable Names
A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume). Rules for Python variables:
Example:-
2myvar = "John"
my-var = "John"
my var = "John"
Variables can store data of different types, and different types can do different things.
Python has the following data types built-in by default, in these categories:
5
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
Binary Types: bytes, bytearray, memoryview
There may be times when you want to specify a type on to a variable. This can be done with
casting. Python is an object-orientated language, and as such it uses classes to define data
types, including its primitive types.
int() - constructs an integer number from an integer literal, a float literal (by removing
all decimals), or a string literal (providing the string represents a whole number)
float() - constructs a float number from an integer literal, a float literal or a string literal
(providing the string represents a float or an integer)
str() - constructs a string from a wide variety of data types, including strings, integer
literals and float literals
❖ Multiline Strings
You can assign a multiline string to a variable by using three quotes:
Example:-
print(a)
Or three single quotes:
a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
print(a)
Note: in the result, the line breaks are inserted at the same position as in the code.
6
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
Like many other popular programming languages, strings in Python are arrays of bytes
representing unicode characters.
However, Python does not have a character data type, a single character is simply a string
with a length of 1.
Example:-
Get the character at position 1 (remember that the first character has the position 0):
a = "Hello, World!"
print(a[1])
output:-
e
Since strings are arrays, we can loop through the characters in a string, with a for loop.
for x in "banana":
print(x)
output :-
b
a
n
a
n
a
❖ String Length
Example:-
a = "Hello, World!"
print(len(a))
❖ Check String
To check if a certain phrase or character is present in a string, we can use the keyword in.
7
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
true
Example:-
Example:-
❖ Slicing
Specify the start index and the end index, separated by a colon, to return a part of the string.
Example:-
b = "Hello, World!"
print(b[2:5])
By leaving out the start index, the range will start at the first character:
Example:-
b = "Hello, World!"
print(b[:5])
By leaving out the end index, the range will go to the end:
b = "Hello, World!"
print(b[2:])
❖ Negative Indexing
8
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
Use negative indexes to start the slice from the end of the string:
Example:-
Example :-
a = "Hello, World!"
print(a.upper())
a = "Hello, World!"
print(a.lower())
The strip() method removes any whitespace from the beginning or the end:
a = "Hello"
b = "World"
c=a+b
print(c)
a = "Hello"
b = "World"
c=a+""+b
print(c)
As we learned in the Python Variables chapter, we cannot combine strings and numbers like
this:
age = 36
txt = "My name is John, I am " + age
print(txt)
9
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
But we can combine strings and numbers by using the format() method!
The format() method takes the passed arguments, formats them, and places them in the
string where the placeholders {} are:
age = 36
txt = "My name is John, 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))
You can 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))
The escape character allows you to use double quotes when you normally would not be
allowed:
❖ Escape Characters
Code Result
\\ Backslash
\n New Line
10
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
\r Carriage Return
\t Tab
\b Backspace
\f Form Feed
The capitalize() method returns a string where the first character is upper case, and the rest
is lower case.
x = txt.capitalize()
print (x)
The casefold() method returns a string where all the characters are lower case.
x = txt.casefold()
print(x)
The center() method will center align the string, using a specified character (space is
default) as the fill character.
x = txt.center(20)
print(x)
11
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
txt = "banana"
x = txt.center(20, "O")
print(x)
Output:-
OOOOOOObananaOOOOOOO
The count() method returns the number of times a specified value appears in the string.
x = txt.count("apple")
print(x)
The join() method takes all items in an iterable and joins them into one string.
x = "#".join(myTuple)
print(x)
output:-
John#Peter#Vicky
Example :-
myDict = {"name": "John", "country": "Norway"}
mySeparator = "TEST"
x = mySeparator.join(myDict)
print(x)
Output:-
nameTESTcountry
The translate() method returns a string where some specified characters are replaced with
the character described in a dictionary, or in a mapping table.
12
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
Hello Pam!
Example :-
txt = "Hello Sam!"
mytable = str.maketrans("S", "P")
print(txt.translate(mytable))
Output:-
Hello Pam!
The zfill() method adds zeros (0) at the beginning of the string, until it reaches the specified
length.
If the value of the len parameter is less than the length of the string, no filling is done.
txt = "50"
x = txt.zfill(10)
print(x)
Output :-
0000000050
Example :-
a = "hello"
b = "welcome to the jungle"
c = "10.000"
print(a.zfill(10))
print(b.zfill(10))
print(c.zfill(10))
output:-
00000hello
welcome to the jungle
000010.000
13
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
❖ Python Operators
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
❖ Arithmetic Operators
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
❖ Assignment Operators
14
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
15
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
>>= x >>= 3 x = x >> 3
❖ Comparison Operators
== Equal x == y
!= Not equal x != y
❖ Logical Operators
16
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
Or Returns True if one of the x < 5 or x < 4
statements is true
Not Reverse the result, returns False not(x < 5 and x < 10)
if the result is true
❖ Identity Operators
❖ Membership Operators
❖ Bitwise Operators
17
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
| OR Sets each bit to 1 if one of two bits is 1 x|y
<< Zero fill Shift left by pushing zeros in from the right x << 2
left shift and let the leftmost bits fall off
18
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
19
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
20
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
21
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
22
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
23
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
24
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
25
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
26
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
27
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
❖ Python Collections (Arrays)
There are four collection data types in the Python programming language:
List
List items are indexed, the first item has index [0], the second item has index [1] etc.
28
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
Ordered
When we say that lists are ordered, it means that the items have a defined order, and that
order will not change.
If you add 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:
Example :-
list = ["apple", "banana", "cherry", "apple", "cherry"]
print(list)
List Length
To determine how many items a list has, use the len() function:
Python's perspective, lists are defined as objects with the data type 'list':
mylist = ["apple", "banana", "cherry"]
print(type(mylist))
Access Items
List items are indexed and you can access them by referring to the index number:
Example :-
thislist = ["apple", "banana", "cherry"]
print(thislist[1])
29
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
-1 refers to the last item, -2 refers to the second last item etc.
thislist = ["apple", "banana", "cherry"]
print(thislist[-1])
Range of Indexes
You can 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 list with the specified items.
a = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(a[2:5])
This example returns the items from the beginning to, but NOT including, "kiwi":
a = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(a[:4])
Change the second and third value by replacing it with one value:
a = ["apple", "banana", "cherry"]
a[1:3] = ["watermelon"]
print(a)
30
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
Output:-
['apple', 'watermelon']
To add an item to the end of the list, use the append() method:
a = ["apple", "banana", "cherry"]
a.append("orange")
print(a)
Output:-
['apple', 'banana', 'cherry', 'orange']
To append elements from another list to the current list, use the extend() method.
a = ["apple", "banana", "cherry"]
b = ["mango", "pineapple", "papaya"]
a.extend(b)
print(a)
Output:-
['apple', 'banana', 'cherry', 'mango', 'pineapple', 'papaya']
If there are more than one item with the specified value, the remove() method removes the
first occurance:
a = ["apple", "banana", "cherry", "banana", "kiwi"]
a.remove("banana")
print(a)
['apple', 'cherry', 'banana', 'kiwi']
31
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
Remove the last item:
thislist = ["apple", "banana", "cherry"]
thislist.pop()
print(thislist)
While Loop
You can loop through the list items by using a while loop.
32
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
Use the len() function to determine the length of the list, then start at 0 and loop your way
through the list items by referring to their indexes.
Remember to increase the index by 1 after each iteration.
thislist = ["apple", "banana", "cherry"]
i=0
while i < len(thislist):
print(thislist[i])
i=i+1
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)
output:-
['apple', 'banana', 'mango']
With list comprehension you can do all that with only one line of code:
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
print(newlist)
output:-
['apple', 'banana', 'mango']
33
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
Iterable
The iterable can be any iterable object, like a list, tuple, set etc.
newlist = [x for x in range(10)]
output:-
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Sort Descending
To sort descending, use the keyword argument reverse = True:
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort(reverse = True)
print(thislist)
34
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
['Kiwi', 'Orange', 'banana', 'cherry']
Reverse Order
What if you want to reverse the order of a list, regardless of the alphabet?
The reverse() method reverses the current sorting order of the elements.
thislist = ["banana", "Orange", "Kiwi", "cherry"]
thislist.reverse()
print(thislist)
output:-
['cherry', 'Kiwi', 'Orange', 'banana']
Another way to join two lists is 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)
output:-
['a', 'b', 'c', 1, 2, 3]
35
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
thislist = ["apple", "banana", "cherry"]
mylist = thislist.copy()
print(mylist)
Output:-
['apple', 'banana', 'cherry']
Tuple
Tuples are used to store multiple items in a single variable.
Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3
are List, Set, and Dictionary, all with different qualities and usage.
A tuple is a collection which is ordered and unchangeable.
Tuples are written with round brackets.
Example:-
a = ("apple", "banana", "cherry")
print(a)
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 tuples are indexed, they can have items with the same value:
thistuple = ("apple", "banana", "cherry", "apple", "cherry")
print(thistuple)
Output:-
('apple', 'banana', 'cherry', 'apple', 'cherry')
36
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
thistuple = ("apple", "banana", "cherry")
if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")
output:-
Yes, 'apple' is in the fruits tuple
You can loop through the tuple items by using a for loop.
thistuple = ("apple", "banana", "cherry")
for i in range(len(thistuple)):
print(thistuple[i])
output:-
apple
banana
cherry
Set
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, the other 3
are List, Tuple, and Dictionary, all with different qualities and usage.
A set is a collection which is unordered, unchangeable*, and unindexed.
Note: Set items are unchangeable, but you can remove items and add new items.
Example:-
thisset = {"apple", "banana", "cherry"}
print(thisset)
output:-
{'banana', 'apple', 'cherry'}
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
Set items are unchangeable, meaning that we cannot change the items after the set has been
created.
37
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
Duplicates Not Allowed
Sets cannot have two items with the same value.
a = {"apple", "banana", "cherry", "apple"}
print(a)
output:-
{'banana', 'cherry', 'apple'}
Access Items
You cannot access items in a set by referring to an index or a key.
But you can loop through the set items using a for loop, or ask if a specified value is present
in a set, by using the in keyword.
thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)
output:
True
thisset.add("orange")
print(thisset)
output:-
{'cherry', 'banana', 'orange', 'apple'}
To add items from another set into the current set, use the update() method.
thisset = {"apple", "banana", "cherry"}
tropical = {"pineapple", "mango", "papaya","banana"}
thisset.update(tropical)
print(thisset)
Output:-
{'banana', 'cherry', 'papaya', 'pineapple', 'mango', 'apple'}
Dictionary
Dictionaries are used to store data values in key:value pairs.
A dictionary is a collection which is ordered*, changeable and do not allow duplicates.
thisdict = {
38
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
output:-
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
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"])
output:
Ford
Changeable
Dictionaries are changeable, meaning that we can change, add or remove items after the
dictionary has been created.
Duplicates Not Allowed
Dictionaries cannot have two items with the same key:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict)
output:-
{'brand': 'Ford', 'model': 'Mustang', 'year': 2020}
39
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
To determine how many items a dictionary has, use the len() function:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(len(thisdict))
Output:-
3
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)
output:-
Mustang
The keys() method will return a list of all the keys in the dictionary.
thisdict = {
"brand": "Ford",
"model": "Mustang",
40
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
"year": 1964
}
x = thisdict.keys()
print(x)
output:-
dict_keys(['brand', 'model', 'year'])
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)
output:-
dict_values(['Ford', 'Mustang', 1964])
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
output:-
dict_values(['Ford', 'Mustang', 1964])
dict_values(['Ford', 'Mustang', 1964, 'red'])
The items() method will return each item in a dictionary, as tuples in a list.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
41
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
}
x = thisdict.items()
print(x)
Output:-
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])
42
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in thisdict:
print(thisdict[x])
output:-
Ford
Mustang
1964
You can also use the values() method to return values of a dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in thisdict.values():
print(x)
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)
output:-
brand Ford
model Mustang
year 1964
Nested Dictionaries
44
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
❖ Functions
Creating a Function
Arguments
Number of Arguments
By default, a function must be called with the correct number of arguments. Meaning that if
your function expects 2 arguments, you have to call the function with 2 arguments, not
more, and not less.
def my_function(fname, lname):
45
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
print(fname + " " + lname)
my_function("Emil", "Refsnes")
output:
Emil Refsnes
46
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
❖ Classes/Objects
The examples above are classes and objects in their simplest form, and are not really useful
in real life applications.
To understand the meaning of classes we have to understand the built-in __init__() function.
All classes have a function called __init__(), which is always executed when the class is being
initiated.
Use the __init__() function to assign values to object properties, or other operations that are
necessary to do when the object is being created:
Example:-
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
Note: The __init__() function is called automatically every time the class is being used to
create a new object.
The __str__() function controls what should be returned when the class object is represented
as a string.
If the __str__() function is not set, the string representation of the object is returned:
Example:-
47
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name}({self.age})"
p1 = Person("John", 36)
print(p1)
The self parameter is a reference to the current instance of the class, and is used to access
variables that belongs to the class.
It does not have to be named self , you can call it whatever you like, but it has to be the first
parameter of any function in the class:
Example:-
class Person:
def __init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age
def myfunc(abc):
print("Hello my name is " + abc.name)
p1 = Person("John", 36)
p1.myfunc()
class definitions cannot be empty, but if you for some reason have a class definition with no
content, put in the pass statement to avoid getting an error.
Example:-
class Person:
pass
# having an empty class definition like this, would raise an error without the pass statement
❖ Inheritance
Inheritance allows us to define a class that inherits all the methods and properties from
another class.
48
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
Parent class is the class being inherited from, also called base class.
Child class is the class that inherits from another class, also called derived class.
❖ Parent Class
Any class can be a parent class, so the syntax is the same as creating any other class:
Example:-
Create a class named Person, with firstname and lastname properties, and
a printname method:
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
#Use the Person class to create an object, and then execute the printname method:
x = Person("John", "Doe")
x.printname()
49
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]