Python strings are sequences of characters that can be accessed and manipulated using various string methods. Strings can be declared using either single or double quotes and support escape characters. Strings are immutable and concatenation creates a new string. Common string methods include len() to get the length, lower()/upper() to case conversion, strip() to remove whitespace, and startswith()/endswith() to check substrings.
7. History of Python
Python was conceptualized in the late 1980s. Guido van Rossum worked that time in a project at the CWI, called
Amoeba, a distributed operating system with ABC language.
Guido Van Rossum published the first version of Python code (version 0.9.0) in February 1991.
This release included already exception handling, functions, and the core data types of list, dict, str and others.
Python version 1.0 was released in January 1994.
In this release were the functional programming tools lambda, map, filter and reduce.
In October 2000, Python 2.0 was introduced. This release included list comprehensions, a full garbage collector
and it was supporting unicode.
The next major release as Python 3.0 was released on December 3, 2008.
Rossum was big fan of Monty Python's Flying Circus hence he choose Python as a working title for language.
9. Python Internals
Python language is an interpreted programming or a script language.
The truth is: Python is both an interpreted and a compiled language. But calling Python a compiled language would be
misleading.
Python code is translated into intermediate code, which has to be executed by a virtual machine, known as the PVM, the Python
virtual machine. This is a similar approach to the one taken by Java.
There is even a way of translating Python programs into Java byte code for the Java Virtual Machine (JVM). This can be
achieved with Jython.
you don't have to and shouldn't bother about compiling Python code. The compilation is hidden from the user for a good reason.
If Python has write-access for the directory where the Python program resides, it will store the compiled byte code in a file that
ends with a .pyc suffix.
If Python has no write access, the program will work anyway. The byte code will be produced but discarded when the program
exits.
Whenever a Python program is called, Python will check, if a compiled version with the .pyc suffix exists. This file has to be
newer than the file with the .py suffix.
If such a file exists, Python will load the byte code, which will speed up the start up time of the script. If there exists no byte code
version, Python will create the byte code before it starts the execution of the program.
Execution of a Python program means execution of the byte code on the Python Virtual Machine (PVM).
Every time a Python script is executed, byte code is created. If a Python script is imported as a module, the byte code will be
stored in the corresponding .pyc file.
10. Indenting Code
Python programs get structured through indentation,
i.e. code blocks are defined by their indentation. This
principle makes it easier to read and understand
other people's Python code.
All statements with the same distance to the right
belong to the same block of code, i.e. the statements
within a block line up vertically.
The block ends at a line less indented or the end of
the file. If a block has to be more deeply nested, it is
simply indented further to the right.
You will find an explanation of the Pythagorean
numbers in our chapter on for loops.
from math import sqrt
n = input("Maximum Number? ")
n = int(n)+1
for a in range(1,n):
for b in range(a,n):
c_square = a**2 + b**2
c = int(sqrt(c_square))
if ((c_square - c**2) == 0):
print(a, b, c)
11. Python Comments
let you store tags at the right places in the code.
You can use them to explain complex sections of code.
The interpreter ignores comments. Declare a comment using an hash (#).
#This is single line a comment
"""This comment
is spanned across
multiple lines"""
Python Docstrings
A docstring is a documentation string in Python.
It is the first statement in a module, function, class, or method in Python.
To check a function’s docstring, use its __doc__ attribute.
def func():
"""
This function prints out a greeting
"""
print("Hi")
func()
func.__doc__
12. Multiple Statements in one line
You can also fit in more than one statement on one line. Do this by separating them with a semicolon.
a=7; print(a);
Python String Formatters
% Operator
x=10; printer="HP“
print("I just printed {0} pages to the printer{1}" .format(x, printer))
x=10; printer="HP“
print("I just printed %s pages to the printer %s" % (x, printer))
format method
x=10; printer="HP“
print(f"I just printed {x} pages to the printer {printer}")
F-string
13.
14. int
Python can hols sign as well un-sign integers.
It can hold a value of any length, the only limitation being the amount of
memory available.
There are three types of Python number functionalities.
type() : It takes one argument, and returns which class it belongs to.
isinstance() : It takes two arguments. The first is the construct(ex- a
variable or a list), and the second is a class. It returns True or False based
on whether the construct belongs to that class.
Exponential numbers : You can write an exponential number using the
letter ‘e’ between the mantissa and the exponent.
>>> a=5
>>> print(a, type(a))
5 <class 'int'>
>>> print(isinstance(a,float))
False
>>> print(2e5)
200000.0
>>> a=9999999999999999999999999999999999999
>>> a
9999999999999999999999999999999999999
15. float
Python also supports floating-point real values.
A float value is only accurate up to 15 decimal places. After
that, it rounds the number off.
Complex Number
A complex number is a Python number type made of real and
imaginary parts. It is represented as a+bj.
it is mandatory to provide a coefficient to the imaginary part.
>>> pi=3.14
>>> print(type(pi))
<class 'float'>
>>> a=1.1111111111111111119
>>> a
1.1111111111111112
>>> a=2+3j
>>> a
(2+3j)
16.
17. >>> int(7.7)
7
>>> float(7)
7.0
>>> int(2+3j)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't convert complex to int
>>> complex(3)
(3+0j)
>>> bin(2)
'0b10'
>>> bin(2.5)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'float' object cannot be interpreted as an
integer
>>> bin(3+3j)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'complex' object cannot be interpreted as an
integer
>>> oct(7)
'0o7'
>>> hex(23)
'0x17'
Number
System
Prefix
Binary 0b or 0B
Octal 0o or 0O
Hexadecimal 0x or 0X
Fractions Module
The Fraction() function of this module returns the value in the
form of numerator and denominator.
The math Module
It has all important mathematical functions like exp, trigonometric
functions, logarithmic functions, factorial, and more.
>>>from fractions import Fraction
>>>print(Fraction(1.5))
3/2
>>> print(Fraction(1,3))
1/3
>>>import math
>>>print(math.factorial(5))
120
19. Variables
There is no declaration of variables required in Python. If there is need of a variable, you think of a name and start using it as a
variable.
Another remarkable aspect of Python: Not only the value of a variable may change during program execution but the type as
well.
The equal "=" sign in the assignment shouldn't be seen as "is equal to". It should be "read" or interpreted as "is set to", meaning
in our example "the variable i is set to 42".
When Python executes an assignment like "i = 42", it evaluates the right side of the assignment and recognizes that it
corresponds to the integer number 42. It creates an object of the integer class to save this data.
i = 42
i = 42 # data type is implicitly set to integer
i = 42 + 0.11 # data type is changed to float
i = "forty" # and now it will be a string
20. Object References
Python variables are
references to objects, but
the actual data is
contained in the objects.
As variables are pointing
to objects and objects can
be of arbitrary data type,
variables cannot have
types associated with
them
We created an integer
object 42 and assigned it
to the variable x. After this
we assigned x to the
variable y.
This means that both
variables reference the
same object. The following
picture illustrates this
What will happen when we execute y=78
Python will create a new integer object with the
content 78 and then the variable y will reference
this newly created object, as we can see in the
following picture
We will see further changes to the variables in the flow of our
program. There might be, for example, a string assignment to the
variable x.
The previously integer object "42" will be orphaned after this
assignment. It will be removed by Python, because no other variable
is referencing it.
21. Valid Variable Names
A Python identifier is a name used to identify a variable, function, class, module or other object.
A variable name and an identifier can consist of the uppercase letters "A" through "Z", the lowercase letters "a" through "z" , the
underscore _ and, except for the first character, the digits 0 through 9.
Python 3.x is based on Unicode. This means that variable names and identifier names can additionally contain Unicode characters
as well.
Identifiers are unlimited in length. Case is significant.
Exceptions from the rules above are the special Python keywords :
No identifier can have the same name as one of the Python keywords, although they are obeying the above naming
conventions.
In case of Identifier with names which consist of more than one word, user can use the underscore functioned as a word
separator, because blanks are not allowed in variable names. For example "maximum_height“.
and, as, assert, break, class, continue, def, del, elif, else, except, False, finally, for, from, global, if, import, in, is, lambda, None,
nonlocal, not, or, pass, raise, return, True, try, while, with, yield
A……..Z a……..z 0…...9 _
22. Multiple Assignment
You can assign values to multiple python variables in one statement.
Deleting Variable:
You can delete variable using ‘del’ keyword.
>>> age,city=21,'Indore'
>>> print(age, city)
21 Indore
>>> x=y=7
>>> print(x,y)
7 7
>>> a, b=30, 40 #number Swapping
>>> print(a, b)
30 40
>>> a, b= b, a
>>> print(a, b)
40 30
>>> a='red'
>>> print(a)
red
>>> del a
>>> print(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
23. Python Local and Global Variables
a. Local variables
When you declare a variable in a function, class, or so, it is only
visible in that scope.
If you call it outside of that scope, you get an ‘undefined’ error.
b. Global variables
When you declare a variable outside any context/scope, it is
visible in the whole program.
Note :You can use the ‘global’ keyword when you want to treat a
variable as global in a local scope.
>>> def func1():
... uvw=2
... print(uvw)
>>> func1()
2
>>> uvw
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'uvw' is not defined
>>> def func2():
... xyz=0
... xyz+=1
... print(xyz)
...
>>> func2()
1
>>> xyz
3
>>> foo=1
>>> def func2():
... global foo
... foo=3
... print(foo)
...
>>> func2()
3
26. Introduction to Python String
A Python string is a sequence of characters. There is a built-in class
‘str’ for handling Python string.
You can prove this with the type() function.
Python doesn’t have the char data-type like C++ or Java does.
How to Declare Python String
You can declare a Python string using either single quotes or
double quotes.
However, you cannot use a single quote to begin a string and a
double quote to end it, and vice-versa.
Use Quotes inside Python String
If you need to use double quotes inside a Python string, delimit the
string with single quotes.
if you need to use single quotes inside a string, delimit it with
double quotes.
You can use as many quotes as you want
>>> type('Dogs are love')
<class 'str'>
>>> a='Dogs are love'
>>> b="Dogs are love"
>>> print(a, b)
Dogs are love Dogs are love
>>> a='Dogs are love"
File "<stdin>", line 1
a='Dogs are love"
^
SyntaxError: EOL while scanning string literal
>>> a="Dogs are "love""
File "<stdin>", line 1
a="Dogs are "love""
^
SyntaxError: invalid syntax
>>> a='Dogs are "love"'
>>> print(a)
Dogs are "love“
>>> a="Dogs are 'love'"
>>> print(a)
Dogs are 'love‘
>>> a="'Dogs' 'are' 'love'"
>>> print(a)
'Dogs' 'are' 'love'
27. Access Python String
>>> a="Welcome to Python"
>>> a
'Welcome to Python'
>>> a[1]
'e'
>>> a[3:7]
'come'
>>> a[:8]
'Welcome '
>>> a[8:]
'to Python'
>>> a[:]
'Welcome to Python'
>>> a[:-2]
'Welcome to Pyth'
>>> a[-2:]
'on'
>>> a[-5:-2]
'yth'
>>> a[-2:-2]
''
String Concatenation
>>> a='Welcome to Python'
>>> b=', its Easy !'
>>> a+b
'Welcome to Python, its Easy !‘
>>> a='10'
>>> a*2
'1010‘
>>> '10'+10
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not
"int") to str
Escape Sequences in Python
>>> print("hello Guysn Welcome to
Python")
hello Guys
Welcome to Python
>>> print("hello Guyst Welcome to
Python")
hello Guys Welcome to Python
>>> print("Kaushal's Day")
Kaushal's Day
>>> print("Kaushal"s Day")
Kaushal"s Day
28. String Functions
>>> a='Welcome to Python'
>>> len(a) len() :returns the length of a string
17
>>> str(25) str() : converts any data type into a string
'25‘
>>> a.lower() lower() : return the string in lowercase
'welcome to python'
>>> a.upper() upper() : return the string in uppercase
'WELCOME TO PYTHON‘
>>> ' Welcome '.strip() strip() : removes whitespaces from the beginning and end of the string.
'Welcome‘
>>> '123'.isdigit() isdigit() : Returns True if all characters in a string are digits.
True
>>> 'abc'.isalpha() isalpha() : Returns True if all characters in a string are characters from an alphabet.
True
>>> ' '.isspace() isspace() : Returns True if all characters in a string are spaces.
True
>>> ' r '.isspace()
False
>>> a.startswith('Welcome') startswith() : returns True is the string it is applied on begins with the string in the argument
True
>>> a.endswith('Python') endswith() : returns True if the string it is applied on ends with the string in the argument.
True
>>> a.find('Python') find() : it takes argument and searches for substring and return index of substring
11
29. String Functions
>>> a='Welcome to Python'
>>> a.replace('Python', 'Java') replace() :It takes two arguments. Replace 1st argument with 2nd one.
'Welcome to Java'
>>> a.split(' ') split() :string is split around every occurrence of the argument in the string.
['Welcome', 'to', 'Python']
>>> '*'.join(['Green', 'Blue','Red']) join() : It takes a list as an argument and joins the elements in the list
'Green*Blue*Red‘ using the string it is applied on.
30. A String Peculiarity
Strings show a special effect, which we will illustrate in the
following example. We will need the "is"-Operator. If both a
and b are strings, "a is b" checks if they have the same
identity, i.e., share the same memory location.
>>> a="Linux"
>>> b="Linux"
>>> a is b
True
>>> id(a)
17303648
>>> id(b)
17303648
>>> a==b
True
>>> a="Linu!x"
>>> b="Linu!x"
>>> a is b
False
>>> a==b
True
>>> id(a)
17303680
>>> id(b)
17303584
Escape Sequences in Strings
The backslash () character is used to escape characters, i.e., to
"escape" the special meaning, which this character would
otherwise have. Examples for such characters are newline,
backslash itself, or the quote character.
Escape Sequence Meaning Notes
newline Ignored
Backslash ()
' Single quote (')
" Double quote (")
a ASCII Bell (BEL)
b ASCII Backspace (BS)
f ASCII Formfeed (FF)
n ASCII Linefeed (LF)
N{name}
Character named name in the Unicode
database (Unicode only)
r ASCII Carriage Return (CR)
t ASCII Horizontal Tab (TAB)
uxxxx
Character with 16-bit hex value xxxx
(Unicode only)
Uxxxxxxxx
Character with 32-bit hex value xxxxxxxx
(Unicode only)
v ASCII Vertical Tab (VT)
ooo Character with octal value ooo
xhh Character with hex value hh
34. Python Relational Operator
>>> 3<4 #Less Than
True
>>> 4>3 #Greater Than
True
>>> 3<=5 #Less Than or Equal to
True
>>> 5==4 #Equal to
False
>>> 5>=4 #Greater than or Equal to
True
>>> 4!=5 #Not Equal to
True
36. Python Logical Operator
These are conjunctions that you can use to combine more than one condition.
We have three Python logical operator – and, or, and not that come under python operators.
and:
If the conditions on both the sides of the operator are true, then
the expression as a whole is true.
>>> a=7>7 and 2>-1
>>> print(a)
False
or:
The expression is false only if both the statements around the
operator are false. Otherwise, it is true.
>>> a=7>7 or 2>-1
>>> print(a)
True
not:
This inverts the Boolean value of an expression. It converts True to
False, and False to True.
>>> a=not(0)
>>> print(a)
True
37. Membership Python Operator
These operators test whether a value is a member of a sequence.
The sequence may be a list, a string, or a tuple.
We have two membership python operators- ‘in’ and ‘not in’.
a. In
This checks if a value is a member of a sequence.
>>> pets=['dog','cat','ferret']
>>> 'fox' in pets
False
b. not in
Unlike ‘in’, ‘not in’ checks if a value is not a member of a
sequence.
>>> 'pot' not in 'disappointment'
True
38. Python Identity Operator
These operators test if the two operands share an identity.
We have two identity operators- ‘is’ and ‘is not’.
a. is
If two operands have the same identity, it returns True. Otherwise, it returns False.
b. is not
2 is a number, and ‘2’ is a string. So, it returns a True to
that.
>>> '2' is "2"
True
>>> 2 is not '2'
True
>>> 2 is not 2
False
41. Functions
It is a collection of statements grouped under a name. You can use it whenever you want to execute all those statements
at a time.
Classes
Python is an object-oriented language. It supports classes and objects.
Modules
A Python module is a collection of related classes and functions.
Packages
Python package is a collection of related modules. You can either import a package or create your own.
Module
Function Function
Function
Function Classes
ClassesClasses
Packages
Module
Module
Module
Module
42. List
a list as a collection of values.
E.g. life = [‘love’, ‘wisdom’, ‘anxiety’]
Tuple
A tuple is like a list, but it is immutable (you cannot change its values).
E.g. pizza = (‘base’, ‘sauce’, ‘cheese’, ‘mushroom’)
Dictionary
A dictionary is a collection of key-value pairs.
Declare it using curly braces, and commas to separate key-value pairs.
Also, separate values from keys using a colon (:).
E.g. student = {‘Name’: ‘Abc’, ‘Age’: 21}
45. Python Lists
A list in Python is an ordered group of items or elements.
To create python list of items, you need to mention the items, separated by commas, in square brackets.
It's important to notice that these list elements don't have to be of the same type.
It can be an arbitrary mixture of elements like numbers, strings, other lists and so on.
The main properties of Python lists:
• They are ordered.
• The contain arbitrary objects
• Elements of a list can be accessed by an index
• They are arbitrarily nestable, i.e. they can contain other lists as sublists
• Variable size.
• They are mutable, i.e. the elements of a list can be changed.
>>> colors=['red','green','blue']
>>> colors
['red', 'green', 'blue']
>>> days=['Monday','Tuesday','Wednesday',4,5,6,7.0]
>>> days
['Monday', 'Tuesday', 'Wednesday', 4, 5, 6, 7.0]
>>> languages=[['English'],['Gujarati'],['Hindi'],'Romanian','Spanish']
>>> languages
[['English'], ['Gujarati'], ['Hindi'], 'Romanian', 'Spanish']
>>> languages=[('English','Albanian'),'Gujarati','Hindi','Romanian','Spanish']
>>> languages
[('English', 'Albanian'), 'Gujarati', 'Hindi', 'Romanian', 'Spanish']
46. Slicing a Python List
>>> a=['zero','one','two','three','four','five']
>>> a[2:5]
['two', 'three', 'four']
>>> a[:4]
['zero', 'one', 'two', 'three']
>>> a[3:]
['three', 'four', 'five']
>>> a[:]
['zero', 'one', 'two', 'three', 'four', 'five']
>>> a[:-2]
['zero', 'one', 'two', 'three']
>>> a[-1:-2] #[] This returns an empty Python list, because the start is ahead of the stop for the traversal.
[]
47. Reassigning a single element
>>> colors=['caramel','gold','silver','occur']
>>> colors[2]='metal'
>>> colors
['caramel', 'gold', 'metal', 'occur']
Reassigning few element
>>> colors=['caramel','gold','silver','occur']
>>> colors[2:3]=['bronze','silver','metal']
>>> colors
['caramel', 'gold', 'bronze', 'silver', 'metal', 'occur']
Deleting List or single/ few elements of list
>>> colors=['caramel','gold','silver','occur']
>>> del colors
>>> colors
NameError: name 'colors' is not defined
>>> colors=['caramel','gold','silver','occur']
>>> del colors[2]
>>> colors
['caramel', 'gold', 'occur']
>>> del colors[1:]
>>> colors
['caramel']
48. Multidimensional Lists
You can also put a list in a list. Let’s look at a multidimensional list.
>>> grocery_list=[['caramel','P&B','Jelly'],['onions','potatoes'],['flour','oil']]
>>> grocery_list
[['caramel', 'P&B', 'Jelly'], ['onions', 'potatoes'], ['flour', 'oil']]
>>> grocery_list[0][2]
'Jelly‘
>>> a=[[[1,2],[3,4],5],[6,7]]
>>> a[0][1][1]
4
Concatenation and Multiplication of Python List
>>> a,b=[3,1,2],[5,4,6]
>>> a+b
[3, 1, 2, 5, 4, 6]
>>> a=a*2
>>> a
[3, 1, 2, 3, 1, 2]
>>> a=[a]*2
>>> a
[[3, 1, 2], [3, 1, 2]]
49. Iterating on a list
>>> for i in [1,2,3,4,5,6]:
... if i%2==0:
... print(i, " is Even no.")
...
2 is Even no.
4 is Even no.
6 is Even no.
>>> even=[2*i for i in range(1,11)]
>>> even
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
>>> even=[2*i for i in range(1,11) if i%3==0]
>>> even
[6, 12, 18]
50. Built-in List Functions
>>> even=[6, 12, 18]
>>> len(even) len() :It calculates the length of the list.
3
>>> max(even) max() :It returns the item from the list with the highest value.
18
>>> max(['2',2,3])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '>' not supported between instances of 'int' and 'str'
>>> min(even) min() :It returns the item from the list with the Lowest value.
6
>>> sum(even) sum() :It returns the sum of all the elements in the list.
36
>>> a=[3,6,2,4]
>>> sorted(a) sorted() :It returns a sorted version of the list, but does not change the
original one.
[2, 3, 4, 6]
>>> sorted(['hello','hell','Hello'])
['Hello', 'hell', 'hello']
>>> list("Welcome") list() : It converts a different data type into a list.
['W', 'e', 'l', 'c', 'o', 'm', 'e']
>>> list(2) It can’t convert a single int into a list
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
51. Built-in List Functions
>>> a=['', '', '1']
>>> any(a) any() :It returns True if even one item in the Python list has a True value
True
>>> all(a) all() :It returns True if all items in the list have a True value
False
52. Built-in Methods
While a function is what you can apply on a construct and get a result, a method is what you can do to it and change
it.
53. >>> a.append(5) #append() :It adds an item to the end of the list.
>>> a
[3, 6, 2, 4, 5]
>>> a.insert(1,0) #insert(index, item) :It inserts an item at a specified position.
>>> a
[3, 0, 6, 2, 4, 5]
>>> a.remove(2) #remove() : It removes the first instance of an item from the Python list.
>>> a
[3, 0, 6, 4, 5]
>>> a.pop(2) #pop(element) : It removes the element at the specified index, and prints
6 it to the screen.
>>> a.clear() #clear() : It empties the Python list.
>>> a
[]
>>> a=[3,6,2,4]
>>> a.index(3) #index(Item) : It returns the first matching index of the item specified.
0
>>> a.count(6) # count(item) : It returns the count of the item specified.
1
>>> a.sort() # sort() : It sorts the list in an ascending order.
>>> a
[2, 3, 4, 6]
>>> a.reverse() # reverse() : It reverses the order of elements in the Python lists.
>>> a
[6, 4, 3, 2]
Built-in Methods
56. Python Tuple
Python Tuples are like a list. It can hold a sequence of items. The difference is that it is immutable.
To declare a Python tuple, you must type a list of items separated by commas, inside parentheses. Then assign it to a
variable.
>>> percentages=(1,2.0,'three')
You should use a tuple when you don’t want to change just an item in future.
The rules for indices are the same as for lists.
Once a tuple has been created, you can't add elements to a tuple or remove elements from a tuple.
The main advantage of tuples consists in the fact that tuples can be used as keys in dictionaries, while lists can't.
Creating Tuple with single Item
To create tuple with single item, use , at the end of the item.
>>> a=(1,)
>>> type(a)
<class 'tuple'>
>>> a=(1)
>>> type(a)
<class 'int'>
Deleting a Python Tuple
you can’t delete just a part of it. You must delete an entire tuple, if you may.
>>> a=(1,2,3,45,67)
>>> del a[2:4]
TypeError: 'tuple' object does not support item deletion
57. Reassigning Tuples in Python
let’s take a new tuple with a list as an item in it.
Now, let’s try changing the list [4,5]. Its index is 3.
>>> my_tuple=(1,2,3,[4,5])
>>> my_tuple[3]=6
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
Now how about changing an element from the same list.
This worked without a flaw. So we can see that while tuples are immutable, a mutable item that it holds may be reassigned.
>>> my_tuple[3][0]=6
>>> my_tuple
(1, 2, 3, [6, 5])
58.
59. >>> a=(1,2,3,4,5)
>>> len(a) #len() : Returns length of tuple
5
>>> max(a) #max() : It returns the item from the tuple with the highest value.
5
>>> min(a) #min() : It returns the item from the tuple with the Lowest value.
1
>>> sum(a) #sum() : It returns the arithmetic sum of all the items in the tuple.
15
>>> any(('','0','')) #any() : If even one item in the tuple has a Boolean value of True, then this function
True returns True. Otherwise, it returns False.
>>> all(('1',1,True,'')) #all() : returns True only if all items have a Boolean value of True. Otherwise, it
False returns False.
>>> a=(4,3,5,2,7,1)
>>> print(a, sorted(a, reverse=True)) #sorted() : It returns a sorted version of the tuple.
(4, 3, 5, 2, 7, 1) [7, 5, 4, 3, 2, 1]
>>> tuple([1,2,3]) #tuple() : It converts another construct into a Python tuple.
(1, 2, 3)
>>> tuple("Tuple")
('T', 'u', 'p', 'l', 'e')
>>> tuple({1,2,3})
(1, 2, 3)
Python Tuple Functions
60. Python Tuple Methods
>>> a=(1,2,3,2,4,5,2)
>>> a.index(3) #index() : This method takes one argument and returns the index of the first
2 appearance of an item in a tuple.
>>> a.count(2) #count() : This method takes one argument and returns the number of times an item
3 appears in the tuple.
Iterating on a Python Tuple
>>> for i in (1,2,3):
... print(i)
1
2
3
Nested Tuples
>>> a=((1,2,3),(4,(5,6)))
>>> a[1][1][1]
6
63. Python Dictionary
Python dictionary holds key-value pairs.
Creating a Python Dictionary is easy. Separate keys from values with a colon(:), and a pair from another by a
comma(,). Finally, put it all in curly braces.
To create an empty dictionary, simply use curly braces and then assign it to a variable.
You can also create a Python dict using comprehension.
It isn’t necessary to use the same kind of keys (or values) for a dictionary in Python.
Using the dict() function, you can convert a compatible combination of constructs into a Python dictionary.
>>> dict1={1:'Python', 2:'Java', 3:'.Net'}
>>> dict1
{1: 'Python', 2: 'Java', 3: '.Net'}
>>> dict2={}
>>> dict2
{}
>>> mydict={x*x:x for x in range(8)} #Dictionary Comprehension
>>> mydict
{0: 0, 1: 1, 4: 2, 9: 3, 16: 4, 25: 5, 36: 6, 49: 7}
>>> dict3={1:'carrots','two':[1,2,3]} #Different kind of keys (or values) for a dictionary
>>> dict3
{1: 'carrots', 'two': [1, 2, 3]}
>>> dict(([1,2],[2,4],[3,6])) #dict() function to convert other construct in Dictionary
{1: 2, 2: 4, 3: 6}
64. Declaring one key more than once
>>> mydict2={1:2,1:3,1:4,2:4}
>>> mydict2
{1: 4, 2: 4}
As you can see, 1:2 was replaced by 1:3, which was then replaced by 1:4. This shows us that a dictionary cannot
contain the same key twice.
Adding elements to Dictionary
When you don’t know what key-value pairs go in your Python dictionary, you can just create an empty Python
dict, and add pairs later.
>>> animals={}
>>> animals[1]='dog'
>>> animals[2]='cat'
>>> animals[3]='ferret'
>>> animals
{1: 'dog', 2: 'cat', 3: 'ferret'}
65. Accessing a value
To get a value from it, you need to put its key in square brackets.
The Python dictionary get() function takes a key as an argument and returns the corresponding value.
>>> mydict={0: 0, 1: 1, 4: 2, 9: 3, 16: 4, 25: 5, 36: 6, 49: 7}
>>> mydict[36]
6
>>> mydict.get(49)
7
>>> mydict.get(47)
>>> mydict[47]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 47
Updating the Value of an Existing Key and Adding a new key
If the key already exists in the Python dictionary, you can reassign its value using square brackets.
If the key doesn’t already exist in the dictionary, then it adds a new one.
>>> dict4={1:1,2:2,3:3}
>>> dict4[2]=4
>>> dict4
{1: 1, 2: 4, 3: 3}
>>> dict4[4]=6
>>> dict4
{1: 1, 2: 4, 3: 3, 4: 6}
66. Deleting Dictionary and its key: value pair
To delete the whole Python dict, simply use its name after the keyword ‘del’.
To delete just one key-value pair, use the keyword ‘del’ with the key of the pair to delete.
>>> dict4={1: 1, 2: 4, 3: 3, 4: 6}
>>> del dict4[4]
>>> dict4
{1: 1, 2: 4, 3: 3}
>>> del dict4
>>> dict4
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'dict4' is not defined
67. In-Built Functions on a Python Dictionary
>>> dict4={1:1,2:2,3:3}
>>> len(dict4) #len() : returns the length of the dictionary in Python
3
>>> any({False:False,'':''}) #any() : returns True if even one key in a dictionary has a Boolean value of True.
False
>>> any({True:False,"":""})
True
>>> all({1:2,2:'',"":3}) #all() : returns True only if all the keys in the dictionary have a Boolean value of True.
False
>>> sorted({3:3,1:1,4:4}) #sorted() : returns a sorted sequence of the keys in the dictionary.
[1, 3, 4]
68. In-Built Methods on a Python Dictionary
>>> dict1={1:'One', 2:'two', '3':3,(3,4):4,'r':234}
>>> dict1.keys() #keys() :returns a list of keys in a Python dictionary.
dict_keys([1, 2, '3', (3, 4), 'r'])
>>> dict1.values() #values() : returns a list of values in the dictionary.
dict_values(['One', 'two', 3, 4, 234])
>>> dict1.items() #items() : returns a list of key-value pairs.
dict_items([(1, 'One'), (2, 'two'), ('3', 3), ((3, 4), 4), ('r', 234)])
>>> dict1.get(2,9) #get() :It takes one to two arguments. While the first is the key to search for, the
'two‘ second is the value to return if the key isn’t found. The default value for this
second argument is None.
>>> dict1.get(5,9)
9
>>> newdict=dict1.copy() #copy() : Creates copy of current dictionary
>>> newdict
{1: 'One', 2: 'two', '3': 3, (3, 4): 4, 'r': 234}
>>> dict1.pop((3,4)) #pop() : This method is used to remove and display an item from the dictionary. It takes
4 one to two arguments. The first is the key to be deleted, while the second is the value
that’s returned if the key isn’t found.
unlike the get() method, this has no default None value for the second parameter.
>>> dict1
{1: 'One', 2: 'two', '3': 3, 'r': 234}
>>> dict1.pop(5)
KeyError: 5
69. In-Built Methods on a Python Dictionary
>>> dict1={1:'One', 2:'two', '3':3, (3,4):4, 'r':234}
>>> dict1.popitem()
('r', 234)
>>> dict1.popitem()
((3, 4), 4)
>>> dict1
{1: 'One', 2: 'two', '3': 3}
Nested Dictionary
You can also place a Python dictionary as a value within a dictionary.
you can’t place it as a key, because that throws an error.
>>> dict1={4:{1:2,2:4},8:16}
>>> dict1
{4: {1: 2, 2: 4}, 8: 16}
>>> dict1[4]
{1: 2, 2: 4}
>>> dict1={{1:2,2:4}:8,8:16}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'
72. Functions in Python
Python lets us group a sequence of statements into a single entity, called a function.
A Python function may or may not have a name.
User-Defined Functions in Python
To define your own Python function, you use the ‘def’ keyword before its name. And its name is to be followed by
parentheses, before a colon(:).
The contents inside the body of the function must be equally indented.
You can access this docstring using the __doc__ attribute of the function.
If you don’t yet know what to put in the function, then you should put the pass statement in its body.
If you leave its body empty, you get an error “Expected an indented block”.
User can Delete function by del keyword. When deleting a function, you don’t need to put parentheses after its name.
>>> def hello():
"""
This Python function simply prints hello to the screen
""“
print("Hello")
>>> del hello
73. Python Function Parameters
Function can take any number of parameters and produce a result.
A function in Python may contain any number of parameters, or none.
you can’t add incompatible types.
A variable that’s declared inside python function is destroyed after the function stops executing.
>>> def sum(a, b): #Function Definition
... print(f"{a}+{b}={a+b}")
>>> sum(5,3) #Call to Function sum(x, y)
5+3=8
Python return statement
A Python function may optionally return a value. This value can be a result that it produced on its execution. Or it can be
something you specify- an expression or a value.
As soon as a return statement is reached in a function, the function stops executing. Then, the next statement after the
function call is executed.
>>> def sum(a,b):
... return a+b
>>> sum(4,3)
7
>>> a=sum(5,5)
>>> a
10
75. Default Argument in Python
Python Program arguments can have default values.
We assign a default value to an argument using the assignment operator in python(=).
When we call a function without a value for an argument, its default value (as ‘User’ in below example) is used.
>>> def greeting(name='User'):
... print(f" Hello, {name}")
>>> greeting('Vimal')
Hello, Vimal
>>> greeting() #Returns Default Value as ‘User’
Hello, User
Python Keyword Arguments
With keyword arguments in python, we can change the order of passing the arguments without any
consequences.
But if you try to put a positional argument after a keyword argument, it will throw Python exception of
SyntaxError.
>>> def divide(a,b):
... return a/b
>>> divide(a=3, b=2) # result=1.5
>>> divide(b=2, a=3) # result=1.5
>>> divide(4,2) # result=2.0
>>> divide(a=3, 2) # SyntaxError: positional argument follows keyword argument
76. Python Arbitrary Arguments
You may not always know how many arguments you’ll get. In that case, you use an asterisk(*) before an argument
name.
And then when you call the function with a number of arguments, they get wrapped into a Python tuple. We iterate over
them using the for loop in python.
>>> def greeting(*names): #*names treated as tuple
... for name in names:
... print("Hello ", name)
...
>>> greeting('Mahesh', 'Kaushal', 'Vimal',)
Hello Mahesh
Hello Kaushal
Hello Vimal
def print_params(**params): # **params treated as dictionary
x=params
print(x.keys(), type(x))
print_params(x=2, y=3, z=5, s=4)
dict_keys(['x', 'y', 'z', 's']) <class 'dict'>
77. Python Lambda Expressions
A lambda expression in Python allows us to create anonymous python function, and we use the ‘lambda’ keyword
for it.
The following is the syntax for a lambda expression.
lambda arguments : expression
It’s worth noting that it can have any number of arguments, but only one expression. It evaluates the value of that
expression, and returns the result.
>>> myvar= lambda a, b : ( a * b ) + 2
>>> myvar(3,5)
17
Python Recursion Function
In Python function, recursion is when a function calls itself.
def fact(n):
if n==1:
return n
return n* fact(n-1)
print(fact(5))
120
78. range() function
1. One Parameter
Syntax is range(stop)
For an argument n, the function returns integer values from 0 to n-1.
2. Two Parameters
Syntax is range(start,stop)
it prints integers from the first number to one from the second.
3. Three Parameters
Syntax is range(start,stop,interval)
>>> list(range(5)) #one parameter range() function
[0, 1, 2, 3, 4]
>>> list(range(1,4)) # two parameter range() function
[1, 2, 3]
>>> list(range(7,1))
[]
>>> list(range(-7,1))
[-7, -6, -5, -4, -3, -2, -1, 0]
>>> list(range(5))
[0, 1, 2, 3, 4]
>>> list(range(1,5))
[1, 2, 3, 4]
>>> list(range(5,1))
[]
>>> list(range(1,8,2)) #three parameter range() function
[1, 3, 5, 7]
>>> list(range(-8,8,2))
[-8, -6, -4, -2, 0, 2, 4, 6]
79. zip() is a built-in Python function that gives us an iterator of tuples.
Like a .zip file holds real files within itself, a zip holds real data within.
It takes iterable(list, String, dict) elements as input and returns an iterator on them (an iterator of tuples).
It evaluates the iterables left to right.
Python zip() function has the following syntax-
zip(*iterables)
zip() function
>>> for i in zip([1,2,3],['a','b','c']): #Multiple arguments of the same lengths
... print(i)
(1, 'a')
(2, 'b')
(3, 'c')
>>> for i in zip([1,2,3]): #Single argument
... print(i)
(1,)
(2,)
(3,)
>>> for i in zip([1,2,3],['a','b','c'],['#','*','$']):
... print(i)
(1, 'a', '#')
(2, 'b', '*')
(3, 'c', '$')
>>> set(zip([1,2],[3,4,5])) #Multiple arguments of different lengths
{(1, 3), (2, 4)}
>>> from itertools import zip_longest as zl
>>> set(zl([1,2],[3,4,5]))
{(1, 3), (2, 4), (None, 5)}
80. Unzipping Values in Python
we use the * character with the zip() function. This unzips the zip object into the variables.
>>> z=zip([1,2,3],['a','b','c'],['#','*','$'])
>>> a,b,c=zip(*z)
>>> a,b,c
((1, 2, 3), ('a', 'b', 'c'), ('#', '*', '$'))
82. eval Function
eval() in Python is a built-in function or method, to which we pass an expression.
It parses this expression and runs it as we execute the program.
syntax for eval function in Python:
eval(expression, globals=None, locals=None)
Expression :This is the string to parse and evaluate.
Globals : This is a dictionary that holds available global methods and variables, and is an optional parameter
Locals : This is a mapping object that holds available local methods and variables, and is an optional
parameter.
eval() in Python does not compile, only evaluates
>>> x=7
>>> eval('x**2') 49
>>> eval('[2,3,4][1]') 3
>>> eval('if 3>1: print("Okay")') #SyntaxError: invalid syntax
>>> expr=input('Enter an expression as x')
Enter an expression as x x*2+(2+3)/2
>>> x=int(input('Enter the value of x'))
Enter the value of x 3
>>> eval(expr)
8.5
83. Exploiting Eval in Python and protection from it
>>> def let_me_in():
... password='@dc#431'
... print("The password is",password)
>>> expr=input('Enter an expression as x')
Enter an expression as x let_me_in()
>>> eval(expr) #A user can make a call to this function through Python eval()
The password is @dc#431
it is possible to pass a list of functions and variables to eval. This means it can access only these functions and
variables. We pass this as a Python eval dictionary.
>>> expr=input('Enter an expression as x')
Enter an expression as x 2
>>> safe_dict={}
>>> safe_dict['x']=x # {‘x’:2}
>>> expr=input('Enter an expression as x')
Enter an expression as x let_me_in()
>>> eval(expr, safe_dict) # expr=2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'let_me_in' is not defined
85. Python exec()
exec() is a built-in function/ method with Python
We use exec() to dynamically execute Python code- this can be a string or some object code.
When it is a string, Python parses it as a set of statements and executes it if there is no syntax error.
When it is object code, Python executes it. But exec() doesn’t return a value; it returns None.
Hence, we cannot use return and yield statements outside function definitions.
Syntax for exec() is
exec(source, globals=None, locals=None, /)
The source may be a string representing one or more Python statements
The globals must be a dictionary and
locals can be any mapping, defaulting to the current globals and locals.
>>> code='a=7nprint("a*17=",a*17)'
>>> exec(code)
a*17= 119
>>> code='a=7nif a==7:print("a*17=",a*17)‘ #String
>>> exec(code)
a*17= 119
>>> code=input('What would you like to do today?')
What would you like to do today?[print(x**2) for x in range(4)] #List Obj
>>> exec(code)
0
1
4
9
86. Python exec vs eval
If we try doing this to create a list with Python exec() , nothing happens! We must use Python eval instead:
>>> exec('[(x**2) for x in range(7)]')
>>> eval('[(x**2) for x in range(7)]')
[0, 1, 4, 9, 16, 25, 36]
Problem in Python exec
If we give liberty to user to execute any type of code, then user can misuse it i.e. user can
delete or corrupt files or directories.
Using the global and locals parameters, we can restrict what variables and methods users can access. We can
either provide both, or just the global, in which case that value suffices for both- global and locals.
>>> a=7
>>> def hello(): print("Hello")
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'a', 'hello']
>>> from math import tan
>>> exec('print(tan(90))')
-1.995200412208242
>>> exec('print(tan(90))', {})
NameError: name 'tan' is not defined
>>> exec('print(tan(90))', {'tan':tan})
-1.995200412208242
88. repr Function
This is a built-in function
This takes an object
repr() returns a string that holds a printable representation of an object.
It has the following syntax:
repr(obj, /)
It is true for many object types and most builtins that
eval(repr(obj))=obj
>>> s=[1,2,3]
>>> repr(s)
'[1, 2, 3]'
>>> eval(repr(s))
[1, 2, 3]
>>> s=[1,2,3][2]
>>> eval(repr(s))
3
>>> repr(s)
'3‘
>>> x='Hello'
>>> eval(repr(x))
'Hello'
>>> repr(x)
"'Hello'"
91. While Loop
A while loop in python iterates till its condition becomes False.
In other words, it executes the statements under itself while the condition it takes is
True.
>>> a=3
>>> while (a>0):
... print(a)
... a-=1
...
3
2
1
92.
93. An Infinite Loop
If you forget to increment the counter variable in python, or write flawed logic, the condition may never become
false. In such a case, the loop will run infinitely, and the conditions after the loop will starve.
To stop execution, press Ctrl+C.
>>> x=5
>>> while x>0:
... print(x)
else statement for while loop
When the condition becomes false, the block under the else statement is executed. However, it doesn’t execute if
you break out of the loop or if an exception is raised.
x=4
while x>0:
print(x)
x-=1
else:
print("Condition False")
Result :
4
3
2
1
Condition False
x=4
while x>0:
print(x)
x-=1
if x==2:
break
else:
print("Condition False")
Result :
4
3
break statement Single statement while
a=3
while a>0: print(a); a-=1;
Result :
3
2
1
94. For Loop
Python for loop can iterate over a sequence of items.
The structure of a for loop in Python is different than that in C++ or Java.
That is, for(int i=0;i<n;i++) won’t work here.
In Python, we use the ‘in’ keyword. Lets see a Python for loop Example
for i in range(3):
print(i)
Result :
0
1
2
for i in {2,3,3,4}: #iterating over set
print(i)
Result :
2
3
4
95. The else statement for for-loop
Like a while loop, a for-loop may also have
an else statement after it.
When the loop is exhausted, the block
under the else statement executes.
for i in range(3):
print(i)
else:
print("reach else")
Result :
0
1
2
reach else
Nested for Loops Python
You can also nest a loop inside another. You can put a
for loop inside a while, or a while inside a for, or a for
inside a for, or a while inside a while.
Or you can put a loop inside a loop inside a loop.
for i in range(1,6):
for j in range(i):
print("*",end=' ')
print()
i=6
while(i>0):
j=6
while(j>i):
print("*",end=' ')
j-=1
i-=1
print()
*
* *
* * *
* * * *
* * * * *
96.
97. break statement
When you put a break statement in the body of a loop, the loop stops executing, and control shifts to the first
statement outside it. You can put it in a for or while loop.
continue statement
When the program control reaches the continue statement, it skips the statements after ‘continue’.
It then shifts to the next item in the sequence and executes the block of code for it.
pass statement
When we need a particular loop, class, or function in our program, but don’t know what goes in it, we place the
pass statement in it.
It is a null statement. The interpreter does not ignore it, but it performs a no-operation (NOP).
for i in range(6):
if i==3:
continue #skip statement and shift to next level i.e. x=4
elif i==4:
pass #Interpreter ignore statement
elif i==5:
break #loop stop executing
print(i)
0
1
2
4
98.
99. Unlike other languages like Java and C++, Python does not have a switch-case construct.
to get around this, we use Python’s built-in dictionary construct to implement cases and decided what to do when a
case is met.
To get around this, we use Python’s built-in dictionary construct to implement cases and decided what to do when
a case is met.
Switch Case Statement
def week(i):
switcher = {
0: 'Sunday',
1: 'Monday',
2: 'Tuesday',
3: 'Wednesday',
4: 'Thursday',
5: 'Friday',
6: 'Saturday'
}
return switcher.get(i, "Invalid day of week")
print(week(2)) #Tuesday
Print(week(8)) # Invalid day of week
def zero():
return 'zero'
def one():
return 'one'
def indirect(i):
switcher = {
0: zero,
1: one,
2: lambda: 'two'
}
func = switcher.get(i, lambda: 'Invalid')
return func()
print(indirect(4)) #Invalid
print(indirect(2)) #two
print(indirect(0)) #zero
100.
101.
102. Python Class
A class is a blueprint for objects.
To define a class in python programming, we use the ‘class’ keyword.
This is followed by an indented block of statements which form the body of the class.
we create an object/instance of this class using the name of the class followed by a pair of parentheses.
The __init__ method is similar to constructors in C++ and Java. It is run as soon as an object of a class is
instantiated.
However, you don’t need to define this function if you don’t need it in your code.
The method is useful to do any initialization you want to do with your object.
# A Sample class with init method
class Person:
# init method or constructor
def __init__(self, name):
self.name = name
# Sample Method
def say_hi(self):
print('Hello, my name is', self.name)
p = Person('Shiv')
p.say_hi()
103. magic methods or Dunder in Python
Dunder or magic methods in Python are the methods having two prefix and suffix underscores in the method name.
Dunder here means “Double Under (Underscores)”.
These are commonly used for operator overloading.
Few examples for magic methods are: __init__, __add__, __len__, __repr__ etc.
The __init__ method for initialization is invoked without any call, when an instance of a class is created,
like constructors in certain other programming languages such as C++, Java, C#, PHP etc.
Magic methods are not meant to be invoked directly by user, but the invocation happens internally from the class
on a certain action.
For example, when you add two numbers using the + operator, internally, the __add__()method will be called.
Use the dir() function to see the number of magic methods inherited by a class. E.g. Print(dir(int)).
Magic methods are most frequently used to define overloaded behaviours of predefined operators in Python.
he + operator is also defined as a concatenation operator in string, list and tuple classes. We can say that the +
operator is overloaded.
In order to make the overloaded behaviour available in your own custom class, the corresponding magic method
should be overridden.
For example, in order to use the + operator with objects of a user-defined class, it should include the __add__()
method.
num=10
print(num+5) #15
print(num.__add__(5)) #15
num='10'
print(num+'5') #105
print(num.__add__('5')) #105
104. __new__() method
Languages such as Java and C# use the new operator to create a new instance of a class.
In Python the __new__() magic method is implicitly called before the __init__() method.
The __new__() method returns a new object, which is then initialized by __init__().
class employee:
def __new__(cls):
print("__new__ magic method is called")
inst = object.__new__(cls)
return inst
def __init__(self):
print("__init__ magic method is called")
self.name = 'Satya'
e1=employee()
__new__ magic method is called
__init__ magic method is called
105. class employee:
def __init__(self):
self.name = 'Swati'
self.salary = 10000
def __str__(self): # Method Overloading
return 'name=' + self.name + ' salary=$' + str(self.salary)
e1=employee()
print(e1) #name=Swati salary=$10000
print(e1.__str__()) #name=Swati salary=$10000
__str__() method
Another useful magic method is __str__().
It is overridden to return a printable string representation of any user defined class.
We have seen str() built-in function which returns a string from the object parameter.
For example, str(12)returns '12'. When invoked, it calls the __str__() method in the int class.
Let us now override the __str__() method in the employee class to return a string representation of its object.
num=12
print(str(num)) #12
print(num.__str__()) #12
106. The self
Class methods must have an extra first parameter(self) in method definition.
We do not give a value for this parameter when we call the method, Python provides it
If we have a method which takes no arguments, then we still have to have one argument – the self.
This is similar to this pointer in C++ and this reference in Java.
class Test:
def fun(self):
print("Welcome to Python")
def fun1(self, greeting):
self.greeting=greeting
print(self.greeting)
obj1 = Test() #Object Creation
obj2 = Test()
obj2.fun() #Function Call
obj1.fun1("hi, Team") #Function call with parameter
Welcome to Python
hi, Team
When we call a method of this object as obj.fun1(arg1),
this is automatically converted by Python into Test.fun1(obj, arg1) – this is all the
special self is about.
107. Class and Instance Variables (Or attributes)
In Python, instance variables are variables whose value is assigned inside a constructor or method with self.
Class variables are variables whose value is assigned in class.
# Class for Computer Science Student
class CSStudent:
stream = 'cse‘ # Class Variable
def __init__(self, roll): # The init method or constructor
self.roll = roll # Instance Variable
a = CSStudent(101) # Objects of CSStudent class
b = CSStudent(102)
print(a.stream) # "cse"
print(b.stream) # "cse"
print(a.roll) # 101
# Class variables can be accessed using class -name also
print(CSStudent.stream) # prints "cse"
108. Inheritance in Python
One of the major advantages of Object Oriented Programming is re-use.
Inheritance is one of the mechanisms to achieve the same.
In inheritance, a class (usually called superclass) is inherited by another class (usually called subclass).
The subclass adds some attributes to superclass.
class Person(object):
def __init__(self, name): # Constructor
self.name = name
def getName(self): # To get name
return self.name
def isEmployee(self): # To check if this person is employee
return False
# Inherited or Sub class (Note Person in bracket)
class Employee(Person):
def isEmployee(self): # Here we return true
return True
emp = Person("Geek1") # An Object of Person
print(emp.getName(), emp.isEmployee()) #Geek1 False
emp = Employee("Geek2") # An Object of Employee
print(emp.getName(), emp.isEmployee()) #Geek2 True
print(issubclass(Employee,Person)) #True
109. Constructors in Python
Constructors are generally used for instantiating an object.
The task of constructors is to initialize(assign values) to the data members of the class when an object of class is created.
In Python the __init__() method is called the constructor and is always called when an object is created.
Syntax is as follow:
def __init__(self):
# body of the constructor
Types of constructors :
default constructor :
The default constructor is simple constructor which doesn’t accept any arguments.
It’s definition has only one argument which is a reference(self) to the instance being constructed.
parameterized constructor :
constructor with parameters is known as parameterized constructor.
The parameterized constructor take its first argument as a reference(self) to the instance being constructed known as self and
the rest of the arguments are provided by the programmer.
110. write both a parameterized and default constructor in a single Python class
Both cannot be done within a same class.
However, you can define one constructor with default values! When no values are passed, ( default constructor is
invoked) or
even a constructor with few of the defined parameters passed) the default values for all or rest of the parameters
would be used to initialize the class members.
class employee:
def __init__(self, name='Kaushal'):
self.name = name
print(name)
e1=employee("Vimal") #Vimal
e1=employee() #Kaushal
111. class Base1(object): # Superclass1
def __init__(self):
self.str1 = "Geek1"
print("Base1")
class Base2(object): #Superclass2
def __init__(self):
self.str2 = "Geek2"
print("Base2")
class Derived(Base1, Base2): #Subclass
def __init__(self):
Base1.__init__(self) #Calling constructors of Base1
Base2.__init__(self) #Calling constructors of Base2
print("Derived")
def printStrs(self):
print(self.str1, self.str2)
obj = Derived() #Obj creation for subclass
print(obj.printStrs()) # Base1 Base2 Derived Geek1 Geek2 None
Mutiple Inheritance in Python
Unlike Java and like C++, Python supports multiple inheritance.
We specify all parent classes as comma separated list in bracket.
112. access parent members in a subclass
Superclass members can be accessed in subclass using superclass name.
We can also access parent class members using super.
class Base(object):
def __init__(self, x): # Constructor of superclass
self.x = x
class Derived(Base):
def __init__(self, x, y): # Constructor of subclass
Base.x = x
self.y = y
def printXY(self):
print(Base.x, self.y)
d = Derived(10, 20)
d.printXY()
10 20
class Base(object):
def __init__(self, x): # Constructor of superclass
self.x = x
class Derived(Base):
def __init__(self, x, y): # Constructor of subclass
super(Derived, self).__init__(x)
self.y = y
def printXY(self):
print(self.x, self.y)
d = Derived(10, 20)
d.printXY()
10 20
113. multilevel inheritance with super()
Python Super function provides us the flexibility to do single level or multilevel inheritances.
The super() function has a property that it always refers the immediate superclass.
Also, super() function is not only referring the __init__() but it can also call the other functions of the superclass when it needs.
class GFG1:
def __init__(self):
print('HEY !!!!!! GfG I am initialised(Class GFG1)')
def sub_GFG(self, b):
print('Printing from class GFG1:', b)
class GFG2(GFG1): # class GFG2 inherits the GFG1
def __init__(self):
print('HEY !!!!!! GfG I am initialised(Class GFG2)')
super().__init__()
def sub_GFG(self, b):
print('Printing from class GFG2:', b)
super().sub_GFG(b + 1)
class GFG3(GFG2): # class GFG3 inherits the GFG1 ang GFG2 both
def __init__(self):
print('HEY !!!!!! GfG I am initialised(Class GFG3)')
super().__init__()
def sub_GFG(self, b):
print('Printing from class GFG3:', b)
super().sub_GFG(b + 1)
gfg = GFG3()
gfg.sub_GFG(10)
HEY !!!!!! GfG I am initialised(Class GFG3)
HEY !!!!!! GfG I am initialised(Class GFG2)
HEY !!!!!! GfG I am initialised(Class GFG1)
Printing from class GFG3: 10
Printing from class GFG2: 11
Printing from class GFG1: 12
114. Polymorphism in Python
The word polymorphism means having many forms.
In programming, polymorphism means same function name (but different signatures) being uses for different types.
# in-built poly- morphic functions
print(len("geeks")) # len() being used for a string 5
print(len([10, 20, 30])) # len() being used for a list 3
# A simple Python function to demonstrate Polymorphism
def add(x, y, z = 0):
return x + y+z
print(add(2, 3)) #5
print(add(2, 3, 4)) #9
115. Polymorphism with class methods
Below code shows how python can use two different class types, in the same way.
We create a for loop that iterates through a tuple of objects. Then call the methods without being concerned about which class
type each object is. We assume that these methods actually exist in each class.
class India:
def capital(self):
print("New Delhi is the capital of India.")
def language(self):
print("Hindi the primary language of India.")
def type(self):
print("India is a developing country.")
class USA:
def capital(self):
print("Washington, D.C. is the capital of USA.")
def language(self):
print("English is the primary language of USA.")
def type(self):
print("USA is a developed country.")
obj_ind = India()
obj_usa = USA()
for country in (obj_ind, obj_usa):
country.capital()
country.language()
country.type()
New Delhi is the capital of India.
Hindi the primary language of India.
India is a developing country.
Washington, D.C. is the capital of
USA.
English is the primary language of
USA.
USA is a developed country.
#Polymorphism with a Function and objects
class India:
def capital(self):
print("New Delhi is the capital of India.")
def language(self):
print("Hindi the primary language of India.")
def type(self):
print("India is a developing country.")
class USA:
def capital(self):
print("Washington, D.C. is the capital of USA.")
def language(self):
print("English is the primary language of USA.")
def type(self):
print("USA is a developed country.")
def func(obj):
obj.capital()
obj.language()
obj.type()
obj_ind = India()
obj_usa = USA()
func(obj_ind)
func(obj_usa)
Notas do Editor
Use of Python
Python Applications
JAVA vs PYTHON
Multiple Statements in one line
Int
Python can hols sign as well un-sign integers.
It can hold a value of any length, the only limitation being the amount of memory available.
VARIABLES IN PYTHON
PYTHON STRING
Python String
A Python string is a sequence of characters. There is a built-in class ‘str’ for handling Python string. You can prove this with the type() function.
PYTHON OPERATORS
PYTHON DATA CONSTRUCTS
Functions
is a collection of statements grouped under a name. You can use it whenever you want to execute all those statements at a time.
Classes
Python is an object-oriented language. It supports classes and objects.
Modules
A Python module is a collection of related classes and functions.
Packages
Python package is a collection of related modules. You can either import a package or create your own.