Module 1
Module 1
Python is a popular programming language. It was created by Guido van Rossum, and
released in 1991.
It is used for:
Why Python?
• Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
• Python has a simple syntax similar to the English language.
• Python has syntax that allows developers to write programs with fewer lines than
some other programming languages.
• Python runs on an interpreter system, meaning that code can be executed as soon
as it is written. This means that prototyping can be very quick.
• Python can be treated in a procedural way, an object-oriented way or a functional
way.
Application of python
• Highly Dynamic. Web Development. Python can be used to make web-applications at a
rapid rate. ...
• Game Development. Python is also used in the development of interactive games. ...
• Machine Learning and Artificial Intelligence. ...
• Data Science and Data Visualization. ...
• Desktop GUI. ...
• Web Scraping Applications. ...
• Business Applications. ...
• CAD Applications.
Spotify
Dropbox
Uber
Top Python Libraries List
Pandas
NumPy
Keras
TensorFlow
SciPy
PyTorch
LightGBM
Syntax in python
print("Hello, World!") Output: Hello world
Creating an Object
class Cars:
def __init__(self, m, p):
self.model = m
self.price = p
Audi = Cars("R8", 100000)
print(Audi.model)
print(Audi.price)
Output:
R8
100000
Data type
Data types are the classification or categorization of data items. It represents the kind of
value that tells what operations can be performed on a particular data. Since everything
is an object in Python programming, data types are actually classes and variables are
instance (object) of these classes.
Following are the standard or built-in data type of Python:
• Numeric
• Sequence Type
• Boolean
• Set
• Tuple
• Dictionary
Variables can store data of different types, and different types can do different things.
Python has the following data types built-in by default, in these categories:
Example
Print the data type of the variable x:
x=5
print(type(x))
Internal Types
• Code.
• Frame.
• Traceback.
• Slice.
• Ellipsis.
• Xrange.
Code Objects:
Code objects are executable pieces of Python source that are byte-compiled.
Frame Objects
These are objects representing execution stack frames in Python. Frame objects contain all the
information the Python interpreter needs to know during a runtime execution environment.
Traceback Objects
When you make an error in Python, an exception is raised. If exceptions are not caught or "handled,"
the interpreter exits with some diagnostic information similar to the output shown below:
Slice Objects
Slice objects are created using the Python extended slice syntax. This extended syntax allows for
different types of indexing. Slice objects can also be generated by the slice () BIF.
Ellipsis Objects
Ellipsis objects are used in extended slice notations as demonstrated above. These objects are used
to represent the actual ellipses in the slice syntax (...). Like the Null object None, ellipsis objects also
have a single name, Ellipsis, and have a Boolean True value at all times.
XRange Objects
XRange objects are created by the BIF xrange(), a sibling of the range() BIF, and used when
memory is limited and when range() generates an unusually large data set. You can find out more
about range() and xrange().
Python Operators ?
An operator is a symbol that will perform mathematical operations on variables or
on values. Operators operate on operands (values) and return a result.
Python has 7 types of operators that you can use:
•Arithmetic Operators
•Relational Operators
• Assignment Operators
• Logical Operators
• Membership Operators
• Identity Operators
• Bitwise Operators
Let’s take an example:
2+3
Here, + is an operator for addition. It adds 2 and 3 and prints 5 in the interpreter. This
is an arithmetic operator.
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.
Arithmetic operators
Arithmetic operators are used to perform mathematical operations like addition,
subtraction, multiplication, etc.
/ Divide left operand by the right one (always results into float) x/y
x % y (remainder of
% Modulus - remainder of the division of left operand by the right
x/y)
Floor division - division that results into whole number adjusted to the
// x // y
left in the number line
# 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)
Run Code
Output
x + y = 19
x - y = 11
x * y = 60
x / y = 3.75
x // y = 3
x ** y = 50625
Comparison operators
> 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
>= Greater than or equal to - True if left operand is greater than or equal to the right x >= y
<= Less than or equal to - True if left operand is less than or equal to the right x <= y
# Output: x == y is False
print('x == y is',x==y)
# Output: x != y is True
print('x != y is',x!=y)
Output
x > y is False
x < y is True
x == y is False
x != y is True
x >= y is False
x <= y is True
Logical operators
Logical operators are the and , or , not operators.
Operator Meaning Example
print('x or y is',x or y)
print('not x is',not x)
Run Code
Output
x and y is False
x or y is True
not x is False
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)
Operator Meaning Example
Assignment operators
Assignment operators are used in Python to assign values to variables.
a = 5 is a simple assignment operator that assigns the value 5 on the right to the
variable a on the left.
There are various compound operators in Python like a += 5 that adds to the variable
and later assigns the same. It is equivalent to a = a + 5.
= 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
Special operators
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.
Operator Meaning Example
is True if the operands are identical (refer to the same object) x is True
is not True if the operands are not identical (do not refer to the same object) x is not True
# Output: False
print(x1 is not y1)
# Output: True
print(x2 is y2)
# Output: False
print(x3 is y3)
Run Code
Output
False
True
False
Here, we see that x1 and y1 are integers of the same values, so they are equal as well
as identical. Same is the case with x2 and y2 (strings).
But x3 and y3 are lists. They are equal but not identical. It is because the interpreter
locates them separately in memory although they are equal.
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.
# Output: True
print('H' in x)
# Output: True
print('hello' not in x)
# Output: True
print(1 in y)
# Output: False
print('a' in y)
Run Code
Output
True
True
True
False
Here, 'H' is in x but 'hello' is not present in x (remember, Python is case sensitive).
Similarly, 1 is key and 'a' is the value in dictionary y . Hence, 'a' in y returns False .
cmp ()
The cmp() built-in function Compares two objects, say, obj1 ...
If we were to be maximally verbose in describing the standard types, we would probably call them
something like Python's "basic built-in data object primitive types."
o "Basic," indicating that these are the standard or core types that Python provides
o "Built-in," due to the fact that these types come by default in Python
o "Data," because they are used for general data storage
o "Object," because objects are the default abstraction for data and functionality
o "Primitive," because these types provide the lowest-level granularity of data storage
o "Types," because that's what they are: data types!
Python Numbers
Number data types store numeric values. They are immutable data types, which means that
changing the value of a number data type results in a newly allocated object.
Different types of Number data types are :
• int
• float
• complex
Let’s see each one of them:
Int type
int (Integers) are the whole number, including negative numbers but not fractions. In Python,
there is no limit to how long an integer value can be.
Example 1: Creating int and checking type
• Python3
num = -8
print(type(num))
Output:
<class 'int'>
Float type
This is a real number with floating-point representation. It is specified by a decimal point.
Optionally, the character e or E followed by a positive or negative integer may be appended
to specify scientific notation. . Some examples of numbers that are represented as floats
are 0.5 and -7.823457.
They can be created directly by entering a number with a decimal point, or by using
operations such as division on integers. Extra zeros present at the number’s end are
ignored automatically.
Example 1: Creating float and checking type
• Python3
num = 3/4
print(type(num))
Output:
<class 'float'>
Complex type
A complex number is a number that consists of the real and imaginary parts. For example,
2 + 3j is a complex number where 2 is the real component, and 3 multiplied by j is an
imaginary part.
Example 1: Creating Complex and checking type
• Python3
num = 6 + 9j
print(type(num))
Output:
<class 'complex'>
• print( ) function
• type( ) function
• input( ) function
• abs( ) function
• pow( ) function
• dir( ) function
• sorted( ) function
• max( ) function
• round( ) function
• divmod( ) function
• id( ) function
• ord( ) function
• len( ) function
• sum( ) function
• help( ) function
print( ) function
The print() function prints the specified message to the screen or another standard
output device.
The message that wants to print can be a string or any other object. This function
converts the object into a string before written to the screen.
Output:
Analytics Vidhya is the Largest Data Science Community over whole world
Example 2: Print more than one object onto the screen:
Output:
type( ) function
The type() function returns the type of the specified object.
Output:
<class 'tuple'>
Output:
<class 'str'>
<class 'int'>
input( ) function
The input() function allows taking the input from the user.
Example: Use the prompt parameter to write the complete message after giving the
input:
Output:
abs( ) function
The abs() function returns the absolute value of the specified number.
negative_number = -676
print(abs(negative_number))
Output:
676
complex_number = 3+5j
print(abs(complex_number))
Output:
5.830951894845301
x = pow(3, 4)
print(x)
Output:
81
x = pow(3, 4, 5)
print(x)
Output:
dir( ) function
The dir() function returns all the properties and methods of the specified object, without
the values.
This function even returns built-in properties which are the default for all objects.
class Person:
name = "Chirag Goyal"
age = 19
country = "India"
education = "IIT Jodhpur"
print(dir(Person))
Output:
sorted( ) function
The sorted() function returns a sorted list of the specified iterable object.
You can specify the order to be either ascending or descending. In this function, Strings
are sorted alphabetically, and numbers are sorted numerically.
NOTE: If a list contains BOTH string values AND numeric values, then we cannot sort it.
Output:
Output:
['h', 'g', 'f', 'e', 'd', 'c', 'b', 'a']
max( ) function
The max() function returns the item with the maximum value or the item with the
maximum value in an iterable.
If the values this function takes are strings, then it is done using an alphabetical
comparison.
Example 1: Return the name with the highest value, ordered alphabetically:
Output:
Kshitiz
Output:
2785
round( ) function
The round() function returns a floating-point number that is a rounded version of the
specified number, with the specified number of decimals.
The default number of decimals is 0, meaning that the function will return the nearest
integer.
nearest_number = round(87.76432)
print(nearest_number)
Output:
88
nearest_number = round(-87.76432)
print(nearest_number)
Output:
-88
nearest_number = round(87.46432)
print(nearest_number)
Output:
87
divmod( ) function
The divmod() function returns a tuple containing the quotient and the remainder when
the first argument i.e, the dividend is divided by the second argument i.e, the divisor.
x = divmod(7, 3)
print(x)
Output:
(2, 1)
x = divmod(72, 6)
print(x)
Output:
(12, 0)
id( ) function
The id() function returns a unique id for the specified object. Note that all the objects in
Python have their own unique id.
The id is the object’s memory address and will be different for each time you run the
program. (except for some object that has a constant unique id, like integers from -5 to
256)
Output:
140727154106096
Output:
140727154110000
ord( ) function
The ord() function returns the number representing the Unicode code of a specified
character.
Output:
104
x = ord("H")
print(x)
Output:
72
len( ) function
The len() function returns the count of items present in a specified object.
When the object is a string, then the len() function returns the number of characters
present in that string.
Output:
Output:
54
sum( ) function
The sum() function returns a number, the sum of all items in an iterable.
If you are a beginner, I think that you don’t have a good understanding of what Iterables
and Iterators are. To learn these concepts, you can refer to the link.
Example 1: Start with the number 7, and add all the items in a tuple to this number:
a = (1, 2, 3, 4, 5)
print(sum(a, 7))
Output:
22
list = [1, 2, 3, 4, 5]
print(sum(list))
Output:
15
help( ) function
The help() function is used to display the documentation of modules, functions, classes,
keywords, etc.
If we don’t give an argument to the help function, then the interactive help utility starts
up on the console.
Example 1: Check the documentation of the print function in the python console.
help(print)
Output:
Related Modules Sequences
Python Strings
Strings
Strings in python are surrounded by either single quotation marks, or double quotation
marks.
Example
print("Hello")
print('Hello')
Try it Yourself »
Example
a = "Hello"
print(a)
Multiline Strings
You can assign a multiline string to a variable by using three quotes:
Example
You can use three double quotes:
Example
a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
print(a)
Note: in the result, the line breaks are inserted at the same position as in the code.
However, Python does not have a character data type, a single character is simply a
string with a length of 1.
Example
Get the character at position 1 (remember that the first character has the position 0):
a = "Hello, World!"
print(a[1])
Looping Through a String
Since strings are arrays, we can loop through the characters in a string, with a for loop.
Example
Loop through the letters in the word "banana":
for x in "banana":
print(x)
Learn more about For Loops in our Python For Loops chapter.
String Length
To get the length of a string, use the len() function.
Example
The len() function returns the length of a string:
a = "Hello, World!"
print(len(a))
Check String
To check if a certain phrase or character is present in a string, we can use the
keyword in.
Example
Check if "free" is present in the following text:
Use it in an if statement:
Example
Print only if "free" is present:
txt = "The best things in life are free!"
if "free" in txt:
print("Yes, 'free' is present.")
Check if NOT
To check if a certain phrase or character is NOT present in a string, we can use the
keyword not in.
Example
Check if "expensive" is NOT present in the following text:
Use it in an if statement:
Example
print only if "expensive" is NOT present:
List
A list represents a group of elements.
Lists are very similar to array but there is major difference, an array can store
only one type of elements whereas a list can store different type of elements.
Lists are mutable so we can modify it’s element.
A list can store different types of elements which can be modified.
Lists are dynamic which means size is not fixed.
Lists are represented using square bracket [ ].
Ex:- a = [10, 20, -50, 21.3, ‘Geekyshows’]
Ex:- a = [10, 20, 50]
Python Lists
❮ PreviousNext ❯
List
Lists are used to store multiple items in a single variable.
Lists are one of 4 built-in data types in Python used to store collections of data, the other
3 are Tuple, Set, and Dictionary, all with different qualities and usage.
Example
Create a List:
List Items
List items are ordered, changeable, and allow duplicate values.
List items are indexed, the first item has index [0], the second item has index [1] etc.
Ordered
When we say that lists are ordered, it means that the items have a defined order, and
that order will not change.
If you add new items to a list, the new items will be placed at the end of the list.
Note: There are some list methods that will change the order, but in general: the order
of the items will not change.
Changeable
The list is changeable, meaning that we can change, add, and remove items in a list after
it has been created.
Allow Duplicates
Since lists are indexed, lists can have items with the same value:
Example
Lists allow duplicate values:
List Length
To determine how many items a list has, use the len() function:
Example
Print the number of items in the list:
Example
String, int and boolean data types:
list1 = ["apple", "banana", "cherry"]
list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]
Example
A list with strings, integers and boolean values:
type()
From Python's perspective, lists are defined as objects with the data type 'list':
<class 'list'>
Example
What is the data type of a list?
Python Tuples
mytuple = ("apple", "banana", "cherry")
Tuple
Tuple – A tuple contains a group of elements which can be same or different
types.
It is similar to List but Tuples are read-only which means we can not modify it’s
element.
Example
Create a Tuple:
Tuple Items
Tuple items are ordered, unchangeable, and allow duplicate values.
Tuple items are indexed, the first item has index [0], the second item has index [1] etc.
Ordered
When we say that tuples are ordered, it means that the items have a defined order, and
that order will not change.
Unchangeable
Tuples are unchangeable, meaning that we cannot change, add or remove items after the
tuple has been created.
Allow Duplicates
Since tuples are indexed, they can have items with the same value:
Example
Tuples allow duplicate values:
thistuple = ("apple", "banana", "cherry", "apple", "cherry")
print(thistuple)
Try it Yourself »
Tuple Length
To determine how many items a tuple has, use the len() function:
Example
Print the number of items in the tuple:
Example
One item tuple, remember the comma:
thistuple = ("apple",)
print(type(thistuple))
#NOT a tuple
thistuple = ("apple")
print(type(thistuple))
Example
String, int and boolean data types:
tuple1 = ("apple", "banana", "cherry")
tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)
Example
A tuple with strings, integers and boolean values:
type()
From Python's perspective, tuples are defined as objects with the data type 'tuple':
<class 'tuple'>
Example
What is the data type of a tuple?
Example
Using the tuple() method to make a tuple:
NOTE : The returned value from map() (map object) then can be passed to functions like list()
(to create a list), set() (to create a set) .
CODE 1
# Python program to demonstrate working
# of map.
# Return double of n
def addition(n):
return n + n
numbers = (1, 2, 3, 4)
print(list(result))
Output :
[2, 4, 6, 8]
Set Type
A set is an unordered collection of elements much like a set in mathematics.
The order of elements is not maintained in the sets. It means the elements may
not appear in the same order as they are entered into the set.
A set does not accept duplicate elements.
Set is mutable so we can modify it.
Sets are unordered so we can not access its element using index.
Sets are represented using curly brackets { }
a = {10, 20, 30, “GeekyShows”, “Raj”, 40}
Creating a Set
A set is created by placing all the items (elements) inside curly braces {},
separated by comma. A set does not accept duplicate elements.
Elements can be of different types except mutable element, like list, set or
dictionary.
Ex:-
a = {10, 20, 30}
a = {10, 20, 30, “GeekyShows”, “Raj”, 40}
a = {10, 20, 30, “GeekyShows”, “Raj”, 40, 10, 20}
Accessing elements
Sets are unordered so we cannot access its element using index.
a = {10, 20, “GeekyShows”, “Raj”, 40}
a[0]
print(a)
Modifying Elements
Sets are mutable but as we can not access elements using index
so we can not modify it
Adding one Element
We can add a new element to set using add( ) method.
Syntax:-
set_name.add(new_element)
a.add(‘Python’)
Method union(other_set)
The union() function returns a new set by collecting all of the elements from current set and the
other_set.
Method intersection(other_set)
The intersection() function returns a new set by collecting common elements from the current set
and the other_set.
Method difference(other_set)
The difference() method will return a set, where the final set contains all of the elements of the
first set except the common elements of those two sets.
Method add(elem)
Add the element elem in the set.
Method discard(elem)
Remove the element elem from the set. This will work when the elem is present in the set. There
is another method called remove(). In the remove(), it will raise KeyError if the item is not present
in the set.
Example Code
mySet1 = {1, 2, 5, 6}
mySet2 = {8, 5, 3, 4}
mySet3 = set(range(15)) # all elements from 0 to 14 in the set
mySet4 = {10, 20, 30, 40}
print(set(mySet1.union(mySet2)))
print(set(mySet1.intersection(mySet2)))
print(set(mySet1.difference(mySet2)))
print(mySet3.issuperset(mySet1))
print(mySet1.isdisjoint(mySet4))
mySet4.add(45)
print(mySet4)
mySet4.discard(40)
print(mySet4)
Output
set([1, 2, 3, 4, 5, 6, 8])
set([5])
set([1, 2, 6])
True
True
set([40, 10, 20, 45, 30])
set([10, 20, 45, 30])