Python notes
Variables in Python
What is a Variable?
A variable is a name used to store data in memory. It acts like a labeled container that holds a value.
For example, you can store a person's name, age, marks, or any other information in a variable.
name = "Abhishek"
age = 21
Here:
namestores a string.agestores an integer.
Why Do We Use Variables?
To store data for later use.
To make programs dynamic.
To avoid repeating values.
To make code easier to read and manage.
Rules for Naming Variables
A variable name can contain letters, digits, and underscores (
_).It must start with a letter or underscore.
It cannot start with a digit.
Variable names are case-sensitive.
Python keywords cannot be used as variable names.
Valid Examples
name = "Abhishek"
_age = 21
total_marks = 450
Invalid Examples
2name = "Abhishek" # Starts with a number
first-name = "Abhi" # Hyphen not allowed
class = 10 # Keyword
Primitive Data Types in Python
Primitive data types are the basic building blocks of Python. They store single values and are used to represent numbers, text, and logical values.
Python's main primitive data types are:
int(Integer)float(Floating-point number)complex(Complex number)str(String)bool(Boolean)
1. Integer (int)
An integer is a whole number without a decimal point.
age = 21
temperature = -5
population = 1000000
Features of Integers
Store positive, negative, or zero values.
Have unlimited size in Python.
Used for counting, indexing, and mathematical calculations.
Immutable (cannot be changed after creation).
x = 10
y = x + 5
print(y) # 15
Common Operations
a = 10
b = 3
print(a + b) # Addition
print(a - b) # Subtraction
print(a * b) # Multiplication
print(a / b) # Division
print(a // b) # Floor Division
print(a % b) # Modulus
print(a ** b) # Exponentiation
2. Float (float)
A float is a number that contains a decimal point.
price = 99.99
pi = 3.14159
Features of Floats
Represent real numbers.
Can store decimal values.
Used in scientific calculations and measurements.
Immutable.
height = 5.8
weight = 72.5
Important Note
Due to internal binary representation, some decimal values may not be stored exactly.
print(0.1 + 0.2) # 0.30000000000000004
3. Complex (complex)
A complex number has two parts:
Real part
Imaginary part
It is written in the form:
a + bj
num = 3 + 4j
Here:
3is the real part.4jis the imaginary part.
Accessing Parts
print(num.real) # 3.0
print(num.imag) # 4.0
Use Cases
Electrical engineering
Signal processing
Scientific computing
4. String (str)
A string is a sequence of characters enclosed in quotes.
name = "Abhishek"
message = 'Hello'
A string can contain:
Letters
Numbers
Symbols
Spaces
text = "Python 3.14 is awesome!"
Key Features of Strings
Ordered collection of characters.
Immutable (cannot be changed after creation).
Supports indexing and slicing.
Can store any textual data.
String Indexing
Each character in a string has a position called an index.
Indexing starts from
0.Negative indexing starts from
-1.
word = "Python"
print(word[0]) # P
print(word[1]) # y
print(word[-1]) # n
print(word[-2]) # o
String Slicing
Slicing extracts a part of a string.
text = "Python"
print(text[0:3]) # Pyt
print(text[2:]) # thon
print(text[:4]) # Pyth
print(text[::2]) # Pto
print(text[::-1]) # nohtyP
Syntax
string[start:stop:step]
start→ starting indexstop→ ending index (excluded)step→ jump size
Common String Operations
first = "Hello"
second = "World"
print(first + " " + second) # Concatenation
print(first * 3) # Repetition
print("H" in first) # Membership
print(len(first)) # Length
Important String Methods
Case Conversion
text = "python programming"
print(text.upper())
print(text.lower())
print(text.title())
print(text.capitalize())
print(text.swapcase())
Searching and Finding
text = "Python Programming"
print(text.find("Pro"))
print(text.index("P"))
print(text.count("m"))
Checking Methods
print("Python".isalpha())
print("123".isdigit())
print("Python123".isalnum())
print("python".islower())
print("PYTHON".isupper())
print(" ".isspace())
Replace and Split
text = "I love Java"
print(text.replace("Java", "Python"))
print(text.split())
Join
words = ["I", "love", "Python"]
print(" ".join(words))
Removing Extra Spaces
text = " Python "
print(text.strip())
print(text.lstrip())
print(text.rstrip())
Escape Characters in Strings
print("Hello
World")
print("Hello World")
print("He said, \"Python is great!\"")
5. Boolean (bool)
A boolean represents one of two values:
TrueFalse
is_logged_in = True
is_completed = False
Why Booleans Are Important
Used in decision-making.
Control program flow.
Essential for conditions and loops.
age = 20
print(age >= 18) # True
Boolean Operations
print(True and False)
print(True or False)
print(not True)
Truthy and Falsy Values
Values treated as False:
00.0""(empty string)[](empty list){}(empty dictionary)NoneFalse
Everything else is generally treated as True.
print(bool(0))
print(bool("Hello"))
print(bool([]))
Summary of Primitive Data Types
| Data Type | Description | Example |
|---|---|---|
int |
Whole numbers | 10 |
float |
Decimal numbers | 3.14 |
complex |
Complex numbers | 2 + 3j |
str |
Text | "Python" |
bool |
Logical values | True |
Collection Data Types in Python
Collection data types are used to store multiple values under a single variable name. Instead of creating separate variables for each value, we can group related data together in one collection.
Python provides four main built-in collection data types:
List
Tuple
Set
Dictionary
Each collection type has its own features and use cases.
1. List
What is a List?
A list is an ordered, mutable (changeable) collection of items.
This means:
Ordered: Items keep their position.
Mutable: You can change, add, or remove items after creation.
Allows duplicates: Same value can appear multiple times.
0-indexed: The first item is at index
0.
fruits = ["apple", "banana", "mango"]
Characteristics of a List
Stores multiple values in one variable.
Can contain different data types.
Supports indexing and slicing.
Dynamic in size.
data = [10, "Python", True, 3.14]
Creating a List
numbers = [1, 2, 3, 4]
empty_list = []
Accessing List Elements
fruits = ["apple", "banana", "mango"]
print(fruits[0]) # apple
print(fruits[-1]) # mango
Slicing a List
print(fruits[0:2]) # ['apple', 'banana']
Changing List Elements
fruits[1] = "orange"
Adding Elements
append() – Add one element at the end
fruits.append("grapes")
extend() – Add multiple elements
fruits.extend(["kiwi", "papaya"])
insert() – Add element at a specific position
fruits.insert(1, "pineapple")
Removing Elements
pop() – Remove element by index
fruits.pop() # Removes last element
fruits.pop(1) # Removes element at index 1
remove() – Remove by value
fruits.remove("apple")
del – Delete element or entire list
del fruits[0]
del fruits
Useful List Methods
numbers = [4, 2, 8, 1]
numbers.sort()
numbers.reverse()
count = numbers.count(2)
index = numbers.index(8)
numbers.clear()
2. Tuple
What is a Tuple?
A tuple is an ordered, immutable collection of items.
This means:
Ordered: Items maintain their order.
Immutable: Cannot be changed after creation.
Allows duplicates.
0-indexed.
colors = ("red", "green", "blue")
Creating a Tuple
numbers = (1, 2, 3)
single = (5,)
A single-element tuple must include a comma.
Accessing Tuple Elements
print(colors[0])
print(colors[-1])
Tuple Methods
Tuples have only two methods:
numbers.count(2)
numbers.index(3)
List vs Tuple
| Feature | List | Tuple |
|---|---|---|
| Mutable | Yes | No |
| Syntax | [] |
() |
| Methods | Many | Few |
| Performance | Slightly slower | Faster |
| Use Case | Dynamic data | Fixed data |
3. Set
What is a Set?
A set is an unordered, mutable collection of unique items.
This means:
Unordered: No fixed position.
Mutable: Can add or remove items.
No duplicates allowed.
Not indexed.
numbers = {1, 2, 3, 4}
Creating a Set
fruits = {"apple", "banana", "mango"}
empty_set = set()
{}creates an empty dictionary, not a set.
Adding Elements
fruits.add("orange")
fruits.update(["grapes", "kiwi"])
Removing Elements
fruits.remove("apple")
fruits.discard("banana")
fruits.pop()
fruits.clear()
Common Set Operations
1. Union
Union combines all unique elements from both sets.
print(A | B)
print(A.union(B))
Output:
{1, 2, 3, 4, 5, 6}
Use union when you want everything from both sets without duplicates.
2. Intersection
Intersection returns only the elements that are present in both sets.
print(A & B)
print(A.intersection(B))
Output:
{3, 4}
Use intersection when you want common elements.
3. Difference
Difference returns elements that are in the first set but not in the second.
print(A - B)
print(A.difference(B))
Output:
{1, 2}
Similarly:
print(B - A)
Output:
{5, 6}
Order matters in difference.
4. Symmetric Difference
Symmetric difference returns elements that are in either set, but not in both.
print(A ^ B)
print(A.symmetric_difference(B))
Output:
{1, 2, 5, 6}
It removes the common elements and keeps only unique ones.
Update Methods (Modify the Original Set)
Unlike the operations above, these methods change the original set directly.
5. update()
Adds all elements from another set.
A = {1, 2, 3}
B = {3, 4, 5}
A.update(B)
print(A)
Output:
{1, 2, 3, 4, 5}
6. intersection_update()
Keeps only common elements.
A = {1, 2, 3, 4}
B = {3, 4, 5}
A.intersection_update(B)
print(A)
Output:
{3, 4}
7. difference_update()
Removes elements found in another set.
A = {1, 2, 3, 4}
B = {3, 4}
A.difference_update(B)
print(A)
Output:
{1, 2}
8. symmetric_difference_update()
Keeps only non-common elements.
A = {1, 2, 3}
B = {3, 4, 5}
A.symmetric_difference_update(B)
print(A)
Output:
{1, 2, 4, 5}
Quick Summary
| Operation | Symbol | Method | Result | |
|---|---|---|---|---|
| Union | ` | ` | union() |
All unique elements |
| Intersection | & |
intersection() |
Common elements | |
| Difference | - |
difference() |
Elements in first set only | |
| Symmetric Difference | ^ |
symmetric_difference() |
Non-common elements |
Update Methods Summary
| Method | Purpose |
|---|---|
update() |
Add all elements |
intersection_update() |
Keep common elements |
difference_update() |
Remove common elements |
symmetric_difference_update() |
Keep non-common elements |
Real-Life Example
english = {"apple", "banana", "mango"}
hindi = {"banana", "mango", "grapes"}
print("Union:", english | hindi)
print("Intersection:", english & hindi)
print("Difference:", english - hindi)
Output:
Union: {'apple', 'banana', 'mango', 'grapes'}
Intersection: {'banana', 'mango'}
Difference: {'apple'}
Key Takeaways
Sets are unordered.
Sets store unique values only.
Duplicate values are automatically removed.
Standard set operations return a new set.
Update methods modify the original set.
Sets are extremely useful when working with unique data, filtering duplicates, and performing mathematical comparisons between collections.
4. Frozen Set
What is a Frozen Set?
A frozenset is an immutable version of a set.
Unordered
No duplicates
Cannot be modified after creation
fs = frozenset([1, 2, 3, 4])
Set vs Frozen Set
| Feature | Set | Frozen Set |
|---|---|---|
| Mutable | Yes | No |
| Add/Remove | Yes | No |
| Hashable | No | Yes |
| Use as Dictionary Key | No | Yes |
5. Dictionary
What is a Dictionary?
A dictionary stores data in key-value pairs.
Each key maps to a value.
student = {
"name": "Abhishek",
"age": 21,
"course": "Python"
}
Features of Dictionary
Ordered (Python 3.7+)
Mutable
Keys must be unique
Values can be duplicated
Accessed using keys, not indexes
Rules for Keys
Keys must be immutable.
Valid key types: string, number, tuple.
Lists and sets cannot be keys.
Accessing Values
print(student["name"])
print(student.get("age"))
Adding and Updating Items
student["city"] = "Delhi"
student["age"] = 22
Removing Items
student.pop("age")
student.popitem()
del student["name"]
student.clear()
Useful Dictionary Methods
student.keys()
student.values()
student.items()
student.update({"grade": "A"})
Common Use Cases of Dictionary
Storing structured data
Mapping values
Counting frequency
Representing real-world objects
Fast data lookup
Summary
List: Ordered, mutable, allows duplicates.
Tuple: Ordered, immutable, allows duplicates.
Set: Unordered, mutable, unique items only.
Frozen Set: Unordered, immutable, unique items only.
Dictionary: Key-value pairs, mutable, fast lookup.
Control Flow Statements in Python
What are Control Flow Statements?
Control flow statements determine the order in which code is executed. They allow a program to make decisions, repeat tasks, and execute different blocks of code based on conditions. In simple words, control flow statements help us control how our program runs.
Why are They Important?
They make programs interactive and dynamic.
They allow decision-making based on different situations.
They help automate repetitive tasks.
They improve code efficiency and reduce duplication.
Decision-Making Statements
if Statement
The if statement executes a block of code only when a specified condition is True.
age = 18
if age >= 18:
print("You are eligible to vote.")
Use Case: When you want to perform an action only if a condition is satisfied.
if...else Statement
The if...else statement executes one block of code if the condition is True and another block if it is False.
age = 16
if age >= 18:
print("You can vote.")
else:
print("You cannot vote yet.")
Use Case: When there are two possible outcomes.
if... elif... ,else Ladder
This is used when multiple conditions need to be checked.
marks = 85
if marks >= 90:
print("Grade A")
elif marks >= 75:
print("Grade B")
elif marks >= 50:
print("Grade C")
else:
print("Fail")
Use Case: When you need to choose one option from many conditions.
Loops in Python
Loops are used to execute a block of code repeatedly until a specified condition becomes false. They save time and reduce repetitive code.
Basic Components of a Loop
Initialization – Starting point of the loop
Condition – Determines how long the loop will run
Updation – Changes the loop variable after each iteration
for Loop
The for loop is used when the number of iterations is known in advance.
for i in range(1, 6):
print(i)
Output: 1 2 3 4 5
How it works:
range(1, 6)generates values from 1 to 5Loop runs once for each value
Use Case: When you know exactly how many times the loop should run.
while Loop
The while loop executes as long as the condition remains True.
i = 1
while i <= 5:
print(i)
i += 1
Use Case: When the number of iterations is not known beforehand.
Comparison of Loops
for loop: Best when the number of iterations is known
while loop: Best when the number of iterations is unknown
Advantages of Control Flow Statements
Enable decision-making in programs
Reduce code repetition
Improve program flexibility
Make code easier to manage and maintain
Allow efficient handling of different scenarios
Real-Life Examples
Checking login credentials using if...else
Assigning grades using if...elif...else
Displaying numbers using loops
Processing items in a shopping cart
Repeating tasks such as sending notifications
Important Notes
Python uses indentation instead of curly braces to define blocks of code
Conditions evaluate to True or False
breakis used to exit a loop earlycontinueis used to skip the current iteration
Functions in Python
What is a Function?
A function is a reusable block of code that performs a specific task. Instead of writing the same code multiple times, we can write it once inside a function and use it whenever needed. Functions help make code more organized, reusable, and easier to maintain.
Why Do We Need Functions?
They reduce code repetition
They make programs easier to read
They help organize large programs into smaller parts
They make debugging and maintenance simpler
Basic Structure of a Function
A function generally has three main parts:
defkeyword – used to define a functionFunction Name – the name used to identify the function
Function Body – the block of code that runs when the function is called
def greet():
print("Hello!")
In this example:
defis the keywordgreetis the function nameThe indented code is the function body
How to Call a Function
Defining a function only creates it. To execute it, we must call it.
greet()
Output:
Hello!
Parameters and Arguments
Parameters
Parameters are variables defined in the function definition.
def greet(name):
print("Hello", name)
Here, name is a parameter.
Arguments
Arguments are the actual values passed to the function when calling it.
greet("Abhishek")
Here, "Abhishek" is an argument.
Types of Functions in Python
1. Built-in Functions
These are functions already provided by Python.
print("Hello")
len([1, 2, 3])
Use Case: Used for common operations like printing, length, type conversion.
2. User-defined Functions
Functions created by the programmer using def.
def add(a, b):
return a + b
print(add(2, 3))
Use Case: When you need custom logic.
3. Lambda Functions (Anonymous Functions)
Small, one-line functions without a name.
square = lambda x: x * x
print(square(5))
Features:
Short and concise
No
defkeywordUsed for simple operations
Use Case: Best for short operations, especially with functions like map, filter.
Types of Arguments in Python
1. Positional Arguments
Arguments are passed in order.
def info(name, age):
print(name, age)
info("Abhishek", 20)
2. Keyword Arguments
Arguments are passed using parameter names.
info(age=20, name="Abhishek")
3. Default Arguments
Parameters have default values.
def greet(name="User"):
print("Hello", name)
greet()
greet("Abhishek")
4. Variable-Length Arguments (*args)
Used to pass multiple values (tuple form).
def numbers(*args):
print(args)
numbers(1, 2, 3, 4)
Output:
(1, 2, 3, 4)
Use Case: When number of inputs is unknown.
5. Keyword Variable-Length Arguments (**kwargs)
Used to pass multiple key-value pairs (dictionary form).
def details(**kwargs):
print(kwargs)
details(name="Abhishek", age=20)
Output:
{'name': 'Abhishek', 'age': 20}
Use Case: When working with dynamic named data.
Return Statement
A function can return a value using return.
def multiply(a, b):
return a * b
result = multiply(3, 4)
print(result)
Advantages of Using Functions
Promote code reusability
Reduce repetition
Improve readability
Make code modular and organized
Simplify testing and debugging
Easier to maintain and update
Real-Life Example
def say_hello(name):
print(f"Hello, {name}!")
say_hello("Abhishek")
say_hello("Muskan")
say_hello("Rahul")
This avoids rewriting the same code multiple times.
Summary
A function is a reusable block of code that performs a specific task. Python supports different types of functions such as built-in, user-defined, and lambda functions. It also provides flexibility through parameters, arguments, *args, and **kwargs. Functions make code cleaner, reusable, and easier to manage in large programs.
