Python Notes
Python is a high-level, interpreted, general-purpose programming language.
Created by Guido van Rossum and first released in 1991, Python's design
philosophy emphasizes code readability through its notable use of significant
indentation.
Why Python?
1. Easy to Learn: Syntax is similar to English, making it accessible for beginners.
2. Versatile: Used in Web Development, Data Science, AI, Automation, and more.
3. Massive Community: A huge ecosystem of libraries (NumPy, Pandas, Django)
and support.
4. Cross-Platform: Runs on Windows, macOS, Linux, and Raspberry Pi.
Key Features
Interpreted: Code is executed line-by-line, which makes debugging easier.
Dynamically Typed: You don't need to declare the type of a variable when you
create one.
High-level: You don't have to worry about complex tasks like memory
management.
Extensive Standard Library: Offers "batteries included" functionality for tasks
like file I/O and networking.
Hello World
The simplest program in Python:
print("Hello, World!")
Python Notes 1
Output:
Hello, World!
Variables and Data Types
Variables are containers for storing data values. Python has no command for
declaring a variable; it is created the moment you first assign a value to it.
Data Type Example Description
int X=5 Whole numbers
float y = 2.5 Dcimal numbers
Sequence of Characters
str name = “Hello”
(String)
bool is_true = True Logical Values (True/False)
Basic Example
n=7
st = 'Hi'
st1 = "Student's"
print(n)
print(st,end=" ")
print(st1)
print()
print(st,st1)
Input & Output
7
Hi Student's
Hi Student's
Reading Input from user
st = input("Enter Value: ")
n = int(input("Enter num: "))
Python Notes 2
f = float(input("Enter decimal: "))
print(st)
print(type(st))
print(n)
print(type(n))
print(f)
print(type(f))
Input & Output
Enter Value: Hi
Enter num: 8
Enter decimal: 7.980
Hi
<class 'str'>
8
<class 'int'>
7.98
<class 'float'>
Reading Multiple Variables
a,b,c = map(int,input().split())
print(a+b+c)
Input & Output
12 34 56
102
Output Formatting
1. F- String Format
name = input("Enter name: ")
age = int(input("Enter Age: "))
print(f"This is {name}, I'm {age} yrs old.")
Python Notes 3
Input & Output
Enter name: Charlie
Enter Age: 15
This is Charlie, I'm 15 yrs old.
2. .format Method
name = input("Enter name: ")
age = int(input("Enter Age: "))
print("This is {}, I'm {} yrs old".format(name,age))
Input & Output
Enter name: Charlie
Enter Age: 19
This is Charlie, I'm 19 yrs old
3. Modulo Format
name = input("Enter name: ")
age = int(input("Enter Age: "))
print("This is %s, I'm %d yrs old"%(name,age))
Input & Output
Enter name: Charlie
Enter Age: 19
This is Charlie, I'm 19 yrs old
Operators
1. Arithmetic: +, -, *, /, % (modulus), ** (exponent), // (floor division).
2. Comparison: ==, !=, >, <, >=, <=.
3. Logical: and, or, not.
Example
Python Notes 4
p = float(input())
r = float(input())
t = int(input())
rate = (r/100)
CI = p*(1+rate)**t
print("%0.2f"%CI)
Input & Output
1000.0
5.0
2
1102.50
Conditional Statements
Used to perform different actions based on different conditions.
Example
age = 18
if age >= 18:
print("You are an adult.")
elif age > 12:
print("You are a teenager.")
else:
print("You are a child.")
Output
You are an adult
Loops
For loop
Python Notes 5
Used for iterating over a sequence (like a list, tuple, or string).
for i in range(5): # Iterates 0 to 4
print(i)
Output
0
3
4
for i in range(n,0,-1): # Iterates fromm 4 to 1
print(i)
Output
3
2
While Loop
Executes a set of statements as long as a condition is true.
count = 1
while count <= 3:
print("Count is:", count)
count += 1
Output
Count is: 1
Python Notes 6
Count is: 2
Count is: 3
List
Lists are used to store multiple items in a single variable. They are ordered and
mutable (changeable).
fruits = ["apple", "banana", "cherry"]
print(fruits)
fruits[0] = "orange" # This workss
print(fruits)
[Link]("grape")
print(fruits)
Output
["apple", "banana", "cherry"]
["orange", "banana", "cherry"]
["orange", "banana", "cherry",”grape”]
1. Adding Elements
These methods allow you to grow your list by adding single items or entire
sequences.
append(x): Adds an item to the end of the list.
fruits = ['apple', 'banana']
[Link]('cherry')
# Result: ['apple', 'banana', 'cherry']
extend(iterable): Appends all elements from another list (or any iterable) to the
current list.
Python Notes 7
fruits = ['apple', 'banana']
[Link](['cherry', 'orange'])
# Result: ['apple', 'banana', 'cherry', 'orange']
insert(i, x): Inserts an item at a specific index.
fruits = ['apple', 'banana']
[Link](1, 'orange')
# Result: ['apple', 'orange', 'banana']
2. Removing Elements
Use these methods when you need to clean up or extract data from your list.
remove(x): Removes the first occurrence of the value x. Raises an error if the
item isn't found.
numbers = [1, 2, 3, 2]
[Link](2)
# Result: [1, 3, 2]
pop([i]): Removes and returns the item at the given position. If no index is
specified, it removes the last item.
fruits = ['apple', 'banana', 'cherry']
last_item = [Link]()
# last_item is 'cherry', fruits is ['apple', 'banana']
clear(): Removes all items from the list, leaving it empty.
fruits = ['apple', 'banana']
[Link]()
# Result: []
3. Finding and Counting
Python Notes 8
These methods help you locate data or determine how often a value appears.
index(x): Returns the index of the first occurrence of x.
colors = ['red', 'blue', 'green']
print([Link]('blue')) # Output: 1
count(x): Returns the number of times x appears in the list.
grades = ['A', 'B', 'A', 'C']
print([Link]('A')) # Output: 2
4. Reordering and Copying
These methods change the structure or order of your list.
sort(key=None, reverse=False): Sorts the list in place (modifies the original
list).
nums = [3, 1, 4, 2]
[Link]()
# Result: [1, 2, 3, 4]
reverse(): Reverses the elements of the list in place.
nums = [1, 2, 3]
[Link]()
# Result: [3, 2, 1]
copy(): Returns a shallow copy of the list.
original = [1, 2, 3]
new_list = [Link]()
Tuple
Python Notes 9
What is a Tuple?
A tuple is a built-in data type in Python used to store multiple values in a single
variable.
🔹 Tuples are:
Ordered → elements have a fixed position (index)
Immutable → cannot be changed after creation
Allow duplicates
Can store different data types
Creating a Tuple
# Empty tuple
t1 = ()
# Tuple with values
t2 = (10, 20, 30)
# Tuple with mixed data types
t3 = (1, "Python", 3.5)
# Tuple without parentheses (tuple packing)
t4 = 10, 20, 30
Accessing Tuple Elements
t = (10, 20, 30, 40)
print(t[0]) # 10
print(t[-1]) # 40
Immutability Example
Python Notes 10
t = (10, 20, 30)
t[1] = 50 # ❌ Error: TypeError (tuples cannot be modified)
In-Built Methods of Tuple
1. count()
🔹 Purpose: Counts how many times a value appears in the tuple.
Syntax:
[Link](value)
Example:
t = (10, 20, 10, 30, 10)
print([Link](10)) # Output: 3
2. index()
🔹 Purpose: Returns the index of the first occurrence of a value.
Syntax:
[Link](value)
Example:
t = (10, 20, 30, 40)
print([Link](30)) # Output: 2
If the value does not exist:
[Link](50) # ❌ ValueError
Useful Operations on Tuples (Not Methods)
Python Notes 11
Length of Tuple
t = (1, 2, 3)
print(len(t)) # 3
Tuple Concatenation
t1 = (1, 2)
t2 = (3, 4)
print(t1 + t2) # (1, 2, 3, 4)
Repetition
t = (5,)
print(t * 3) # (5, 5, 5)
Why Use Tuples?
✔ Faster than lists
✔ Data protection (cannot be modified)
✔ Used for fixed data (coordinates, days, months)
Set
What is a Set in Python?
A set is a built-in Python data type used to store multiple unique values in a
single variable.
🔹 Sets are:
Unordered → no fixed index
Mutable → elements can be added or removed
Do NOT allow duplicates
Unindexed
Python Notes 12
Creating a Set
# Empty set (use set(), not {})
s1 = set()
# Set with values
s2 = {10, 20, 30}
# Duplicate values are removed automatically
s3 = {1, 2, 2, 3}
print(s3) # {1, 2, 3}
Accessing Elements
Sets cannot be accessed using index.
for i in s2:
print(i)
In-Built Methods of Set (With Basic Examples)
1. add()
➕ Adds a single element.
s = {1, 2, 3}
[Link](4)
print(s) # {1, 2, 3, 4}
2. update()
➕ Adds multiple elements.
Python Notes 13
s = {1, 2}
[Link]([3, 4, 5])
print(s) # {1, 2, 3, 4, 5}
3. remove()
❌ Removes a specific element (error if not found).
s = {10, 20, 30}
[Link](20)
print(s) # {10, 30}
4. discard()
❌ Removes an element (NO error if not found).
s = {10, 20, 30}
[Link](40) # No error
print(s)
5. pop()
❌ Removes and returns a random element.
s = {1, 2, 3}
[Link]()
print(s)
6. clear()
🧹 Removes all elements.
s = {1, 2, 3}
[Link]()
print(s) # set()
Python Notes 14
Set Operations
7. union()
Returns all elements from both sets.
a = {1, 2}
b = {2, 3}
print([Link](b)) # {1, 2, 3}
8. intersection()
Returns common elements.
print([Link](b)) # {2}
9. difference()
Returns elements present in first set but not second.
print([Link](b)) # {1}
10. symmetric_difference()
Returns elements not common in both sets.
print(a.symmetric_difference(b)) # {1, 3}
Relationship / Checking Methods
11. issubset()
a = {1, 2}
b = {1, 2, 3}
Python Notes 15
print([Link](b)) # True
12. issuperset()
print([Link](a)) # True
13. isdisjoint()
x = {1, 2}
y = {3, 4}
print([Link](y)) # True
What is a Dictionary in Python?
A dictionary is a built-in Python data type used to store data in key–value pairs.
🔹 Dictionaries are:
Unordered (before Python 3.7), ordered (from Python 3.7+)
Mutable → can be changed
Keys are unique
Values can be duplicated
Creating a Dictionary
# Empty dictionary
d1 = {}
# Dictionary with values
student = {
"name": "Seema",
Python Notes 16
"age": 21,
"course": "Python"
}
Accessing Dictionary Elements
print(student["name"]) # Seema
print([Link]("age")) # 21
🔹 Difference:
dict[key] → Error if key not found
get(key) → Returns None (no error)
Modifying a Dictionary
student["age"] = 22 # Update
student["college"] = "ABC" # Add new key
In-Built Methods of Dictionary (With Examples)
1. keys()
Returns all keys.
print([Link]())
2. values()
Returns all values.
print([Link]())
3. items()
Python Notes 17
Returns key–value pairs.
print([Link]())
4. get()
Returns value of a key.
print([Link]("course")) # Python
5. update()
Updates dictionary with new key–value pairs.
[Link]({"age": 23, "city": "Hyderabad"})
6. pop()
Removes specified key and returns its value.
[Link]("age")
7. popitem()
Removes last inserted item.
[Link]()
8. clear()
Removes all items.
[Link]()
9. copy()
Returns a shallow copy.
Python Notes 18
new_student = [Link]()
10. setdefault()
Returns value if key exists; otherwise adds key with default value.
[Link]("gender", "Female")
11. fromkeys()
Creates a new dictionary from keys.
keys = ("id", "name", "salary")
emp = [Link](keys, 0)
print(emp)
Looping Through Dictionary
for key in student:
print(key, student[key])
Example Program
marks = {
"Math": 90,
"Science": 85,
"English": 88
}
total = 0
for m in [Link]():
total += m
print("Total Marks:", total)
Python Notes 19
Why Use Dictionary?
✔ Fast data retrieval
✔ Easy data mapping
✔ Real-world use (student details, JSON, configs)
Functions
What is a Function?
A function is a block of reusable code that performs a specific task.
Functions help in code reusability, readability, and modularity.
Syntax of a Function
def function_name(parameters):
statement(s)
return value
Example: Simple Function
def add(a, b):
return a + b
result = add(10, 20)
print(result) # 30
Types of Functions
1. Function without parameters
def greet():
print("Hello, Welcome!")
Python Notes 20
greet()
2. Function with parameters
def square(n):
return n * n
print(square(5)) # 25
3. Function with default arguments
def power(a, b=2):
return a ** b
print(power(5)) # 25
print(power(5, 3)) # 125
4. Function with return statement
def even_odd(n):
if n % 2 == 0:
return "Even"
return "Odd"
print(even_odd(7))
Anonymous Function
What is an Anonymous Function?
An anonymous function is a function without a name.
In Python, it is created using the lambda keyword.
Python Notes 21
🔹 Used for short, one-line operations.
Syntax
lambda arguments : expression
Example: Lambda Function
add = lambda a, b: a + b
print(add(5, 3)) # 8
Lambda with map()
numbers = [1, 2, 3, 4]
squares = list(map(lambda x: x*x, numbers))
print(squares)
Lambda with reduce()
from functools import reduce
numbers = [1, 2, 3, 4]
sum_all = reduce(lambda a, b: a + b, numbers)
print(sum_all)
Recursion
Python Notes 22
What is Recursion?
Recursion is a technique where a function calls itself to solve a problem.
🔹 Every recursive function must have:
1. Base condition – stops recursion
2. Recursive call – function calls itself
Syntax
deffunction():
if condition:# base case
return value
return function()# recursive call
Example: Factorial Using Recursion
def factorial(n):
if n == 1:
return 1
return n * factorial(n-1)
print(factorial(5)) # 120
Example: Fibonacci Using Recursion
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n-1) + fibonacci(n-2)
Python Notes 23
print(fibonacci(6)) # 8
Example: Sum of Numbers Using Recursion
def sum_n(n):
if n == 0:
return 0
return n + sum_n(n-1)
print(sum_n(5)) # 15
Advantages & Disadvantages of Recursion
✅ Advantages
Simple and clean code
Useful for tree, graph problems
❌ Disadvantages
Slower than loops
Risk of stack overflow
Python Notes 24