Python is an object-oriented, high-level programming language.
It was created by Guido van Rossum in 1991.
Named after Monty Python.
It is a partially compiled language and partially interpreted language.
It is user for Web Development, Game Development and Software Development.
‘#’ is used to comment on everything that comes after on the line.
MUTABLE AND IMMUTABLE:
Mutable data types can be edited i.e., they can change at runtime.
Eg – List, Set, Dictionary
Immutable data types cannot be edited i.e., they cannot change at runtime.
Eg – String, Tuple
STRING:
Sequence of characters enclosed in single, double, or triple quotes
Immutable
Example: string = "Hello, World!"
print(string[0]) # Access first character: 'H'
print(string.upper()) # Convert to uppercase: 'HELLO, WORLD!'
LIST:
Ordered collection of data values
Represented by [ ]
Mutable
Created using the list() function
Example: [1, 2, 3, "hello"]
data.append(89) # Add an item
data.remove(45) # Remove an item
data[2] = 99 # Update an item: [1, 2, 99, "hello", True, 4]
TUPLE:
Ordered collection of data values
Represented by ( )
Immutable
Created using the tuple() function.
Example: (1, 2, 3, "hello")
SET:
Unordered collection of unique elements
Represented by { }
Mutable
Created using the set() function
Example: {1, 2, 3, 4, 5}
set_example = {1, 2, 3, 3, 4} # Duplicates are removed: {1, 2, 3, 4}
set_example.add(5) # Add an item: {1, 2, 3, 4, 5}
set_example.remove(2) # Remove an item: {1, 3, 4, 5}
Set Operations (Union, Intersection, Difference)
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
union = set1.union(set2) # {1, 2, 3, 4, 5, 6}
set1 | set2
intersection = set1.intersection(set2) # {3, 4}
set1 & set2
difference = set1.difference(set2) # {1, 2}
set1 - set2
symmetric difference
set1 ^ set2
DICTIONARY:
A collection of key-value pairs
Keys must be unique
Represented by { }
Mutable
Created using the dict() function
Example: {1: “a”, 2: “b”, 3: “c”, 4: “d”, 5: “e”}
record = {
'id': 1,
'name': 'John Doe',
'email': '[email protected]',
'age': 30
}
dict_example = {"name": "Alice", "age": 25, "is_student": False}
dict_example["age"] = 26 # Update value
dict_example["city"] = "New York" # Add a new key-value pair
GLOBAL VARIABLES: Variables declared outside a function
LOCAL VARIABLES: Variables declared inside a function
/ represents precise division (result is a floating point number)
// represents floor division (result is an integer)
5//2 = 2
5/2 = 2.5
EXCEPTIONAL HANDLING:
3 main keywords i.e. try, except, and finally
Used to catch exceptions and handle the recovering mechanism accordingly
Try is the block of a code that is monitored for errors.
Except block gets executed when an error occurs.
Two kinds of errors:
syntax errors and exceptions
Exceptions:
Error in the code
10 * (1/0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
10 * (1/0)
~^~
ZeroDivisionError: division by zero
Exception handling
try:
result = 10 * (1 / 0)
print("Result:", result)
except ZeroDivisionError as e:
print(f"Error: {e}. Division by zero is not allowed.")
Final output
Error: division by zero. Division by zero is not allowed.
LAMBDA:
A lambda function is an anonymous function. It can have any number of parameters but one
statement.
Example:
a = lambda x, y : x*y
print(a(7, 19))
NEGATIVE INDEX:
Negative numbers mean that you count from the right instead of the left Example: list[-1]
refers to the last element
LOOP CONTROL STATEMENTS:
Break - terminate the loop or statement
Continue - Forces to execute the next iteration of the loop
Pass - Performing no operation
USER-DEFINED FUNCTIONS:
def keyword is used to declare user-defined functions
Syntax:
def function_name():
statements
.
.
Example:
def fun():
print("Inside function")
fun()
CLASS:
Blueprint for creating objects
CONSTRUCTOR:
Special method called when an object is created
Purpose - assign values to the data members within the class when an object is initialized
__init__()
All classes have a function called __init__(), which is always executed when the class is being
initiated.
It is used to initialize objects of a class.
It is also called a constructor.
SELF:
Represents the instance of class
Allows you to access variables, attributes, and methods of a defined class
OBJECTS:
Variables that contain data and functions that can be used to manipulate the data
Parameter - variable listed inside the parentheses in the function definition
argument - value that is sent to the function when it is called
FUNCTION:
Set of statements that take inputs, do some specific computation, and produce output
Put some commonly or repeatedly done tasks together and make a function so that instead
of writing the same code again and again for different inputs, we can call the function.
Functions that readily come with Python are called built-in functions.
Eg: print()
strip() - remove the whitespace or the characters that are passed in the argument.
split() - split the string into substrings.
end=' ' indicates that the end character has to be identified by whitespace and not a
newline.
Zip - is an in-built function in Python used to iterate over multiple iterables.
We can also create your own functions known as user-defined functions.
CONTROL STRUCTURES
Sequential - a set of statements whose execution process happens in a sequence.
Selection - This structure is used for making decisions by checking conditions and
branching.
Only if
if-else
The nested if
The complete if-elif-else
Repetition – Used to repeat a certain set of statements.
The for loop
The while loop
DATA TYPE AND VARIABLE
Data type identifies the type of data that a variable can store.
A variable is basically an object or an element that we store in the memory.
sqlite3 library - allows the program to interact with a SQLite database.
DJANGO
Python framework that makes it easier to create web sites using Python.
Django models act as the interface between the database and the server code.
Django is a high-level Python web framework that enables rapid development of secure and
maintainable websites.
Manage.py
Running the development server. Doing database migrations.
URLs
URLs are used to route users to the appropriate content or functionality when they visit a
web application.
Views
Functions or classes in Django that handle HTTP requests and determine what data or
content should be sent back to the client.
models.py
Defines the structure of the application's database.
PANDAS
Pandas is a Python library used for working with data sets.
Created by Wes McKinney in 2008.
Data structures of pandas
Series
It is a one-dimensional array holding data of any type.
DataFrame
Like a 2-dimensional array, or a table with rows and columns.
Three main components: the data, the index, and the columns.
NumPy
Numerical Python, is an open-source Python library that provides support for scientific
computing and mathematical tasks
MATPLOTLIB
Low-level graph plotting library in python that serves as a visualization utility.
Open source
CLASSIFICATION
Assigning data into predefined categories based on specific attributes.
CLUSTERING
Groups data into clusters based on similarities without predefined labels