Python Material 1713000658
Python Material 1713000658
Python Course
Python Basics
What is Python?
Python is a popular and High Level programming language.
It was created by Guido van Rossum, and released in 1991.
Game developer
Full-stack developer
Machine learning engineer
Data scientist
Data analyst
Data engineer
Many more other roles
Applications on Python
Netflix
BGMI
Robots
many more
Features of Python
Easy-to-learn
Easy-to-read
Easy-to-maintain
Easy to Connect with Databases
Open Source
Large Standard libraries like Numpy,Pandas, Matplotlib etc.....
Python Install
By Clicking below link you can get official Python Website
link: https://www.python.org/
In [ ]:
The installation process will take few minutes to complete and once the installation is
successful, the following screen is displayed.
- Verify the Python version -- Open command prompt -- Type python --version
In [ ]:
Hello World
Python version: 3.11.5 | packaged by Anaconda, Inc. | (main, Sep 11 2023, 13:26:23)
[MSC v.1916 64 bit (AMD64)]
Python Indentation
Indentation refers to the spaces at the beginning of a code line.
Python uses indentation to indicate a block of code.
Python Comments
In [9]: #hfkasfhhkfasjhfkjahfianfiasifhaikjf
Hello, World!
Multiline Comments
Hello, World!
Python Identifiers
A Python identifier is a name used to identify a variable, function, class, module or other
object.
An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or
more letters, underscores and digits (0 to 9).
Python is a case sensitive programming language. Thus, 'Manpower' and 'manpower' are
two different identifiers in Python.
Python keywords
python keywords are Reserved Words
you cannot use them as constant or variable or any other identifier names.
All the Python keywords contain lowercase letters
len(python_keywords)
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class',
'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'globa
l', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise',
'return', 'try', 'while', 'with', 'yield']
35
Out[6]:
In [ ]:
Python Variables
Python variables are the reserved memory locations used to store values with in a Python
Program.
This means that when you create a variable you reserve some space in the memory.
Variables are containers for storing data values.
a = 10
print(a)
# where 'a' is variable and it is store a Value '10' by assign in it
var = 1678
var_3 = 'Python'
_var = 'Welcome to Data Science Course'
In [2]: print(var)
1678
1_var = 565
@var = 'Data'
for = 'Python'
In [22]: #You can get the data type of a variable with the type() function.
x = 57
y = "Data science"
print(type(x))
print(type(y))
<class 'int'>
<class 'str'>
Multiple Variables
In [4]: x, y, z = "Cherry", "Apple", "Banana"
print(x)
print(y)
print(z)
Cherry
Apple
Banana
100
100
100
Python Numbers
There are three numeric types in Python:
int
float
complex
In [1]: x = 1 # int
y = 2.8 # float
z = 1j #1+6j # complex # real number + imgeariy nymber
In [2]: print(type(x))
print(type(y))
print(type(z))
<class 'int'>
<class 'float'>
<class 'complex'>
Type Conversion
You can convert from one type to another with the int(), float(), and complex() methods
Note: You cannot convert complex numbers into another number type.
print(a)
print(b)
print(c)
print(type(a))
print(type(b))
print(type(c))
1.0
2
(1+0j)
<class 'float'>
<class 'int'>
<class 'complex'>
In [6]: y = 2.8j
c = float(y)
c
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[6], line 2
1 y = 2.8j
----> 2 c = float(y)
3 c
Python Booleans
Booleans represent one of two values: True or False.
True
False
True
In [10]: print(bool("Hello"))
print(bool(15>9))
True
True
Python Operators
Operators are used to perform operations on variables and values. Python divides the operators in the following
groups: - Arithmetic operators - Assignment operators - Comparison operators - Logical operators - Identity
operators - Membership operators - Bitwise operators
In [11]: a = 67
b = 86
In [12]: # Addition
c = a + b
print(c)
153
In [13]: #Subtraction
d = a - b
print(d)
-19
In [14]: #Multiplication
f = a * b
print(f)
In [15]: #Division
g = a / b #returns the quotient
print(g)
0.7790697674418605
In [16]: #Modulus
h = a % b
print(h) # It returns the remainder
67
In [15]: a = 5
b = 2
#Exponentiation
j = a ** b
print(j)
25
Assignment Operators
-- Assignment operators are used to assign values to variables.
In [19]: # assign 10 to a
a = 10
# assign 5 to b
b = 5
print(a)
15
In [ ]: c = 3
g = 5
c *= g
c= c * g
Comparison Operators
-- Comparison operators compare two values/variables and return a boolean result: True or
False.
In [ ]: print()
In [20]: a = 50
b = 28
# equal to operator
a == b = False
a != b = True
a > b = True
a < b = False
a >= b = True
a <= b = False
Logical Operators
-- Logical operators are used to check whether an expression is True or False. -- Python logical
operators are used to combile two or more conditions and check the final result.
True
False
True
Identity Operators
-- Identity whether the value is present or not
In [2]: x1 = 5
y1 = 5
x2 = 'Hello'
y2 = 'Hello'
False
True
In [27]: t = [1,2,3]
i = [1,2,3]
print(t is i)
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
-- They are used to test whether a value or variable is found in a sequence or not
True
True
True
False
Bitwise operators
Bitwise operators act on operands as if they were strings of binary digits. They operate bit by bit, hence the name.
For example, 2 is 10 in binary and 7 is 111
In [4]: """
The & operator compares each bit and set it to 1 if both are 1, otherwise it is set to
6 = 0110
3 = 0011
-----------
2 = 0010
===========
"""
print(6 & 3)
In [ ]: """
The | operator compares each bit and set it to 1 if one or both is 1, otherwise it is
6 = 0110
3 = 0011
---------
7 = 0111
=========
"""
print(6 | 3)
In [ ]: """
The ^ operator compares each bit and set it to 1 if only one is 1, otherwise (if both
6 = 0110
3 = 0011
----------
5 = 0101
==========
"""
print(6 ^ 3)
In [ ]: """
The ~ operator inverts each bit (0 becomes 1 and 1 becomes 0).
simple formal
-(n+1) -(3+1) = -4
"""
print(~3)
print(~83)
In [2]: """
The << operator inserts the specified number of 0's (in this case 2) from the right an
"""
print(3 << 2)
12
In [6]: """
The >> operator moves each bit the specified number of times to the right. Empty holes
"""
print(8 >> 2)
Precedence
-- Operator precedence describes the order in which operations are performed.
In [2]: 6+(4+7)-5
12
Out[2]:
In [ ]: 6 +11 - 5
In [1]: 17-5
12
Out[1]:
In [32]: 9+7-(4-2)*5
6
Out[32]:
In [ ]: 90-67+4*3/5
In [4]: 7+(4*4)-8**2
-41
Out[4]:
Data Types
Python List
-> It is commonly used data type that represents an ordered, mutable (modifiable), and iterable sequence of
elements. -> Lists are used to store collections of items, and these items can be of any data type, including
numbers, strings, or even other lists. -> Lists are defined using square brackets [] and elements are separated by
commas.
Creation of Lists:
In [3]: # Creating an empty list
my_list = []
In [6]: a =29.9
print(type(a))
<class 'float'>
In [4]: print(type(mixed_types))
<class 'list'>
Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to
the second last item and so on.
Python
C++
print(lst1[-2])
java
C++
Slicing of a List
In Python, it is possible to access a portion of a list using the slicing operator :
my_list = ['E','t','e','r','n','a','l','t','e','k']
print(my_list[-3:-1]) # n+1
['t', 'e']
List Operations
List Contain Two types of Operations 1) Concatenation 2) Repetition
In [12]: #concatenation
a = [1, 2, 3]
b = [4, 5, 6]
c = a + b
print(c)
[1, 2, 3, 4, 5, 6]
In [11]: # Repetition
a = [3,6,9,12]
b = a * 7
print(b)
print(lt)
list methods
1) append():
[1, 2, 3, 4]
2) extend():
[1, 2, 3, 4, 5, 6]
3) insert():
#numbers.insert(2, 9)
#numbers.insert(-1, 9)
print(numbers)
[1, 99, 2, 3]
4) remove():
[1, 6, 2, 3, 2, 4]
5) pop():
[1, 3, 4, 5, 7, 9, 4]
2
6) index():
In [14]: numbers = [10, 20, 30, 20, 40, 30, 30, 40]
index = numbers.index(40)
print(index)
count():
8) sort():
[0, 1, 2, 2, 2, 2, 3, 4, 4, 6, 6, 6, 7, 9]
9) reverse():
In [28]: numbers = [ 6, 0, 2, 6, 4]
numbers.reverse()
print(numbers)
[4, 6, 2, 0, 6]
List Comprehension
List comprehension offers a shorter syntax when you want to create a new list based on the
values of an existing list.
Syntax
Condition
The condition is like a filter that only accepts the items that valuate to True.
print(newlist)
In [51]: print(newlist)
['apple']
Python Strings
In Python, a string is a sequence of characters.
Strings are one of the most commonly used data types, and they are used to represent text.
Strings are immutable, meaning that once a string is created, you cannot modify its content
directly.
However, you can perform various operations and use methods to manipulate and work with
strings.
This is a
multi-line string.
String Operations
1) Concatenation:
Hello World
2) Repetition:
3) Indexing:
4) Slicing:
World
1. Format Method:
Uses f-strings, where expressions inside curly braces {} are evaluated and replaced
format_str = f"My name is {name} and i am {age} year old. i am from {location}."
print(format_str)
String Methods
1) len():
23
2) lower() / upper():
print(my_string.upper())
HELLO
hello world
3) strip():
Python
4) replace():
file:///C:/Users/TEKS108/Downloads/Python Course Material (3).html 26/63
2/21/24, 6:01 PM Python Course Material
Hello, Python!
Hello Good
5) split():
6) join():
Python Tuples
A tuple is a data type that represents an ordered, immutable (unchangeable) sequence of
elements.
Tuples are similar to lists, but the key difference is that tuples cannot be modified once they are
created.
They are defined using parentheses () and elements are separated by commas.
Each element in a tuple has a specific order that will never change because tuples are ordered
sequences.
Creating a Tuple
In [54]: #Empty Tuple:
empty_tuple = ()
single_element_tuple = (42,)
single_element_tuple
(42,)
Out[61]:
In [ ]: single_element_tuple = 42
Accessing of Tuples
Tuples support indexing and slicing, just like lists.
In [67]: # 0 1 2
fruits = ("apple", "banana", "orange")
print(fruits[2]) #index
print(fruits[0:7]) #slicing
orange
('apple', 'banana', 'orange')
In [ ]:
Immutability:
Once a tuple is created, you cannot change its elements or add/remove elements.
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[77], line 3
1 fruits = ("apple", "banana", "orange")
2 # This will raise an error
----> 3 fruits[2] = "pear"
4 #print(fruits)
5 fruits
Tuple Operations
1) Concatenation:
2) Repetition:
Repeating a tuple.
(1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1,
2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2,
3, 1, 2, 3)
Tuple Methods
Tuples have limited methods compared to lists due to their immutability
1) count():
2) index():
Python Dictionaries
A dictionary is a data structure that allows you to store and retrieve data in a key-value pair
format.
Dictionaries are also known as associative arrays or hash maps in other programming
languages.
They are defined using curly braces {} and consist of key-value pairs separated by colons.
Creating Dictionaries:
In [13]: # Empty dictionary
empty_dict = {}
In [ ]:
In [65]: print(empty_dict)
print(student)
print(mixed_dict)
{}
{'name': 'Eternaltek', 'age': 25, 'grade': 'A'}
{'name': 'Vamsi', 'age': 30, 'grades': [85, 90, 92]}
Accessing Values:
You can access the values in a dictionary using the keys.
Radika
[85, 90, 92]
In [4]: print(student['age'])
25
{'name': 'Sai', 'age': 26, 'grade': 'A', 'gender': 'Female', 'Qulification': 'B.Tec
h'}
In [6]: print(student)
{'name': 'Sai', 'age': 26, 'grade': 'A', 'gender': 'Female', 'Qulification': 'B.Tec
h'}
Dictionary Methods:
1) get():
Returns the value for a specified key. It allows you to provide a default value if the key is not
found.
In [26]: g = student.get('grade')
gender = student.get('gender', 'Not specified')
h = student.get('location', 'Not Prividied')
#g = student.get('exper')
In [27]: print(g)
print(gender)
print(h)
A
Female
Not Prividied
2) keys():
3) values():
4) items():
5) pop():
30
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[18], line 1
----> 1 name = mixed_dict.pop()
2 name
6) popitem():
In [28]: print(student)
{'name': 'Sai', 'age': 26, 'grade': 'A', 'gender': 'Female', 'Qulification': 'B.Tec
h'}
('Qulification', 'B.Tech')
7) update():
Updates the dictionary with elements from another dictionary or from an iterable of key-value
pairs.
Python Sets
In Python, a set is a collection of unique elements, and it is defined using curly braces {} and sep
by , (comma)
Sets provide a variety of methods for performing common set operations like union,
intersection, difference, and more
Creating Sets:
In [4]: # Creating an empty set
#empty_set = set()
{1, 2, 3, 4, 5}
In [23]: numbers
'[1, 2, 3, 4, 5]'
Out[23]:
set()
Out[84]:
{2, 3, 4, 5, 6, 8, 9}
#print('Initial Set:',numbers)
Updated Set: {34, 67, 21, 54, 87, 90, 12, 45}
In [ ]:
The update() method is used to update the set with items other collection types (lists, tuples,
sets, etc).
update_companies = companies.update(tech_companies)
print(companies)
In [ ]:
#print('Initial Set:',languages)
even_numbers = {2,4,6,8,10,12,14,12,16,18}
#print('Set:',even_numbers)
Total Elements: 9
The union of two sets A and B include all the elements of set A and B.
# second set
d = {0, 2, 4}
In [ ]: A.union(B)
2) Set Intersection
The intersection of two sets A and B include the common elements between set A and B.
# second set
B = {1, 2, 3, 0, 5, 4}
The difference between two sets A and B include elements of set A that are not present on set B.
Returns elements that are in the first set but not in the second.
# second set
The symmetric difference between two sets A and B includes all elements of A and B without the
common elements.
Returns elements that are in either of the sets, but not in both.
# second set
B = {1, 2, 6, 4, 9}
# using symmetric_difference()
print('using symmetric_difference():', A.symmetric_difference(B))
using ^: {1, 3, 5, 6, 7, 8, 9}
using symmetric_difference(): {1, 3, 5, 6, 7, 8, 9}
In [ ]:
The if, else, and elif (short for "else if") keywords are used for creating conditional structures.
1) Python if Statement
Syntax
if condition:
# body of if statement
In [ ]:
In [22]: number = 43
# check if number is greater than 0
if number > 0: #condition --- if condition is TRue it will the return the body statem
print('Number is positive')
#print("Python")
In [29]: number = 78
if number > 0:
print("Given number is positive")
The else statement executes if the condition in the if statement evaluates to False.
Syntax
if condition:
# body of if statement
else:
In [19]: number = 56
if number > 0:
print('Positive number')
else:
print('Negative number')
Positive number
In [ ]:
#body statement
elif condition:
#body statements
else:
#body statements
In [34]: number = 0
if number > 0:
print("Positive number")
else:
print('Zero')
Zero
In [ ]:
1) static type input: intital assgin by developer or code writer 2) dymanic type input: inputs enter
by user
In [33]: number = int(input("Enter your lucky number: ")) #number you to mention int()
if number > 0:
print("your lucky number is Positive")
elif number < 0:
print("your lucky is negative")
else:
print("your lucky number is Zero")
# outer if statement
if number >= 0: #-8 >= 0
# inner if statement
if number == 0:
print('Number is 0')
file:///C:/Users/TEKS108/Downloads/Python Course Material (3).html 41/63
2/21/24, 6:01 PM Python Course Material
# inner else statement
else:
print('Number is positive')
if a > 10:
print("a is greater than 10")
if b > 20:
print("b is greater than 20")
if c > 30:
print("c is greater than 30")
else:
print("c is not greater than 30")
else:
print("b is not greater than 20")
else:
print("a is not greater than 10")
a is greater than 10
b is greater than 20
c is not greater than 30
Loop Statements
file:///C:/Users/TEKS108/Downloads/Python Course Material (3).html 42/63
2/21/24, 6:01 PM Python Course Material
while condition:
Here,
-> If the condition evaluates to True, the code inside the while loop is executed.
i = i + 1 #increment
print(i)
1
2
3
4
5
6
1
2
3
4
5
# statement(s)
The loop continues until we reach the last item in the sequence.
P
y
t
h
o
n
apple
banana
orange
E
t
e
r
n
a
l
t
e
k
Vamsi's grade is 90
Reddy's grade is 85
Kumar's grade is 92
shiva's grade is 98
In [ ]:
Control Statements
In Python, pass, break, and continue are control flow statements used within loops.
They provide ways to control the execution of a loop or to handle certain situations.
In [ ]:
1. pass:
The pass statement is a no-operation statement.
It is a placeholder where syntactically some code is required, but no action needs to be taken.
0
1
2
3
4
5
7
8
9
In this example, when i is equal to 3, the pass statement is executed, and the loop continues
without doing anything.
It is often used when a statement is syntactically required, but you want to skip its execution.
In [ ]:
2. break:
The break statement is used to exit a loop prematurely.
When a break statement is encountered, the loop terminates immediately, and the control is
transferred to the statement immediately following the loop.
0
1
2
3
4
In this example, the loop will print values from 0 to 4. When i becomes 5, the break statement is
encountered, and the loop is terminated.
In [ ]:
3. continue:
The continue statement is used to skip the rest of the code inside a loop for the current iteration
and move to the next iteration.
0
1
2
3
4
5
6
8
9
In [ ]:
In this example, the loop will print values from 0 to 4, skipping the printing step when i is equal
to 2 due to the continue statement.
In [ ]: def gin():
Python Functions
A function is a block of code that performs a specific task.
Types of function
Standard library functions - These are built-in functions in Python that are available to use.
User-defined functions - We can create our own functions based on our requirements.
def function_name(arguments):
# function body
return
Here,
print(f"Hello, {name}!")
Hello, Reddy!
Hello, F!
In [ ]:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[62], line 5
2 print(f'your name is {name} and your {age} is Eogluta vote')
4 #vote("reddy", 23)
----> 5 vote("Reddy")
add_number(454, 4)
Sum: 128
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[65], line 9
6 # function call with two values
7 add_numbers(44, 84)
----> 9 add_number(454, 4)
def add_numbers(): ... return sum Here, we are returning the variable sum to the function call.
# function call
find_square(37)
#print('Square:',square)
1369
Out[72]:
These library functions are defined inside the module. And, to use them we must include the
module inside our program.
Python Lambda
A lambda function is a small anonymous function.
A lambda function can take any number of arguments, but can only have one expression.
Syntax
In [16]: x = lambda a : a + 10
print(x(55)) # print(x(a))
65
mult = myfunc(5)
print(mult(11))
55
In other words, we can say that local variables are accessible only inside the function in which it
was initialized whereas the global variables are accessible throughout the program and inside
every function.
# local variable
s = "I love Eternaltek"
print(s)
# Driver code
f()
I love Eternaltek
rt()
#If we will try to use this local variable outside the function then let’s see what wi
# local variable
s = "I love Eternaltek"
print("Inside Function:", s)
# Driver code
f()
print(s)
These are those which are defined outside any function and which are accessible throughout
the program, i.e.,
inside and outside of every function. Let’s see how to create a Python global variable.
f()
print("Outside Function", s)
In [ ]:
Python Classes/Objects
Python is an object oriented programming language.
Create a Class
To create a class, use the keyword class:
Create Object
Now we can use the class named MyClass to create objects:
def bark(self):
print("Woof!")
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:
obj = self()
Hello world
In [ ]:
In this example, when you create a Dog object (my_dog), the init method is automatically called,
and it initializes the name and age attributes of the object.
str Method:
The str method is used to provide a human-readable string representation of the object.
It is called when the str() function is used on an object or when print() is called with an object.
def __str__(self):
return f"{self.name}, {self.age} years old"
In this example, the str method is defined to return a formatted string representing the dog's
name and age.
When str() or print() is called on the my_dog object, the str method is invoked, providing a
readable output.
In [ ]:
Python Inheritance
Inheritance is a way of creating a new class for using details of an existing class without
modifying it.
The newly formed class is a derived class (or child class). Similarly, the existing class is a base
class (or parent class).
def eat(self):
print( "I can eat!")
def sleep(self):
print("I can sleep!")
# derived class
class Dog(Animal):
def bark(self):
print("I can bark! Woof woof!!")
class Cat(Animal):
def Mayoo(self):
print(" I can Mayoo! Mayoo!")
obj2 = Cat()
obj2.eat()
obj2.sleep()
obj2.Mayoo()
I can eat!
I can sleep!
I can bark! Woof woof!!
I can eat!
I can sleep!
I can Mayoo! Mayoo!
In [ ]:
Python Encapsulation
Encapsulation is one of the key features of object-oriented programming.
Encapsulation refers to the bundling of attributes and methods inside a single class.
wrapping data and methods that work with data in one unit.
In Python, we denote private attributes using underscore as the prefix i.e single _(Protected) or
double __ (Private) and Public. For example,
d = Demo1(3,4)
d.output()
3
4
In [ ]:
Polymorphism
Polymorphism is another important concept of object-oriented programming. It simply means
more than one form.
That is, the same entity (method or operator or object) can perform different operations in
different scenarios.
In [ ]: #class Polygon:
# method to render a shape
#def render(self):
# print("Rendering Polygon...")
#class Square(Polygon):
# renders Square
# def render(self):
# print("Rendering Square...")
#class Circle(Polygon):
# renders circle
# def render(self):
# print("Rendering Circle...")
obj = sum1()
print(obj.add(3,5))
print(obj.add('a','b'))
8
None
ab
None
Abstraction
Hiding the unnecessary details.
Abstraction allows you to focus on what an object does rather than how it achieves its
functionality.
In [ ]: class Car:
def start_engine(self):
pass # Abstract method, implementation details hidden
def drive(self):
pass # Abstract method, implementation details hidden
def stop_engine(self):
pass # Abstract method, implementation details hidden
In [ ]:
Polymorphism allows the same interface for different objects, so programmers can write
efficient code.
In [ ]:
When we want to read from or write to a file, we need to open it first. When we are done, it
needs to be closed so that the resources that are tied with the file are freed.
To demonstrate how we open files in Python, let's suppose we have a file named test.txt with
the following content.
In [ ]:
In [37]: #By default, the files are open in read mode (cannot be modified). The code above is e
s = open("test1.txt", "r")
print(s.read())
Hi Friends
Hi Friends
Closing a file will free up the resources that were tied with the file.
Bye FriendsHi friendsHi friendsHow are you friendsHow are you friends
The try...except block is used to handle exceptions in Python. Here's the syntax of try...except block: try: # code
that may cause exception except: # code to run when exception occurs
In [46]: try:
file1 = open("test1.txt", "r")
read_content = file1.read()
print(read_content)
finally:
# close the file
file1.close()
Bye FriendsHi friendsHi friendsHow are you friendsHow are you friends
In [ ]:
In [48]: try:
numerator = 10
denominator = 0
result = numerator/denominator
print(result)
except:
print("Error: Denominator cannot be 0.")
In [ ]: