Python Notes Harshith
Python Notes Harshith
Python:
Python is a high-level, object-oriented, interpreted language that can be applied to various fields such as web development,
machine learning, data analysis, etc.
Why Python:
Python is known for its straightforward syntax and ease of use, making it a popular choice for beginners.
With over 127,000 libraries available, it offers a vast range of possibilities for developers to work with.
Python is widely used across various domains such as web development, machine learning, artificial intelligence, and
more.
Variables:
Variables are named places in memory where values can be stored for later use.
a=10
b="Harshith"
In the above statement "a = 10 and b = "Harshith", "a" and "b" are examples of variables that are assigned the values 10 and
"Harshith", respectively.
Python, variables are case-sensitive, meaning that "Name" and "name" are considered two different variables.
Data Types:
Data types are the classification of data based on the type of value they hold. Some common data types in programming
include:
4. Boolean: a data type that can have only two values, either True or False
#Integers
a=10
b=11339
#Float
a=1.22
nass=0.40
g=1.00
#Strings
a="ahhssh"
b="asdfghjkl"
#Boolean
a=True
b=False
#complex
a=2+3j
b=44-9j
ip: type(123)
op: int
ip: type("ASDFFF")
op: str
ip: type(1.00)
op: float
ip: type(True)
op: boolean
ip: type(1+2j)
op: complex
Type Casting:
Type casting is the technique by which we can change the data type of the data from one data type to another.
For eg: if a=123 and it is an integer, we can easily change its Data Type by using float(a) or str(a). Here float value will become
123.00 and if it’s changed to string it will become “123” which is not a number but a character in the form of a number.
ip: a=123
type(a)
op: int
ip: a=str(a)
type(a)
op: str
# And we can do this as vice versa to change strings(in the form of numbers) to float and int.
# And also float to int and str.
ip: int(123.45)
op: 123
ip: print("asdfghjkl")
op: asdfghjkl
ip: a=12
print(a)
op: 12
ip: print(1+2)
op: 3
ip: print("asdfghjkl
asdghhh)
op: error
ip: print("asdfghjkl\nasdghhh")
op: asdfghjkl
asdfhhh
ip: a=12
b="pen"
print(a,b)
op: 12,pen
ip: print(a,b,sep='-')
op: 12-pen
Using comma
fstring
Formatting
Using comma:
Just use the comma symbol between two variables to add them( variables can be of any Data Types)
fstring:
Format Function:
Same as fstring but there is no need to give f and also no need to give the variable name in angular {} braces. Instead, we can
use .format() function and pass the variables or parameters in it.
# Note: The variables in the format function should be in the same order as the places
# you want them to fit in angular braces.
ip: print("My name is {n} and age is {a} and I had done my {d}".format(a=age,d=degree
,n=name))
op: My name is Harshith and age is 21 and I had done my Btech
ip: a=22
# using "IF" the code will check if the condition is greater than 18 or not.
if a>18:
# if the statement is true it will execute the below line of code
print("You are major")
else:
# if the "IF" statement is false, then the Else code will be executed.
print("You are minor")
op: You are major
Elif: Will be used along with If-Else where we have to check more than 2 conditions.
ip: a=77
# using "IF" the code will check if the condition is greater than 18 or not.
if a>18 and a<60:
# if the statement is true it will execute the below line of code
print("You are major")
elif a>60:
print("You are old")
else:
print("You are minor")
op: You are old
For Loop: Executes a block of code repeatedly for each item in a sequence (list, tuple, etc.).
For eg: if name=”Harshith” and I want to traverse each of the elements of the value of the variable name, Then I have to travel
through H A R S H I T H one by one. we can do this by using For loop. so we can define for-loop as the one which can traverse
through all the elements of a given value be it string or list or dictionary or etc.
#Program to replace all the letters "H" to "*" using if statement in for loop.
ip: name="HARSHITH"
for i in name:
# I will add an if statement here.
if i=="H":
print(*)
else:
print(i)
op: *
A
R
S
*
I
T
*
Instead of Printing each character in a different line, we can print them on the same line using the end property in the print
statement.
#In this code I used end="" empty string to be placed between each printing Element.
ip: name="HARSHITH"
for i in name:
if i=="H":
print(*,end="")
else:
print(i,end="")
op: *ARS*IT*
we can use the Break statement to end a loop when a certain condition occurs.
#In this code I will stop executing code if there is letter "R" occurs.
ip: name="HARSHITH"
for i in name:
if i=="R":
break
print(i,end="")
op: HA
Continue: Skips the current iteration of a loop and moves to the next one.
we can use the Continue to skip the loop for one time to execute when a certain condition occurs.
#In this code I will skip executing code if there is letter "H" occurs.
ip: name="HARSHITH"
for i in name:
if i=="H":
continue
print(i,end="")
op: ARSIT
While Loop: Executes a block of code repeatedly as long as a given condition is true.
For Eg: If there is a Government employee who aged 25. if we want to write a code to notify him when it’s time for him to Retire
we can do it using While loop by printing that it’s time for his retirement once he reaches 62 by using While Loop.
Logical Operators:
There are 3 types of Logical Operators in Python, they are
And: Return True if both the values are True, else return False.
True False
False True
Comparision Operators:
The main Comparision Operators in python include:
is - Returns True if both the a and b point to the same memory location, else Return False. Usually, non mutable Data
Types with the same values in them return True.
# The below code will return False because lst1 and lst2 were saved in a different location.
ip: lst1=[1,2,3,4,5]
lst2=[1,2,3,4,5]
lst1 is lst2
op: False
# The below code will return True because lst1 and lst2 were saved in different locations.
ip: lst1=[1,2,3,4,5]
lst2=[1,2,3,4,5]
lst1 is not lst2
op: True
# The below code will return False because a and b were saved in the same location.
ip: a=9
b=9
a is not b
op: False
== - it will return True if the value assigned to a is equal to value assigned to b, else False.
# The below code will return True because lst1 and lst2 have the same values in them.
ip: lst1=[1,2,3,4,5]
lst2=[1,2,3,4,5]
lst1 == lst2
op: True
# The below code will return False because a and b have different values.
ip: a=9
b=90
a == b
op: False
# The below code will return False because lst1 and lst2 have the same values in them.
ip: lst1=[1,2,3,4,5]
lst2=[1,2,3,4,5]
lst1 != lst2
op: False
# The below code will return True because a and b have different values.
ip: a=9
b=90
a != b
op: True
Arithmetic Operators:
+ - addition
- - subtraction
* - multiplication
/ - division
% - remainder
100 9 + 109
100 9 - 91
100 9 * 900
100 9 / 11.1111
Strings:
In Python, a string is a sequence of characters represented in quotes (single or double).
Slicing is a way to extract a portion of a string, list, or any sequence. It's done by specifying the start and end index of the
portion, separated by a colon (:). For example:
In this example, the slicing my_string[0:5] returns a new string that starts at index 0 and ends at index 5 (not including index
5).
If the start index is not specified, it defaults to the start of the sequence. If the end index is not specified, it defaults to the end of
the sequence. For example:
ip: my_string[:5]
op: Hello
ip: my_string[6:]
op: World!
Negative indices can also be used to slice from the end of the sequence. For example:
ip: my_string[-6:]
op: World!
2. find() : returns the index of the first occurrence of the substring in the string. Returns -1 if the substring is not found.
4. partition() : splits the string into three parts: the part before the first occurrence of the substring, the substring, and the part
7. swapcase() : returns a new string with all uppercase characters converted to lowercase and all lowercase characters
converted to uppercase.
8. title() : returns a new string with the first letter of each word capitalized.
10. reversed() : Returns a reverse iterator of a string. To get the reversed string, use ''.join(reversed(string)) .
15. isspace() : Returns True if all characters in a string are whitespaces, False otherwise.
16. isupper() : Returns True if all characters in a string are uppercase, False otherwise.
17. islower() : Returns True if all characters in a string are lowercase, False otherwise.
18. startswith() : Returns True if a string starts with a specified prefix, False otherwise.
19. endswith() : Returns True if a string ends with a specified suffix, False otherwise.
20. isalnum() : Returns True if all characters in a string are alphanumeric (letters and digits), False otherwise.
22. isalpha() : Returns True if all characters in a string are letters, False otherwise.
substring = "Hello"
print("First occurrence of substring '{}' at index: {}".format(substring, string.find(substring)))
print("Number of occurrences of substring '{}': {}".format(substring, string.count(substring)))
Outputs:
Lists:
A list is a collection of items in a ordered sequence, which can be of different data types (integer, string, float, etc.). Lists are
defined using square brackets [] and items are separated by commas , .
min is a built-in function in Python that returns the minimum value from a list or any iterable.
max is a built-in function in Python that returns the maximum value from a list or any iterable.
reverse is a method in Python that can be used to reverse the order of elements in a list.
descending reverse: To sort a list in descending order, the sort method can be used with the argument reverse=True .
append is a method in Python that can be used to add an element to the end of a list.
extend is a method in Python that can be used to add elements from one list to another.
# Initializing a list
numbers = [3, 4, 1, 8, 5]
Outputs:
Min Value: 1
Max Value: 8
Sorted List: [1, 3, 4, 5, 8]
Reversed List: [8, 5, 4, 3, 1]
Sorted List in Descending Order: [8, 5, 4, 3, 1]
List after appending 9: [8, 5, 4, 3, 1, 9]
List after extending with new numbers: [8, 5, 4, 3, 1, 9, 10, 11, 12]
List Comprehensions:
List comprehensions are a concise way to create new lists by transforming existing ones. They are written as a single line of
code and can include an optional condition.
Output:
Tuples:
Tuples are immutable, ordered collections of items, denoted by ()
Functions in Tuple:
1. index(element): returns the index of the first occurrence of the given element in the tuple.
2. count(element): returns the number of occurrences of the given element in the tuple.
# Creating a tuple
t = (1, 2, 3, 3, 4, 5)
# Index function
print("The index of 3 in the tuple is: ", t.index(3))
# Output: The index of 3 in the tuple is: 2
# Count function
print("The count of 3 in the tuple is: ", t.count(3))
# Output: The count of 3 in the tuple is: 2
# Length function
print("The length of the tuple is: ", len(t))
# Output: The length of the tuple is: 6
# Min function
print("The minimum element in the tuple is: ", min(t))
# Output: The minimum element in the tuple is: 1
# Max function
print("The maximum element in the tuple is: ", max(t))
# Output: The maximum element in the tuple is: 5
# Changing elements (Convert tuple to list, change elements and convert list to tuple)
l = list(t2)
l[0] = 8
t2 = tuple(l)
print("The modified tuple is: ", t2)
# Output: The modified tuple is: (8, 2, 3, 3, 4, 5, 6, 7)
Tuples are immutable, meaning once you create a tuple you cannot change its elements.
However, you can concatenate two tuples to form a new tuple, e.g. tuple1 + tuple2.
Changing elements:
If you need to change elements in a tuple, you'll have to convert the tuple to a list, change the elements and then convert
the list back to a tuple.
The del statement is used in Python to delete a reference to an object. When you delete a reference, the object may not be
immediately destroyed. Instead, the memory occupied by the object is released when there are no more references to the
object.
t = (1, 2, 3, 4)
print("The original tuple: ", t)
# Output: The original tuple: (1, 2, 3, 4)
Functions:
1. add() : Adds an element to the set.
2. pop() : Removes and returns an arbitrary element from the set. Raises a KeyError if the set is empty.
3. clear() : Removes all elements from the set.
# Creating a set
s = {1, 2, 3}
print("The set: ", s)
# Output: The set: {1, 2, 3}
s = {1, 2, 3}
print("The original set: ", s)
# Output: The original set: {1, 2, 3}
s.add(4)
print("The set after adding an element: ", s)
# Output: The set after adding an element: {1, 2, 3, 4}
s = {1, 2, 3}
print("The original set: ", s)
# Output: The original set: {1, 2, 3}
x = s.pop()
print("The popped element: ", x)
# Output: The popped element: 1
print("The set after popping an element: ", s)
# Output: The set after popping an element: {2, 3}
s = {1, 2, 3}
print("The original set: ", s)
# Output: The original set: {1, 2, 3}
s.clear()
print("The set after clearing all elements: ", s)
# Output: The set after clearing all elements: set()
s = {1, 2, 3}
print("The original set: ", s)
# Output: The original set: {1, 2, 3}
Python Dictionaries
A dictionary in Python is an unordered collection of key-value pairs. It is also known as an associative array or hash map. You
can use a dictionary to store values in a key-value format, where each key maps to a unique value.
# Creating a dictionary
d = {'key1': 'value1', 'key2': 'value2'}
print("The dictionary: ", d)
# Output: The dictionary: {'key1': 'value1', 'key2': 'value2'}
Dictionary Methods
Here are some of the common methods that can be performed on a dictionary:
2. values() : Returns a view object that displays a list of all the values in the dictionary.
3. items() : Returns a view object that displays a list of all the key-value pairs in the dictionary.
4. update() : Adds elements to the dictionary. If the key is already present, it updates the key-value.
5. The update() method is used to add elements to an existing dictionary or to merge two dictionaries.
7. The get() method is used to retrieve the value of a key from the dictionary.
8. The fromkeys() method is used to create a new dictionary where each key is the same and the values are set to None.
9. To create a deep copy of a dictionary, you can use the copy module in Python.
# Creating a dictionary
d = {'key1': 'value1', 'key2': 'value2'}
print("The dictionary: ", d)
# Output: The dictionary: {'key1': 'value1', 'key2': 'value2'}
d.update({'key3': 'value3'})
print("The dictionary after updating an element: ", d)
# Output: The dictionary after updating an element: {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
import copy
Functions:
Functions are blocks of reusable code that can be called multiple times in a program.
They are defined using the def keyword, followed by the function name, parameters within parentheses and a colon.
The code inside the function is indented and executed when the function is called.
Functions can return values using the return keyword. If a function does not have a return statement, it returns None by
default.
greet("John")
# Output: Hello, John. How are you today?
Arguments:
Functions can take arguments as inputs.
Positional arguments: passed to the function in the same order as they are defined in the function.
Keyword arguments: passed to the function using the argument name and value.
Default arguments: assigned a default value in the function definition. If no value is provided during the function call,
the default value is used.
greet("John")
# Output: Hello, John. Good morning!
*args:
It allows the function to take a variable number of positional arguments.
args is used as a parameter in the function definition and collects all remaining positional arguments into a tuple.
def greet(*names):
"""This function greets all persons in the names tuple"""
for name in names:
print("Hello, " + name)
**kwargs:
It allows the function to take a variable number of keyword arguments.
*kwargs is used as a parameter in the function definition and collects all remaining keyword arguments into a dictionary.
def greet(**kwargs):
"""This function greets the person passed in as a parameter"""
if kwargs:
print("Hello, " + kwargs['name'] + ". " + kwargs['msg'])
Generator Functions:
A generator function is a special type of function that can be used to generate a sequence of values over time, instead
of computing all the values at once and returning them in a list.
The generator function uses the yield keyword instead of return to produce a value.
Generator functions are used for iteration, because they can generate values one by one, instead of all at once.
def my_range(n):
"""This is a generator function that yields values from 0 to n (exclusive)"""
i = 0
while i < n:
yield i
i += 1
for i in my_range(5):
print(i)
# Output:
# 0
# 1
# 2
# 3
# 4
Lambda Function:
A lambda function is a small anonymous function. It can take any number of arguments, but can only have one expression.
x = lambda a : a + 10
print(x(5))
# Output: 15
Map:
The map() function is used to apply a function to each item of an iterable (list, tuple etc.) and returns a new list containing
all the items modified by the function
pythonCopy code
def multiply(x):
return x * 2
numbers = [1, 2, 3, 4]
result = list(map(multiply, numbers))
print(result)
# Output: [2, 4, 6, 8]
Reduce:
The reduce() function is used to apply a particular function passed in its argument to all of the list elements. This function is
defined in the functools module.
pythonCopy code
from functools import reduce
numbers = [1, 2, 3, 4]
result = reduce(multiply, numbers)
print(result)
# Output: 24
Filter:
The filter() function is used to filter the given iterable with the help of another function passed as an argument to test all
the elements to be True or False .
def even_check(num):
if num % 2 == 0:
return True
OOPS in Python:
Object:
An object is an instance of a class, which represents real-world entities such as a person, a car, a bank account, etc.
Everything in Python is an object, including data types such as numbers, strings, and lists.
Class:
A class is a blueprint for creating objects, allowing you to define the attributes and behaviors of objects of a particular type.
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
Method:
A method is a function that is associated with an object and can be called on that object.
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def get_info(self):
return f"{self.make} {self.model} ({self.year})"
Constructor:
The __init__ method is a special method that is called when an object is created from a class and is used to initialize the
attributes of the object. It is also called a constructor.
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year