Python Fundamentals
Python Fundamentals
Let's create a very simple program called Hello World. A "Hello, World!" is a simple
program that outputs Hello, World! on the screen.
print("Hello, world!")
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Python Keywords and Identifiers
Python Keywords
They are used to define the syntax and structure of the Python language.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
False await else import pass
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Python Identifiers
An identifier is a name given to entities like class, functions, variables, etc. It helps to
differentiate one entity from another.
An identifier cannot start with a digit. 1variable is invalid, but variable1 is a valid
name.
Python Statement
Instructions that a Python interpreter can execute are called statements. For
example, a = 1 is an assignment statement. if statement, for statement, while
statement, etc.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Multi-line statement
In Python, the end of a statement is marked by a newline character. But we can make a statement extend over
multiple lines with the line continuation character (\). For example:
a=1+2+3+\
4+5+6+\
7+8+9
This is an explicit line continuation. In Python, line continuation is implied inside parentheses ( ), brackets [ ],
and braces { }. For instance, we can implement the above multi-line statement as:
a = (1 + 2 + 3 +
4+5+6+
7 + 8 + 9)
Here, the surrounding parentheses ( ) do the line continuation implicitly. Same is the case with [ ] and { }. For
example:
colors = ['red',
'blue',
'green']
We can also put multiple statements in a single line using semicolons, as follows:
a = 1; b = 2; c = 3
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Python Indentation
Most of the programming languages like C, C++, and Java use braces { } to define a
block of code. Python, however, uses indentation.
A code block (body of a function, loop, etc.) starts with indentation and ends with
the first unindented line. The amount of indentation is up to you, but it must be
consistent throughout that block.
Generally, four whitespaces are used for indentation and are preferred over tabs.
Here is an example.
for i in range(1,11):
print(i)
if i == 5:
break
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
The enforcement of indentation in Python makes the code look neat and clean. This
results in Python programs that look similar and consistent.
Indentation can be ignored in line continuation, but it's always a good idea to indent.
It makes the code more readable. For example:
if True:
print('Hello')
a=5
and
if True: print('Hello'); a = 5
both are valid and do the same thing, but the former style is clearer.
#This is a comment
#print out Hello
print('Hello')
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Multi-line comments
We can have comments that extend up to multiple lines. One way is to use the hash(#)
symbol at the beginning of each line. For example:
These triple quotes are generally used for multi-line strings. But they can be used as a
multi-line comment as well. Unless they are not docstrings, they do not generate any
extra code.
"""This is also a
perfect example of
multi-line comments"""
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Docstrings in Python
Python docstrings (documentation strings) are the string literals that appear right
after the definition of a function, method, class, or module.
def double(num):
"""Function to double the value"""
return 2*num
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Docstrings appear right after the definition of a function, class, or a module. This
separates docstrings from multiline comments using triple quotes.
The docstrings are associated with the object as their __doc__ attribute.
So, we can access the docstrings of the above function with the following lines of
code:
def double(num):
"""Function to double the value"""
return 2*num
print(double.__doc__)
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Python Variables, Constants and
Literals
Python Variables
A variable is a named location used to store data in the memory. It is helpful to
think of variables as a container that holds data that can be changed later in the
program. For example,
number = 10
Here, we have created a variable named number. We have assigned the value 10 to
the variable.
number = 10
number = 1.1
Initially, the value of number was 10. Later, it was changed to 1.1.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Note: In Python, we don't actually assign values to the variables. Instead,
Python gives the reference of the object(value) to the variable.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Assigning values to Variables in Python
As you can see from the above example, you can use the assignment operator = to
assign a value to a variable.
website = “talentbattle.in"
Note: Python is a type-inferred language, so
print(website)
you don't have to explicitly define the variable
type. It automatically knows that
talentbattle.in is a string and declares the
website variable as a string.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Example 2: Changing the value of a variable
website = “talentbattle.in"
print(website)
print(website)
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Example 3: Assigning multiple values to multiple variables
a, b, c = 5, 3.2, "Hello"
print (a)
print (b)
print (c)
If we want to assign the same value to multiple variables at once, we can do this as:
x = y = z = "same"
print (x)
print (y)
print (z)
The second program assigns the same string to all the three variables x, y and z.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Constants
2.If you want to create a variable name having two words, use underscore
to separate.
5.Don't startThisavideo
variable name with a digit.
is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Literals
Literal is a raw data given in a variable or constant. In Python, there are various types
of literals they are as follows:
Numeric Literals
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
a = 0b1010 #Binary Literals
b = 100 #Decimal Literal
c = 0o310 #Octal Literal
d = 0x12c #Hexadecimal Literal
#Float Literal
float_1 = 10.5
float_2 = 1.5e2
print(a, b, c, d)
print(float_1, float_2)
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
In the above program,
When we print the variables, all the literals are converted into decimal values.
10.5 and 1.5e2 are floating-point literals.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
String literals
print(strings)
print(char)
print(multiline_str)
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Boolean literals
A Boolean literal can have any of the two values: True or False.
print("x is", x)
print("y is", y)
print("a:", a)
print("b:", b)
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
In the above program, we use boolean literal True and False.
In Python, True represents the value as 1 and False as 0. The value of x is True
because 1 is equal to True. And, the value of y is False because 1 is not equal to
False.
Similarly, we can use the True and False in numeric expressions as the value.
The value of a is 5 because we add True which has a value of 1 with 4. Similarly, b is
10 because we add the False having value of 0 with 10.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Special literals
Python contains one special literal i.e. None. We use it to specify that the field has not
been created.
def menu(x):
if x == drink:
print(drink)
else:
print(food)
menu(drink)
menu(food)
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Literal Collections
There are four different literal collections List literals, Tuple literals, Dict literals, and
Set literals.
print(fruits)
print(numbers)
print(alphabets)
print(vowels)
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Python Data Types
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Python Numbers
Integers, floating point numbers and complex numbers fall under Python numbers
category. They are defined as int, float and complex classes in Python.
We can use the type() function to know which class a variable or a value belongs to.
Similarly, the isinstance() function is used to check if an object belongs to a particular
class.
a = 10
print(a, "is of type", type(a))
a = 2.8
print(a, "is of type", type(a))
a = 1+2j
print(a, "is complex number?", isinstance(1+2j,complex))
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Integers can be of any length, it is only limited by the memory available.
Complex numbers are written in the form, x + yj, where x is the real part and y is the
imaginary part. Here are some examples.
a = 1234567890123456789
print(a)
b = 0.1234567890123456789
print(b)
c = 1+2j
print(c)
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Python List
List is an ordered sequence of items. It is one of the most used datatype in Python
and is very flexible. All the items in a list do not need to be of the same type.
Declaring a list is pretty straight forward. Items separated by commas are enclosed
within brackets [ ].
We can use the slicing operator [ ] to extract an item or a range of items from a list.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
a = [5,10,15,20,25,30,35,40]
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Python Tuple
Tuple is an ordered sequence of items same as a list. The only difference is that
tuples are immutable. Tuples once created cannot be modified.
Tuples are used to write-protect data and are usually faster than lists as they cannot
change dynamically.
t = (5,'programmiing’, 4+5j)
We can use the slicing operator [] to extract items but we cannot change its value.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
t = (50,'programming’, 5+4j)
# t[1] = 'programming'
print("t[1] = ", t[1])
# Generates error
# Tuples are immutable
t[0] = 10
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Python Strings
s = "This is a string"
print(s)
s = '''A multiline
string'''
print(s)
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Just like a list and tuple, the slicing operator [ ] can be used with strings. Strings,
however, are immutable.
s = 'Hello world!'
# s[4] = 'o'
print("s[4] = ", s[4])
# s[6:11] = 'world'
print("s[6:11] = ", s[6:11])
# Generates error
# Strings are immutable in Python
s[5] ='d'
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Python Set
a = {5,2,3,1,4}
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
We can perform set operations like union, intersection on two sets. Sets have unique
values. They eliminate duplicates.
a = {1,2,2,3,3,3}
print(a)
Output
{1, 2, 3}
Since, set are unordered collection, indexing has no meaning. Hence, the slicing
operator [] does not work.
a = {1,2,3}
a[1]
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Python Dictionary
It is generally used when we have a huge amount of data. Dictionaries are optimized for
retrieving data. We must know the key to retrieve the value.
In Python, dictionaries are defined within braces {} with each item being a pair in the
form key:value. Key and value can be of any type.
d = {1:'value','key':2}
type(d)
<class 'dict'>
We use key to retrieve the respective value. But not the other way around.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
d = {1:'value','key':2}
print(type(d))
# Generates error
print("d[2] = ", d[2])
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
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.
As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are
unordered.
Dictionaries are written with curly brackets, and have keys and values:
Example
Create and print a dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
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.
Example Example
Print the "brand" value of the dictionary: Duplicate values will overwrite existing values:
thisdict = { thisdict = {
"brand": "Ford", "brand": "Ford",
"model": "Mustang", "model": "Mustang",
"year": 1964 "year": 1964,
} "year": 2020
print(thisdict["brand"]) }
print(thisdict)
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Python Input, Output and Import
Python provides numerous built-in functions that are readily available to us at the
Python prompt.
Some of the functions like input() and print() are widely used for standard input
and output operations respectively.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
a=5
Python Output Using print() function
print('The value of a is', a)
The sep separator is used between the values. It defaults into a space character.
After all values are printed, end is printed. It defaults into a new line.
The file is the object where the values are printed and its default value is sys.stdout
(screen).
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Output formatting
Sometimes we would like to format our output to make it look attractive. This can be
done by using the str.format() method. This method is visible to any string object.
x = 5; y = 10
print('The value of x is {} and y is {}'.format(x,y))
Here, the curly braces {} are used as placeholders. We can specify the order in which
they are printed by using numbers (tuple index).
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
print('Hello {name}, {greeting}'.format(greeting = 'Good Night', name = ‘TalentBattle'))
We can specify the order in which they are printed by using numbers (tuple index).
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Python Input
To allow flexibility, we might want to take the input from the user. In Python, we have
the input() function to allow this. The syntax for input() is:
input([prompt])
where prompt is the string we wish to display on the screen. It is optional.
Here, we can see that the entered value 10 is a string, not a number. To convert this
into a number we can use int() or float() functions.
int('10')
10
float('10')
10.0 This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
int('2+3’)
eval('2+3')
5
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Python Import
When our program grows bigger, it is a good idea to break it into different
modules.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
For example, we can import the math module by typing the following line:
import math
We can use the module in the following ways:
import math
print(math.pi)
Output
3.141592653589793
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Python Operators
Operators are special symbols in Python that carry out arithmetic or logical
computation. The value that the operator operates on is called the operand.
For example:
2+3
5
Here, + is the operator that performs addition. 2 and 3 are the operands and 5 is the
output of the operation.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Arithmetic operators
Operator Meaning Example
+ Add two operands or unary plus x + y+ 2
/ Divide left operand by the right one (always results into float) x/y
% Modulus - remainder of the division of left operand by the right x % y (remainder of x/y)
** Exponent - left operand raised to the power of right x**y (x to the power y)
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Example 1: Arithmetic operators in Python
x = 15
y=4
# Output: x + y = 19
print('x + y =',x+y)
# Output: x - y = 11
print('x - y =',x-y)
# Output: x * y = 60
print('x * y =',x*y)
# Output: x / y = 3.75
print('x / y =',x/y)
# Output: x // y = 3
print('x // y =',x//y)
# Output: x ** y = 50625
print('x ** y =',x**y)
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Comparison operators
Operator Meaning Example
> Greater than - True if left operand is greater than the right x>y
< Less than - True if left operand is less than the right x<y
Less than or equal to - True if left operand is less than or equal to the
<= x <= y
right
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Example 2: Comparison operators in Python
x = 10
y = 12
# Output: x == y is False
print('x == y is',x==y)
# Output: x != y is True
print('x != y is',x!=y)
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Logical operators
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Example 3: Logical Operators in Python
x = True
y = False
print('x or y is',x or y)
print('not x is',not x)
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Bitwise operators
Bitwise operators act on operands as if they were strings of binary digits. They operate
bit by bit, hence the name.
In the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Operator Meaning Example
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Assignment operators
Operator Example Equivalent to
= x=5 x=5
+= x += 5 x=x+5
-= x -= 5 x=x-5
*= x *= 5 x=x*5
/= x /= 5 x=x/5
%= x %= 5 x=x%5
//= x //= 5 x = x // 5
**= x **= 5 x = x ** 5
|= x |= 5 x=x|5
^= x ^= 5 x=x^5
Python language offers some special types of operators like the identity operator or the
membership operator. They are described below with examples.
Identity operators
is and is not are the identity operators in Python. They are used to check if two values
(or variables) are located on the same part of the memory. Two variables that are equal
does not imply that they are identical.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Example : Identity operators in Python
x1 = 5
y1 = 5
x2 = 'Hello'
y2 = 'Hello' Here, we see that x1 and y1 are integers of the
x3 = [1,2,3] same values, so they are equal as well as
y3 = [1,2,3] identical. Same is the case with x2 and y2
(strings).
# Output: False
print(x1 is not y1) But x3 and y3 are lists. They are equal but not
identical. It is because the interpreter locates
# Output: True them separately in memory although they are
print(x2 is y2) equal.
# Output: False
print(x3 is y3)
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Membership operators
in and not in are the membership operators in Python. They are used to test whether a
value or variable is found in a sequence (string, list, tuple, set and dictionary).
In a dictionary we can only test for presence of key, not the value.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Example : Membership operators in Python
x = 'Hello world'
y = {1:'a',2:'b'}
# Output: True
print('H' in x)
Here, 'H' is in x but 'hello' is not present in x
# Output: True (remember, Python is case sensitive). Similarly,
print('hello' not in x) 1 is key and 'a' is the value in dictionary y.
Hence, 'a' in y returns False.
# Output: True
print(1 in y)
# Output: False
print('a' in y)
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Python if...else Statement
Decision making is required when we want to execute a code only if a certain condition is
satisfied.
In Python, the body of the if statement is indicated by the indentation. The body starts with an
indentation and the first unindented line marks the end.
Python interprets non-zero values as True. None and 0 are interpreted as False.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
# If the number is positive, we print an appropriate message
num = 3
if num > 0:
print(num, "is a positive number.")
print("This is always printed.")
num = -1
if num > 0:
print(num, "is a positive number.")
print("This is also always printed.")
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Python if...else Statement
Syntax of if...else
if test expression:
Body of if
else:
Body of else
The if..else statement evaluates test expression and will execute the body of if only
when the test condition is True.
If the condition is False, the body of else is executed. Indentation is used to separate
the blocks.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
# Program checks if the number is positive or negative
# And displays an appropriate message
num = 3
if num >= 0:
print("Positive or Zero")
else:
print("Negative number")
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Python if...elif...else Statement
Syntax of if...elif...else
if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else
The elif is short for else if. It allows us to check for multiple expressions.
If the condition for if is False, it checks the condition of the next elif block and so on.
If all the conditions are False, the body of else is executed.
Only one block among the several if...elif...else blocks is executed according to the
condition.
The if block can have only one else block. But it can have multiple elif blocks.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
num = 3.4
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Python Nested if statements
Any number of these statements can be nested inside one another. Indentation is the
only way to figure out the level of nesting. They can get confusing, so they must be
avoided unless necessary.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
num = float(input("Enter a number: "))
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Python for Loop
The for loop in Python is used to iterate over a sequence (list, tuple, string) or other
iterable objects. Iterating over a sequence is called traversal.
Here, val is the variable that takes the value of the item inside the sequence on each
iteration.
Loop continues until we reach the last item in the sequence. The body of for loop is
separated from the rest of the code using indentation.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
# Program to find the sum of all numbers stored in a list
# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
The range() function
We can also define the start, stop and step size as range(start, stop,step_size).
step_size defaults to 1 if not provided.
However, it is not an iterator since it supports in, len and __getitem__ operations.
To force this function to output all the items, we can use the function list().
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
print(range(10))
print(list(range(10)))
print(list(range(2, 8)))
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
# Program to iterate through a list using indexing
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
for loop with else
A for loop can have an optional else block as well. The else part is executed if the
items in the sequence used in for loop exhausts.
The break keyword can be used to stop a for loop. In such cases, the else part is
ignored.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
digits = [0, 1, 5]
for i in digits:
print(i)
else:
print("No items left.")
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
# program to display student's marks from record
student_name = ‘Talent'
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Python while Loop
The while loop in Python is used to iterate over a block of code as long as the test
expression (condition) is true.
We generally use this loop when we don't know the number of times to iterate
beforehand.
In the while loop, test expression is checked first. The body of the loop is entered only
if the test_expression evaluates to True. After one iteration, the test expression is
checked again. This process continues until the test_expression evaluates to False.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
# Program to add natural
# numbers up to
# sum = 1+2+3+...+n
while i <= n:
sum = sum + i
i = i+1 # update counter
Same as with for loops, while loops can also have an optional else block.
The else part is executed if the condition in the while loop evaluates to False.
The while loop can be terminated with a break statement. In such cases, the else part
is ignored. Hence, a while loop's else part runs if no break occurs and the condition is
false.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
#Illustration
counter = 0
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Python break and continue
In Python, break and continue statements can alter the flow of a normal loop.
Loops iterate over a block of code until the test expression is false, but sometimes we
wish to terminate the current iteration or even the whole loop without checking test
expression.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Python break statement
The break statement terminates the loop containing it. Control of the program flows
to the statement immediately after the body of the loop.
If the break statement is inside a nested loop (loop inside another loop), the break
statement will terminate the innermost loop.
Syntax of break
break
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
# Use of break statement inside the loop
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Python continue statement
The continue statement is used to skip the rest of the code inside a loop for the
current iteration only. Loop does not terminate but continues on with the next
iteration.
Syntax of Continue
continue
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
# Program to show the use of continue statement inside loops
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Python pass statement
Syntax of pass
Pass
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Suppose we have a loop or a function that is not implemented yet, but we want to
implement it in the future. They cannot have an empty body. The interpreter would
give an error. So, we use the pass statement to construct a body that does nothing.
def function(args):
pass
class Example:
pass
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
a = 10
b = 20
if(a<b):
pass
else:
print("b<a")
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
li =['a', 'b', 'c', 'd']
for i in li:
if(i =='a'):
pass
else:
print(i)
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
What is a function in Python?
Functions help break our program into smaller and modular chunks.
As our program grows larger and larger, functions make it more organized and
manageable.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Syntax of Function
def function_name(parameters):
"""docstring"""
statement(s)
Above shown is a function definition that consists of the following components.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
def daily(name):
daily(‘Talent Battle')
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
def absolute_value(num):
if num >= 0:
return num
else:
return -num
print(absolute_value(2))
print(absolute_value(-4))
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Scope and Lifetime of variables
Parameters and variables defined inside a function are not visible from outside
the function. Hence, they have a local scope.
The lifetime of a variable is the period throughout which the variable exits in the
memory.
They are destroyed once we return from the function. Hence, a function does
not remember the value of a variable from its previous calls.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Here, we can see that the value of x is 20 initially.
Even though the function my_func() changed the
def my_func(): value of x to 10, it did not affect the value outside
x = 10 the function.
print("Value inside function:",x)
This is because the variable x inside the function is
different (local to the function) from the one
x = 20 outside. Although they have the same names, they
my_func() are two different variables with different scopes.
print("Value outside function:",x)
On the other hand, variables outside of the function
are visible from inside. They have a global scope.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Python User-defined Functions
Functions that we define ourselves to do certain specific task are referred as user-
defined functions.
Functions that readily come with Python are called built-in functions. If we use
functions written by others in the form of library, it can be termed as library
functions.
All the other functions that we write on our own fall under user-defined functions.
So, our user-defined function could be a library function to someone else.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Advantages of user-defined functions
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
def add_numbers(x,y):
sum = x + y
return sum
num1 = 5
num2 = 6
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Python Function Arguments
In Python, you can define a function that takes variable number of arguments.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Python Default Arguments
greet("Kate")
greet("Bruce", "How do you do?")
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
In this function, the parameter name does not have a default value and is required
(mandatory) during a call.
On the other hand, the parameter msg has a default value of "Good morning!". So, it is
optional during a call. If a value is provided, it will overwrite the default value.
Any number of arguments in a function can have a default value. But once we have a
default argument, all the arguments to its right must also have default values.
This means to say, non-default arguments cannot follow default arguments. For example,
if we had defined the function header above as:
When we call a function with some values, these values get assigned to the
arguments according to their position.
For example, in the above function greet(), when we called it as greet("Bruce", "How
do you do?"), the value "Bruce" gets assigned to the argument name and similarly
"How do you do?" to msg.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
# 2 keyword arguments
greet(name = "Bruce",msg = "How do you do?")
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Python Arbitrary Arguments
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Python Recursion
What is recursion?
Recursion is the process of defining something in terms of
itself.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Factorial of a number is the product of all the integers from 1 to that number.
For example, the factorial of 6 (denoted as 6!) is 1*2*3*4*5*6 = 720.
if x == 1:
return 1
else:
return (x * factorial(x-1))
num = 3
print("The factorial of", num, "is", factorial(num))
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
When we call this function with a positive integer, it will recursively call itself by
decreasing the number.
Each function multiplies the number with the factorial of the number below it until it
is equal to one. This recursive call can be explained in the following steps.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Our recursion ends when the number reduces to 1. This is called the base condition.
Every recursive function must have a base condition that stops the recursion or else
the function calls itself infinitely.
The Python interpreter limits the depths of recursion to help avoid infinite recursions,
resulting in stack overflows.
By default, the maximum depth of recursion is 1000. If the limit is crossed, it results
in RecursionError.
def recursor():
recursor()
recursor()
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Advantages of Recursion
Disadvantages of Recursion
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Python Anonymous/Lambda Function
While normal functions are defined using the def keyword in Python, anonymous
functions are defined using the lambda keyword.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
How to use lambda Functions in Python?
Lambda functions can have any number of arguments but only one expression. The
expression is evaluated and returned. Lambda functions can be used wherever
function objects are required.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Example of Lambda Function in python
print(double(5))
Output
10
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
In the above program, lambda x: x * 2 is the lambda function. Here x is the argument
and x * 2 is the expression that gets evaluated and returned.
This function has no name. It returns a function object which is assigned to the
identifier double. We can now call it as a normal function. The statement
double = lambda x: x * 2
def double(x):
return x * 2
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Example use with filter()
The filter() function in Python takes in a function and a list as arguments.
The function is called with all the items in the list and a new list is returned which
contains items for which the function evaluates to True.
Here is an example use of filter() function to filter out only even numbers from a list.
print(new_list)
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Example use with map()
The map() function in Python takes in a function and a list.
The function is called with all the items in the list and a new list is returned which
contains items returned by that function for each item.
Here is an example use of map() function to double all the items in a list.
print(new_list)
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Python import statement
We can import a module using the import statement and access the definitions inside
it using the dot operator as described above. Here is an example.
import math
print("The value of pi is", math.pi)
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Import with renaming
import math as m
print("The value of pi is", m.pi)
We have renamed the math module as m. This can save us typing time in some cases.
Note that the name math is not recognized in our scope. Hence, math.pi is invalid, and
m.pi is the correct implementation.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Python from...import statement
We can import specific names from a module without importing the module as a
whole. Here is an example.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Import all names
We can import all names(definitions) from a module using the following construct:
Here, we have imported all the definitions from the math module.
Importing everything with the asterisk (*) symbol is not a good programming practice.
This can lead to duplicate definitions for an identifier. It also hampers the readability of
our code.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
The dir() built-in function
We can use the dir() function to find out names that are defined inside a module.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Python Package
As our application program grows larger in size with a lot of modules, we place
similar modules in one package and different modules in different packages. This
makes a project (program) easy to manage and conceptually clear.
Similarly, as a directory can contain subdirectories and files, a Python package can
have sub-packages and modules.
A directory must contain a file named __init__.py in order for Python to consider it
as a package. This file can be left empty but we generally place the initialization code
for that package in this file.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Importing module from a package
We can import modules from packages using the dot (.) operator.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Python Strings
What is String in Python?
A string is a sequence of characters.
A character is simply a symbol. For example, the English language has 26 characters.
Computers do not deal with characters, they deal with numbers (binary). Even though
you may see characters on your screen, internally it is stored and manipulated as a
combination of 0s and 1s.
This conversion of character to a number is called encoding, and the reverse process is
decoding. ASCII and Unicode are some of the popular encodings used.
my_string = 'Hello'
print(my_string)
my_string = "Hello"
print(my_string)
my_string = '''Hello'''
print(my_string)
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
How to access characters in a string?
We can access individual characters using indexing and a range of characters using
slicing. Index starts from 0. Trying to access a character out of index range will raise an
IndexError. The index must be an integer. We can't use floats or other types, this will
result into TypeError.
The index of -1 refers to the last item, -2 to the second last item and so on. We can
access a range of items in a string by using the slicing operator :(colon).
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
#Accessing string characters in Python
str = ‘talent battle'
print('str = ', str)
#first character
print('str[0] = ', str[0])
#last character
print('str[-1] = ', str[-1])
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Strings are immutable. This means that elements of a string cannot be changed once
they have been assigned.
We can simply reassign different strings to the same name.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Concatenation of Two or More Strings
Joining of two or more strings into a single one is called concatenation.
The + operator does this in Python. Simply writing two string literals together also
concatenates them.
The * operator can be used to repeat the string for a given number of times.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Iterating Through a string
We can iterate through a string using a for loop. Here is an example to count the
number of 'l's in a string.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Built-in functions to Work with Python
Various built-in functions that work with sequence work with strings as well.
Some of the commonly used ones are enumerate() and len(). The enumerate() function
returns an enumerate object. It contains the index and value of all the items in the string
as pairs. This can be useful for iteration.
str = ‘talent'
# enumerate()
list_enumerate = list(enumerate(str))
print('list(enumerate(str) = ', list_enumerate)
#character count
print('len(str) = ', len(str))
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
The format() Method for Formatting Strings
The format() method that is available with the string object is very versatile and
powerful in formatting strings. Format strings contain curly braces {} as placeholders
or replacement fields which get replaced.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
# Python string format() method
# default(implicit) order
default_order = "{}, {} and {}".format(‘Ram’,’Sham’,’Meera')
print('\n--- Default Order ---')
print(default_order)
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Common Python String Methods
Some of the commonly used methods are lower(), upper(), join(), split(), find(),
replace() etc.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
>>> “TalEntBaTTle".lower()
>>> “talEntBattLe".upper()
>>> ' '.join(['This', 'will', 'join', 'all', 'words', 'into', 'a', 'string'])
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Object Oriented Programming
class Parrot:
pass
Here, we use the class keyword to define an empty class Parrot. From class, we construct
instances.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Object
obj = Parrot()
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
The __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.
Note: The __init__() function is called automatically every time the class is being used
to create a new object.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Example
Create a class named Person, use the __init__() function to assign values for name
and age:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person(“Talent", 20)
print(p1.name)
print(p1.age)
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person(“Python”, 3)
p1.myfunc()
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
The self Parameter
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:
class Person:
def __init__(xyz, name, age):
xyz.name = name
xyz.age = age
def myfunc(abc):
print("Hello my name is " + abc.name)
print("My age is =",abc.age)
p1 = Person("Python", 3)
p1.myfunc()
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
class Parrot:
# class attribute
species = "bird"
# instance attribute
def __init__(self, name, age):
self.name = name
self.age = age
Methods are functions defined inside the body of a class. They are used to define
the behaviors of an object.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
class Parrot:
# instance attributes
def __init__(self, name, age):
self.name = name
self.age = age
# instance method
def sing(self, song):
return "{} sings {}".format(self.name, song)
def dance(self):
return "{} is now dancing".format(self.name)
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Inheritance
The newly formed class is a derived class (or child class). Similarly, the
existing class is a base class (or parent class).
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
# parent class
class Bird:
def __init__(self):
print("Bird is ready")
def whoisThis(self):
print("Bird")
def swim(self):
print("Swim faster")
# child class
class Penguin(Bird):
def __init__(self):
# call super() function
super().__init__()
print("Penguin is ready")
def whoisThis(self):
print("Penguin")
def run(self):
print("Run faster")
peggy = Penguin()
peggy.whoisThis()
peggy.swim()
peggy.run()
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
In the above program, we created two classes i.e. Bird (parent class) and Penguin (child
class). The child class inherits the functions of parent class. We can see this from the
swim() method.
Again, the child class modified the behavior of the parent class. We can see this from
the whoisThis() method. Furthermore, we extend the functions of the parent class, by
creating a new run() method.
Additionally, we use the super() function inside the __init__() method. This allows us
to run the __init__() method of the parent class inside the child class.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Encapsulation
In Python, we denote private attributes using underscore as the prefix i.e single _
or double __.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
class Computer:
def __init__(self):
self.__maxprice = 900
def sell(self):
print("Selling Price: {}".format(self.__maxprice))
c = Computer()
c.sell()
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
In the above program, we defined a Computer class.
We used __init__() method to store the maximum selling price of Computer. We tried
to modify the price. However, we can't change it because Python treats the
__maxprice as private attributes.
As shown, to change the value, we have to use a setter function i.e setMaxPrice()
which takes price as a parameter.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Polymorphism
Polymorphism is an ability (in OOP) to use a common interface for multiple forms
(data types).
Suppose, we need to color a shape, there are multiple shape options (rectangle,
square, circle).
However we could use the same method to color any shape. This concept is called
Polymorphism.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
class Parrot:
def fly(self):
print("Parrot can fly")
def swim(self):
print("Parrot can't swim")
class Penguin:
def fly(self):
print("Penguin can't fly")
def swim(self):
print("Penguin can swim")
# common interface
def flying_test(bird):
bird.fly()
#instantiate objects
blu = Parrot()
peggy = Penguin()
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
In the above program, we defined two classes Parrot and Penguin. Each of them have a
common fly() method. However, their functions are different.
Thus, when we passed the blu and peggy objects in the flying_test() function, it ran
effectively.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Key Points to Remember:
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Python Objects and Classes
An object is simply a collection of data (variables) and methods (functions) that act on
those data. Similarly, a class is a blueprint for that object.
An object is also called an instance of a class and the process of creating this
object is called instantiation.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Defining a Class in Python
Like function definitions begin with the def keyword in Python, class definitions begin
with a class keyword.
The first string inside the class is called docstring and has a brief description of the
class. Although not mandatory, this is highly recommended.
class MyNewClass:
'''This is a docstring. I have created a new class'''
pass
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
A class creates a new local namespace where all its attributes are defined. Attributes
may be data or functions.
There are also special attributes in it that begins with double underscores __. For
example, __doc__ gives us the docstring of that class.
As soon as we define a class, a new class object is created with the same name. This
class object allows us to access the different attributes as well as to instantiate new
objects of that class.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
class Person:
"This is a person class"
age = 10
def greet(self):
print('Hello')
# Output: 10
print(Person.age)
We saw that the class object could be used to access different attributes.
It can also be used to create new object instances (instantiation) of that class.
The procedure to create an object is similar to a function call.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
class Person: You may have noticed the self parameter in
"This is a person class"
age = 10
function definition inside the class but we
called the method simply as harry.greet()
def greet(self): without any arguments. It still worked.
print('Hello')
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Constructors in Python
Class functions that begin with double underscore __ are called special functions as
they have special meaning.
Of one particular interest is the __init__() function. This special function gets called
whenever a new object of that class is instantiated.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
class ComplexNumber:
def __init__(self, r=0, i=0):
self.real = r
self.imag = i
def get_data(self):
print(f'{self.real}+{self.imag}j')
num1 = ComplexNumber(2, 3)
num1.get_data()
num2 = ComplexNumber(5)
num2.attr = 10
print((num2.real, num2.imag, num2.attr))
print(num1.attr)
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
In the above example, we defined a new class to represent complex numbers. It has two
functions, __init__() to initialize the variables (defaults to zero) and get_data() to display
the number properly.
We created a new attribute attr for object num2 and read it as well. But this does not
create that attribute for object num1.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
When we do c1 = ComplexNumber(1,3), a new instance object is created in memory
and the name c1 binds with it.
On the command del c1, this binding is removed and the name c1 is deleted from the
corresponding namespace. The object however continues to exist in memory and if no
other name is bound to it, it is later automatically destroyed.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Python Inheritance
It refers to defining a new class with little or no modification to an existing class. The
new class is called derived (or child) class and the one from which it inherits is called
the base (or parent) class.
Derived class inherits features from the base class where new features can be added
to it. This results in re-usability of code.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
class Animal:
def speak(self):
print("Animal Speaking")
#child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
d = Dog()
d.bark()
d.speak()
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
class Polygon:
def __init__(self, no_of_sides):
self.n = no_of_sides
self.sides = [0 for i in range(no_of_sides)]
def inputSides(self):
self.sides = [float(input("Enter side "+str(i+1)+" : ")) for i in range(self.n)]
def dispSides(self):
for i in range(self.n):
print("Side",i+1,"is",self.sides[i])
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
class Triangle(Polygon):
def __init__(self):
Polygon.__init__(self,3)
def findArea(self):
a, b, c = self.sides
# calculate the semi-perimeter
s = (a + b + c) / 2
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print('The area of the triangle is %0.2f' %area)
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
>>> t = Triangle()
>>> t.inputSides()
We can see that even though we did not define
Enter side 1 : 3
methods like inputSides() or dispSides() for
Enter side 2 : 5
class Triangle separately, we were able to use
Enter side 3 : 4
them.
>>> t.dispSides()
If an attribute is not found in the class itself,
Side 1 is 3.0
the search continues to the base class. This
Side 2 is 5.0
repeats recursively, if the base class is itself
Side 3 is 4.0
derived from other classes.
>>> t.findArea()
The area of the triangle is 6.00
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Python Access Modifiers
In most of the object-oriented languages access modifiers are used to limit the access
to the variables and functions of a class. Most of the languages use three types of
access modifiers, they are - private, public and protected.
Just like any other object oriented programming language, access to variables or
functions can also be limited in python using the access modifiers. Python makes the
use of underscores to specify the access modifier for a specific data member and
member function in a class.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Python: Types of Access Modifiers
There are 3 types of access modifiers for a class in Python. These access modifiers
define how the members of the class can be accessed. Of course, any member of a
class is accessible inside any member function of that same class. Moving ahead to the
type of access modifiers, they are:
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
public Access Modifier
By default, all the variables and member functions of a class are public in a python
program.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
protected Access Modifier
According to Python convention adding a prefix _(single underscore) to a variable name
makes it protected.
# defining a class Employee
class Employee:
# constructor
def __init__(self, name, sal):
self._name = name; # protected attribute
self._sal = sal; # protected attribute
In the code above we have made the class variables name and sal protected by adding an
_(underscore) as a prefix, so now we can access them as follows:
Now let's try to access protected member variable of class Employee from the class HR:
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
private Access Modifier
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
# define parent class Company
class Company:
# constructor
def __init__(self, name, proj):
self.name = name # name(name of company) is public
self._proj = proj # proj(current project) is protected
2.The function that is redefined in the child class should have the same
signature as in the parent class i.e. same number of parameters.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
# parent class
class Parent:
# some random function
def anything(self):
print('Function defined in parent class!')
# child class
class Child(Parent):
# empty class definition
pass
While the child class can access the parent
class methods, it can also provide a new
obj2 = Child() implementation to the parent class
obj2.anything() methods, which is called method
overriding.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
class Animal:
# properties
multicellular = True
# Eukaryotic means Cells with Nucleus
eukaryotic = True
# function breathe
def breathe(self):
print("I breathe oxygen.")
# function feed
def feed(self):
print("I eat food.")
class Herbivorous(Animal):
# function feed
def feed(self):
print("I eat only plants. I am vegetarian.")
herbi = Herbivorous()
herbi.feed()
# calling some other function
herbi.breathe()
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Python Polymorphism Example
class Square:
side = 5
def calculate_area(self):
return self.side * self.side
class Triangle:
base = 5
height = 4
def calculate_area(self):
return 0.5 * self.base * self.height
sq = Square()
tri = Triangle()
print("Area of square: ", sq.calculate_area())
print("Area of triangle: ", tri.calculate_area())
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video
Python Multiple Inheritance
A class can be derived from more than one base class in Python, similar to C++. This is
called multiple inheritance.
In multiple inheritance, the features of all the base classes are inherited into the
derived class. The syntax for multiple inheritance is similar to single inheritance.
Example
class Base1:
pass
class Base2:
pass
class Base:
pass
class Derived1(Base):
pass
class Derived2(Derived1):
pass
Here, the Derived1 class is derived from the Base class, and the Derived2 class is
derived from the Derived1 class.
This video is sole property of Talent Battle Pvt. Ltd. Strict penal action will be taken against unauthorized piracy of this video