CHAPTER 1
What is Python? Python is a popular programming language. It was created by Guido van Rossum, and released in 1991.
PYTHON VARIABLES AND DATA TYPES - HI Welcome! If you're just starting out python. This guide will give you a quick overview of the fundamentals.
- Python is a powerfull,readable, and beginner-friendly programming language used in web development,AI,
- Data science and more.
- why python Simple and readable: beginner friendly syntax Stron community: Supportive and active developer base Massive ecosystem: Thousands of libraries and frameworks
Commom libraries
Area popular libraries
Web development django,Flask,fastApi data science pandas,Numpy,Matplotlib Machine learning scikit-learn,Pytorch,TensorFlow Automation Requestes,selenium,Pyautogui
HELLO WORLD EXAMPLE
python
print ("hello world")
In Python, variables are used to store data that can be referenced and manipulated later in your code. You don’t need to declare the type—Python is dynamically typed, so it figures it out for you.
Creating Variables
python name = "Arun" # string age = 20 # integer height = 5.6 # float is_student = True # boolean
Python uses =
to assign values.
Rules for Variable Names
-
Must start with a letter or an underscore (
_
) -
Cannot start with a number
-
Can contain letters, numbers, and underscores
-
Are case-sensitive (
Name
andname
are different)Valid:
python user_name = "Bob" _age = 30
Invalid:
python 2name = "Error" # starts with number user-name = "Error" # hyphen not allowed
Reassigning & Dynamic Typing
Variables can change type at runtime:
python
x = 42 # int x = "hello" # now it's a string
Variable Types (Built-in)
Type | Example |
---|---|
int |
x = 10 |
float |
pi = 3.14 |
str |
name = "Eve" |
bool |
is_valid = True |
list |
nums = [1, 2, 3] |
dict |
user = {"name": "Max"} |
Best Practices
- Use meaningful names (e.g.
user_age
instead ofua
) - Use snake_case for variable names
- Avoid using Python keywords as variable names (e.g.
class
,def
,if
)
Learn more in the Python Docs – Variables
In python, variables are used to store the data that can be referenced What is a variable ?
A Variable in python is like a container used to store data you can assign values using = operator
PYTHON
name = "Arun" age = 20 is_student = True
Python is a dynamically typed language, which means you don't need to declare a variable's type explicitly. Python has several built-in data types categorized into different classes.
Type | Description | Example |
---|---|---|
int |
Integer numbers | x = 42 |
float |
Floating point numbers (decimals) | pi = 3.14 |
complex |
Complex numbers | z = 2 + 3j |
Type | Description | Example |
---|---|---|
str |
Unicode strings | name = "Alice" |
Type | Description | Example |
---|---|---|
bool |
True or False values | is_valid = True |
- Ordered, mutable, allows duplicates.
python fruits = ["apple", "banana", "cherry"]
- Ordered, immutable, allows duplicates.
python dimensions = (1920, 1080)
- Unordered, no duplicates.
python colors = {"red", "green", "blue"}
- Key-value pairs, unordered (Python 3.6+ preserves order).
python person = {"name": "Alice", "age": 30}
Type | Description | Example |
---|---|---|
NoneType |
Represents the absence of a value | result = None |
bytes |
Immutable byte sequences | data = b"hello" |
bytearray |
Mutable byte sequences | arr = bytearray(5) |
range |
Represents a range of numbers | range(0, 10) |
Use the built-in type()
and isinstance()
functions:
python type(42) # <class 'int'> isinstance(42, int) # True
Optional type hints using the typing
module:
python def greet(name: str) -> str: return f"Hello, {name}"
Category | Types |
---|---|
Numeric | int , float , complex |
Text | str |
Sequence | list , tuple , range |
Set | set , frozenset |
Mapping | dict |
Boolean | bool |
Binary | bytes , bytearray , memoryview |
Special | NoneType |
In Python, variables are used to store data. Naming variables properly is essential for readable and maintainable code.
- Must start with a letter (
A–Z
,a–z
) or an underscore (_
) - Can contain letters, digits (
0–9
), and underscores (_
) - Case-sensitive (
name
,Name
, andNAME
are different variables) - Cannot be a Python keyword
python
name = "Arun" _age = 20 user_1 = "admin" pi_value = 3.1415
python 2cool = "nope" # Starts with a digit first-name = "John" # Hyphen not allowed class = "Physics" # 'class' is a reserved keyword
-
Use lowercase letters and underscores for variable names:
python user_name = "arun" total_amount = 100.0
-
Use UPPER_CASE for constants:
python MAX_RETRIES = 5
-
Avoid using:
- Single characters like
l
,O
, orI
(easily confused with numbers) - Ambiguous names like
data1
,data2
, etc.
- Single characters like
These are built-in and have special meaning in Python:
( False, None, True, and, as, assert, break, class, continue, def, del, elif, else, except, finally, for, from, global, if, import, in, is, lambda, nonlocal, not, or, pass, raise, return, try, while, with, yield )
You can get the full list programmatically:
python import keyword print(keyword.kwlist)
Variable Name | Valid? | Reason |
---|---|---|
_user |
Starts with underscore | |
user_123 |
Alphanumeric + _ |
|
123user |
Starts with digit | |
user-name |
Hyphen not allowed | |
def |
Python keyword |
In Python, variables are used to store data values. You do not need to declare the data type explicitly—Python automatically detects the type based on the value assigned.
python variable_name = value
- variable_name: the name you give to the variable.
- =: the assignment operator.
- value: the data you want to store.
python
age = 25
name = "Arun"
price = 19.99
is_active = True
- Must start with a letter or underscore (
_
) - Can contain letters, numbers, and underscores
- Case-sensitive (
name
andName
are different) - Should not use reserved keywords (like
class
,if
,for
)
python x = 10 print(type(x)) # <class 'int'>
x = "Python" print(type(x)) # <class 'str'>
- Use meaningful names (
user_name
instead ofx
) - Use snake_case for variable names (e.g.,
total_amount
) - Use lowercase letters (constants can be in UPPERCASE)
python
age = 20
height = 5.9
name = "Arun"
is_student = True
hobbies = ["reading", "coding", "gaming"]
user = { "name": "Arun", "age": 21, "is_student": True }
print(name, age, height, is_student) print("Hobbies:", hobbies) print("User Info:", user)
Arun 21 5.9 True Hobbies: ['reading', 'coding', 'gaming'] User Info: {'name': 'Arun', 'age': 21, 'is_student': True}
- No need to use
var
,int
,string
, etc. - Use descriptive names (
name
,hobbies
) instead ofx
,a1
. - Python uses dynamic typing — you can change the type later.
Use the print()
function to display variable values in the console.
python name = "Arun" age = 21
print(name) print(age)
print("Name:", name) print("Age:", age)
print(f"My name is {name} and I am {age} years old.")
Arun 21 Name: Arun Age: 21 My name is Arun and I am 21 years old.
Python has several built-in data types used to store values of different kinds:
Type | Example | Description |
---|---|---|
int |
x = 10 |
Integer numbers |
float |
y = 3.14 |
Decimal numbers |
complex |
z = 2 + 3j |
Complex numbers |
bool |
flag = True |
Boolean (True / False ) |
str |
name = "Alice" |
Text or string values |
Type | Example | Description |
---|---|---|
list |
fruits = ["apple", "banana"] |
Ordered, mutable collection |
tuple |
coords = (10, 20) |
Ordered, immutable collection |
set |
ids = {1, 2, 3} |
Unordered, unique values |
dict |
person = {"name": "Bob"} |
Key-value pairs |
python print(type(10)) # <class 'int'> print(type("hello")) # <class 'str'>
python int("5") # → 5 str(10) # → "10" list("abc") # → ['a', 'b', 'c']
Sure! Here's a short and GitHub-friendly explanation of the comma operator in Python:
In Python, the comma (,
) is not an operator like in C/C++.
Instead, it's used to create tuples or separate values in function arguments, assignments, and loops.
python
a = 1, 2, 3 print(type(a)) # <class 'tuple'>
x, y = 10, 20
def add(a, b): return a + b
result = add(5, 7)
for i, val in enumerate(['a', 'b']): print(i, val)
- Comma is a separator, not an operator.
- Often used to create tuples or unpack variables.
In Python, commas inside print()
separate multiple values and insert a space between them.
python
name = "Arun" age = 25
print("Name:", name, "| Age:", age)
Output:
Name: Arun | Age: 25
- Commas let you print different types (like strings + numbers) without converting them.
- Adds automatic spaces between items.
Python’s print() function has two useful optional parameters:
sep
: Defines the separator between multiple items.end
: Defines what to print at the end of the output (default is a newline\n
).
By default, print() separates multiple arguments with a space.
python print("Python", "is", "awesome")
You can change the separator using sep
:
python print("Python", "is", "awesome", sep="-")
By default, print()
ends with a newline (\n
):
python print("Hello") print("World")
You can change this using end
:
python print("Hello", end=" ") print("World")
python print("2025", "07", "04", sep="-", end="!\n")
Use sep
and end
to format output without string concatenation!
python print("Hello", "World", "2025", sep=" - ")
Output:
Hello - World - 2025
The sep
parameter sets the separator between printed values.
python print("Hello", end=" ") print("World!")
Output:
Hello World!
end=" "
keeps the cursor on the same line with a space instead of a newline.
f-Strings (formatted string literals) make it easy to include variables and expressions inside strings using {}
.
Available from Python 3.6+.
python name = "Arun" print(f"Hello, {name}!")
Output:
Hello, Arun!
Just add an f
before the opening quote, and put variables or expressions inside {}
.
python a = 5 b = 10 print(f"The sum of {a} and {b} is {a + b}")
Output:
The sum of 5 and 10 is 15
python pi = 3.14159 print(f"Value of pi: {pi:.2f}")
Output:
Value of pi: 3.14
python from datetime import datetime today = datetime.now() print(f"Today's date: {today:%Y-%m-%d}")
Output:
Today's date: 2025-07-04
f-Strings are:
- Faster and more readable than
format()
or%
formatting - Great for inline calculations and formatting
python name = "Arun" print(f"Hello, {name}!")
Output:
Hello, Arun!
🔹 f-strings let you insert variables directly into strings using {}
.
Use the built-in round()
function:
python num = 3.14159 rounded = round(num, 2) print(rounded)
Output:
3.14
round(number, 2) rounds the number to 2 decimal places.
CHAPTER 2
Comments are notes in your code to explain what it does. They are ignored by the Python interpreter.
Use the #
symbol:
python
print("Hello, World!") # This prints a message
Python doesn’t have official multi-line comment syntax, but you can use multiple #
:
python
print("Done")
Or use a docstring (not recommended unless for documentation):
python """ This is a multi-line string which can act like a comment """
Note: Triple-quoted strings are not true comments — they are stored as string objects if not assigned.
- Use comments to explain why, not what (if code is self-explanatory)
- Keep them short and clear
- Update comments when code changes
Comments are used to:
- Explain code for better readability
- Make the code easier to understand and maintain
- Help other developers (and your future self) know why something was done
- Temporarily disable code during debugging
Comments are ignored by the Python interpreter.
python
print("Welcome to Python!")
🔹 The #
makes everything after it a comment (ignored by Python).
Use the *
operator to repeat a string:
python print("Hello " * 3)
Output:
Hello Hello Hello
The *
operator repeats the string n times.
You can use triple quotes ('''
or """
) to create a multi-line string:
python message = """Hello, This is a multi-line string in Python.""" print(message)
Output:
Hello, This is a multi-line string in Python.
🔹 Triple quotes preserve line breaks and spacing.
Type casting means converting a value from one data type to another (e.g., int
to float
, str
to int
, etc.).
Python provides built-in functions for casting:
Function | Converts to... |
---|---|
int() |
Integer |
float() |
Floating point |
str() |
String |
bool() |
Boolean |
python
num = int("10") # 10
x = int(3.7) # 3
y = float(5) # 5.0
text = str(123) # "123"
val = bool(1) # True
Type casting may raise errors if the conversion is invalid:
python int("abc") # ValueError
- Accepting user input (
input()
returns a string) - Mathematical operations
- Data processing and validation
To calculate total salary, you typically use:
total_salary = basic_salary + allowances - deductions
Where:
- basic_salary: Fixed base salary
- allowances: Extra income (e.g., HRA, travel, etc.)
- deductions: Amounts subtracted (e.g., tax, PF, etc.)
You can use variables and simple arithmetic to compute this.
python
basic_salary = 25000 allowances = 5000 deductions = 3000
total_salary = basic_salary + allowances - deductions
print(f"Total Salary: ₹{total_salary}")
Total Salary: ₹27000
You can also use input()
to take user input for dynamic salary calculation:
python basic = float(input("Enter basic salary: ")) allow = float(input("Enter allowances: ")) deduct = float(input("Enter deductions: "))
total = basic + allow - deduct print(f"Total Salary: ₹{total}")
Example: B coverting string to float
The following code converts Ivan's salary from a string to float;otherwise, the program generates an error. Arun's wage is not enclosed with a double quote;therefore, it is already a number and doesn't need to be covrerted
calculator.py
salary_ivan=3200 salary_Arun="2800" total_salary=salary_ivan+float(salary_Arun) print("Total salaries:$",total_salary)
OUTPUT
Total salaries:$6000.0
Example: C coverting string to Int
To calculate the age difference between two individuals, you must covert the second age to int type because the second age is a string
calculate.py
age1=22 age2"34" age_difference=int(age2)-age1 print("Age Difference:",age_difference)
OUTPUT
Age Difference: 12
CHAPTER 3
Escape sequences are special characters used in strings to represent characters that are otherwise difficult to include directly, like newlines, tabs, quotes, etc.
They begin with a backslash (\
).
Escape | Meaning | Example Output |
---|---|---|
\n |
New line | Splits the text to a new line |
\t |
Tab (horizontal) | Adds a tab space |
\\ |
Backslash | Prints \ character |
\' |
Single quote | Prints ' in a string |
\" |
Double quote | Prints " in a string |
python
print("Hello\nWorld") # New line print("Python\tRocks") # Tab space print("He said: "Yes"") # Double quotes inside string print('It's awesome!') # Single quote inside string
Hello World Python Rocks He said: "Yes" It's awesome!
You can also use raw strings (r"..."
) to ignore escape sequences.
python print(r"This is a raw string:\nNo new line here.")
🧾 Output:
This is a raw string:\nNo new line here.
Test your knowledge of escape sequences! Choose the correct output or fill in the blanks.
python print("Hello\nPython")
A. Hello Python B. Hello\nPython C. Hello Python D. Error
✅ Answer: C
A. \n B. \t C. \n D. \b
✅ Answer: B
QUIZ: 2
He said: "Hello"
python print("He said: _______")
✅ Answer: "He said: "Hello""
python print('It's easy!')
A. It's easy! B. Its easy! C. It's easy! D. Error
✅ Answer: A
Scenario: You're building a Python program to display the total weight of 3 people inside a lift. Use escape sequences to format the output nicely.
Fill in the blanks ( ___ ) to complete the program.
python
person1 = 65.5 person2 = 72.0 person3 = 58.3
total_weight = person1 + person2 + person3
print("Lift Weight Report\n") print("Person 1:\t", person1, "kg") print("Person 2:\t", person2, "kg") print("Person 3:\t", person3, "kg") print("\nTotal:\t\t", total_weight, "kg")
-
What does \n do in the print statement?
- A. Adds a new line
- B. Adds a tab
- C. Prints a slash
- D. None of the above
-
What is the purpose of \t in this code?
- A. New paragraph
- B. Adds a tab space for alignment
- C. Skips the line
- D. None
-
What is the total weight calculated in the program?
Lift Weight Report
Person 1: 65.5 kg Person 2: 72.0 kg Person 3: 58.3 kg
Total: 195.8 kg
** Objective:**
Practice using escape sequences (\n
, \t
) along with print()
, type()
, and variables.
-
Declare 3 different variables with different data types.
-
Use print() to:
- Show each variable's value
- Show its type
- Use \n for new lines and \t for indentation
-
Try to format the output to look clean and readable.
python
name = "Alice" age = 25 height = 5.4
print("Variable Info:\n")
print("Name:\t", name) print("Type:\t", type(name), "\n")
print("Age:\t", age) print("Type:\t", type(age), "\n")
print("Height:\t", height) print("Type:\t", type(height), "\n")
Variable Info:
Name: Alice Type: <class 'str'>
Age: 25 Type: <class 'int'>
Height: 5.4 Type: <class 'float'>
- Try with bool and list types too.
- Use f-strings instead of commas in print() for cleaner formatting.
** Task:** Use \n (new line) and \t (tab) escape sequences to print the following triangle shape:
*
* *
* * *
* * * *
python
print("\t\t\t*") print("\t\t * *") print("\t * * *") print(" * * * *")
- Use \t for horizontal spacing (tab).
- Use \n if printing all lines together in a single
print()
statement. - Try modifying the shape or adding more lines!
CHAPTER 4
Operators are special symbols used to perform operations on variables and values.
Used for basic math.
Operator | Description | Example |
---|---|---|
+ | Addition | 3 + 2 = 5 |
- | Subtraction | 5 - 1 = 4 |
* | Multiplication | 4 * 2 = 8 |
/ | Division | 10 / 2 = 5.0 |
// | Floor Division | 10 // 3 = 3 |
% | Modulus (Remainder) | 10 % 3 = 1 |
** | Exponentiation | 2 ** 3 = 8 |
Compare two values and return True
or False
.
Operator | Description | Example |
---|---|---|
== |
Equal to | 5 == 5 → True |
!= |
Not equal to | 3 != 4 → True |
> |
Greater than | 7 > 2 → True |
< |
Less than | 2 < 5 → True |
>= |
Greater or equal | 5 >= 5 → True |
<= |
Less or equal | 4 <= 6 → True |
Used to assign values.
Operator | Meaning | Example |
---|---|---|
= |
Assign | x = 10 |
+= |
Add and assign | x += 5 → x = x + 5 |
-= |
Subtract and assign | x -= 3 → x = x - 3 |
*= |
Multiply and assign | x *= 2 |
/= |
Divide and assign | x /= 4 |
Used to combine conditions.
Operator | Description | Example |
---|---|---|
and |
True if both are true | x > 5 and x < 10 |
or |
True if one is true | x < 3 or x > 8 |
not |
Reverses the result | not(x == 5) |
Used to compare object identity.
Operator | Meaning | Example |
---|---|---|
is |
True if same object | x is y |
is not |
True if not same | x is not y |
Check if a value exists in a sequence.
Operator | Meaning | Example |
---|---|---|
in |
Value exists | "a" in "apple" |
not in |
Value does not exist | "z" not in "apple" |
python x = 10 y = 5
print(x + y) # Arithmetic print(x > y) # Comparison print(x == 10 and y == 5) # Logical x += 2 # Assignment print(x)
a = 10 b = 3
print("Addition:", a + b)
print("Subtraction:", a - b)
print("Multiplication:", a * b)
print("Division:", a / b)
print("Floor Division:", a // b)
print("Modulus:", a % b)
print("Exponentiation:", a ** b)
The modulus operator % returns the remainder of a division.
python print(10 % 3) # Output: 1
Here, 10 ÷ 3 = 3 with a remainder of 1 → so 10 % 3 gives 1.
-
Check if a number is even/odd:
python print(7 % 2) # Output: 1 → odd print(8 % 2) # Output: 0 → even
-
Looping in cycles, e.g.,
i % 4
cycles 0,1,2,3,0,... -
Useful in clock-based logic or round-robin systems.
python
a = 17 b = 5
result = a % b print("Remainder:", result) # Output: 2
Explanation: 17 ÷ 5 = 3 remainder 2, so 17 % 5 = 2.
Floor division returns the quotient of a division, rounded down to the nearest whole number.
python a // b
a = 17 b = 5
result = a // b print("Quotient:", result) # Output: 3
Explanation: 17 ÷ 5 = 3.4 → floor division 17 // 5 = 3 (rounds down).
Common use: Get whole number part of a division without decimals.
The assignment operator =
is used to assign a value to a variable.
x = 10 # Assigns 10 to variable x print("x =", x)
python x += 5 # x = x + 5 x -= 2 # x = x - 2 x *= 3 # x = x * 3 x /= 2 # x = x / 2
Tip: Assignment operators help update variable values concisely.
x = 5 print("x =", x) # Output: x = 5
This assigns the value 5 to the variable x.
greeting = "Hello, " + "World!" print(greeting) # Output: Hello, World!
message = "Hello" message += ", Python!" print(message) # Output: Hello, Python!
Tip:
-
- creates a new string
- += updates the existing string variable
Useful for building strings in loops or step-by-step.
Example for concatenate strings using "+"
first = "Hello" second = "World" result = first + " " + second print(result) # Output: Hello World
A short example for concatenating strings using +=
:
text = "Hello" text += " World" print(text) # Output: Hello World
+= adds " World" to the existing text string.
CHAPTER 5
Comparison operators are used to compare values. They return either True or False.
Operator | Meaning | Example |
---|---|---|
== |
Equal to | 5 == 5 → True |
!= |
Not equal to | 5 != 3 → True |
> |
Greater than | 7 > 2 → True |
< |
Less than | 3 < 4 → True |
>= |
Greater than or equal | 5 >= 5 → True |
<= |
Less than or equal | 2 <= 3 → True |
a = 10 b = 5
print(a > b) # True print(a == b) # False
Tip: Commonly used in if
statements, loops, and filters.
A short example for comparison operators in Python:
a = 7 b = 5
print(a > b) # True print(a == b) # False
Compares values and returns True or False.
Logical operators are used to combine conditional statements. They return True or False.
Operator | Description | Example |
---|---|---|
and |
True if both are True | True and False → False |
or |
True if at least one is True | True or False → True |
not |
Reverses the result | not True → False |
python a = 5 b = 10
print(a > 2 and b > 8) # True print(a < 3 or b == 10) # True print(not(a == b)) # True
Tip: Used in if statements to combine multiple conditions.
A short example for logical operators in Python:
python
x = 10 y = 5
print(x > 5 and y < 10) # True print(x < 5 or y == 5) # True print(not(x == y)) # True
Combines conditions using and, or, not.
Identity operators are used to compare the memory location of two objects.
Operator | Description | Example |
---|---|---|
is |
Returns True if both refer to same object |
a is b |
is not |
Returns True if they are different objects |
a is not b |
a = [1, 2, 3] b = a c = [1, 2, 3]
print(a is b) # True (same object) print(a is c) # False (different object with same value) print(a is not c) # True
Note: Use == to compare values, is to compare identity.
A short example for identity operators in Python:
a = [1, 2] b = a c = [1, 2]
print(a is b) # True print(a is c) # False print(a is not c) # True
is
checks if both refer to the same object in memory.
Membership operators are used to check if a value exists in a sequence (like a list, string, tuple, etc).
Operator | Description | Example |
---|---|---|
in |
Returns True if value is present |
"a" in "apple" → True |
not in |
Returns True if value is not present |
3 not in [1, 2, 4] → True |
fruits = ["apple", "banana", "cherry"]
print("apple" in fruits) # True print("grape" not in fruits) # True
Tip: Great for searching in strings, lists, and other collections.
A short quiz on arithmetic operators:
What will be the output of the following code?
x = 8 y = 3 print(x % y + x // y)
A. 3 B. 5 C. 4 D. 6
A short quiz on the assignment operator:
Question: What will be the output of the following code?
x = 10 x += 5 print(x)
A. 10 B. 5 C. 15 D. Error
Answer: C. 15
Explanation: x += 5
means x = x + 5
, so 10 + 5 = 15
.
Sure! Here's a short quiz for comparison operators in Python:
** Quiz: Comparison Operator in Python**
Question: What will be the output of the following code?
x = 10 y = 20 print(x > y)
A. True B. False C. 10 D. 20
Correct Answer: B. False
Explanation: 10 > 20
is not true, so it returns False
.
Question: What will be the output of the following code?
x = [1, 2, 3] y = x z = [1, 2, 3]
print(x is y) print(x is z)
Options:
A) True
True
B) True
False
C) False
True
D) False
False
Answer: B) True False
Explanation:
x is y
→True
becausey
refers to the same object asx
.x is z
→False
becausez
is a new list with the same values, but it's a different object in memory.
Python uses the input() function to get data from the user.
name = input("Enter your name: ") print("Hello,", name)
- input() always returns data as a string.
You can use string methods to manipulate text:
text = " python is FUN! "
print(text.strip()) # Removes leading/trailing spaces print(text.lower()) # Converts to lowercase print(text.upper()) # Converts to uppercase print(text.replace("FUN", "awesome")) # Replaces words
Join strings using +
or f-strings
:
first = "Hello" last = "World"
print(first + " " + last) # Using + print(f"{first} {last}!") # Using f-string
Tip: Always convert input to the needed type (e.g., int(input())
for numbers).
Python uses the input()
function to take input from the user.
name = input("Enter your name: ") print("Hello,", name)
- input() always returns a string.
- You can convert input to other types using
int()
,float()
, etc.
age = int(input("Enter your age: ")) print("You will be", age + 1, "next year.")
Example: To create a triangle using user input:
rows = int(input("Enter number of rows: "))
for i in range(1, rows + 1): print("*" * i)
If user enters 5
:
**
This prints a right-angled triangle of stars (*
).
Example: to calculate total weight using user input:
item1 = float(input("Enter weight of item 1 (kg): ")) item2 = float(input("Enter weight of item 2 (kg): ")) total = item1 + item2
print("Total weight:", total, "kg")
Enter weight of item 1 (kg): 2.5
Enter weight of item 2 (kg): 3.2
Total weight: 5.7 kg
Example: to check the variable types using type()
in Python:
name = "Alice" age = 25 height = 5.6 is_student = True
print(type(name)) # <class 'str'> print(type(age)) # <class 'int'> print(type(height)) # <class 'float'> print(type(is_student))# <class 'bool'>
<class 'str'> <class 'int'> <class 'float'> <class 'bool'>
Example for converting strings to integers using user input:
num = input("Enter a number: ")
num = int(num)
print("You entered:", num)
Note: input()
always returns a string. Use int()
to convert it to an integer.
explanation of strings and substrings in Python:
-
A string is a sequence of characters enclosed in quotes (' ' or " ").
-
Example:
message = "Hello, Python!"
-
A substring is a part of a string.
-
You can extract substrings using slicing:
text = "Programming" print(text[0:6]) # Output: Progra
-
You can also check if a substring exists:
"gram" in text # True
Tip: Python strings are zero-indexed.
Test it out:
word = "education" print(word[1:4]) # duc print("cat" in word) # True
Explanation of string indexing in Python:
- Indexing lets you access individual characters in a string.
- Index starts at 0 (zero-based indexing).
text = "Python" print(text[0]) # P print(text[5]) # n
- You can also use negative indexes to count from the end:
print(text[-1]) # n (last character) print(text[-3]) # h
Tip: Use indexes to loop, slice, or manipulate characters in strings.
A short example for string index:
name = "Python" print(name[0]) # Output: P print(name[3]) # Output: h print(name[-1]) # Output: n (last character)
This shows how to access characters using positive and negative indexes.
A explanation of substrings in Python:
-
A substring is a part of a string.
-
Use slicing to get substrings:
text = "HelloWorld" print(text[0:5]) # Output: Hello
-
Check if a substring exists:
print("World" in text) # True
Syntax: string[start:end] (start index is included, end index is excluded)
Try this:
word = "education" print(word[2:5]) # uca print("cat" in word) # True
explanation of using operators with strings in Python:
Python allows some operators to work with strings:
-
Joins two strings:
first = "Hello" second = "World" result = first + " " + second print(result) # Output: Hello World
-
Repeats a string multiple times:
text = "Hi " print(text * 3) # Output: Hi Hi Hi
-
Strings can be compared using
==
,!=
,<
,>
, etc.print("apple" == "apple") # True print("a" < "b") # True
Tip: Use +
to build strings, and *
to repeat patterns.
short example for comparing strings:
a = "apple" b = "banana"
print(a == b) # False print(a < b) # True (because "apple" comes before "banana")
You can use ==
, !=
, <
, >
, <=
, >=
to compare strings alphabetically.
Quick guide, perfect for dropping into a GitHub README.
Comparison | What it checks | Example | Result |
---|---|---|---|
== / != | Exact equality / inequality | "cat" == "cat" | True |
< > <= >= | Lexicographic (alphabetical) order, Unicode‐code‑point based | "apple" < "banana" | True |
casefold() | Case‑insensitive equality (better than lower() ) |
"straße".casefold() == "STRASSE".casefold() | True |
in | Substring membership | "py" in "python" | True |
if user_input == secret_word: print("Match!")
words = ["Banana", "apple", "Cherry"] print(sorted(words, key=str.casefold)) # ['apple', 'Banana', 'Cherry']
if name.casefold() == "alice": ...
import natsort from natsort import natsorted files = ["file10.txt", "file2.txt"] print(natsorted(files)) # ['file2.txt', 'file10.txt']
Remember
==
compares contents;is
compares object identity (don’t useis
for strings unless you really mean it).- Lexicographic order is Unicode‑based; for locale‑aware sorting (e.g., accented letters), use
locale.strxfrm
or a library likePyICU
.
s1, s2 = "Python", "python"
equal = s1 == s2 # False ci_equal = s1.casefold() == s2.casefold() # True before_after = s1 < s2 # True ('P' < 'p' in Unicode) contains = "tho" in s1 # True
Drop this snippet into your repo’s docs or README.md for an instant, developer‑friendly explanation of string comparison in Python.
text = "Python programming is fun" if "programming" in text: print("Found!")
Output:
Found!
Use in
to check if a substring exists.
Case-sensitive by default. Use .lower()
or .casefold()
for case-insensitive checks.
CHAPTER 6
Python provides many built-in string methods. Here's a quick reference:
Function | Description | Example |
---|---|---|
len() | Returns string length | len("Hello") → 5 |
.lower() / .upper() | Changes case | "Hi".lower() → "hi" |
.strip() | Removes spaces | " text ".strip() → "text" |
.replace() | Replaces part of string | "a-b".replace("-", ":") → "a:b" |
.split() | Splits into list | "a,b,c".split(",") → ['a', 'b', 'c'] |
.find() | Finds index of substring | "hello".find("l") → 2 |
.count() | Counts substring | "hello".count("l") → 2 |
.startswith() / .endswith() | Checks start/end | "file.txt".endswith(".txt") → True" |
message = " Hello Python! " print(message.strip().lower().replace("python", "world"))
Output:
hello world!
Most string methods don't change the original string — they return a new string. You can chain methods like
.strip().lower()
for clean processing.
name = " Hello World! "
cleaned = name.strip().lower().replace("world", "Python") print(cleaned)
Output:
hello python!
Used functions:
- .strip() → removes spaces
- .lower() → converts to lowercase
- .replace() → replaces text
##Example: Boolean Function in Python (GitHub-Friendly)
def is_even(n): return n % 2 == 0
print(is_even(4)) # True print(is_even(7)) # False
Explanation:
- is_even() returns a boolean (True or False)
- You can use it in conditions like if is_even(x): ...
Question: What will be the output of the following code?
text = " Hello, Python! " result = text.strip().replace("Python", "World").upper() print(result)
Options: A) HELLO, PYTHON! B) HELLO, WORLD! C) HELLO, WORLD! D) Hello, World!
** Answer:** B) HELLO, WORLD!
Explanation:
- strip() removes spaces
- replace("Python", "World") replaces the word
- upper() converts to uppercase
Sure! Here's a short quiz on string indexing in Python:
Question: What will be the output of the following code?
text = "Python" print(text[3])
Options: A) h B) t C) o D) n
** Answer:** A) h
Explanation:
- Indexing starts at 0
- text[3] gives the 4th character, which is 'h' in "Python"
Sure! Here's a short explanation of conditional statements in Python:
Conditional statements let your program make decisions based on conditions.
if condition: # code runs if condition is True elif another_condition: # runs if previous is False and this is True else: # runs if all conditions are False
age = int(input("Enter your age: "))
if age >= 18: print("You are an adult.") elif age > 12: print("You are a teenager.") else: print("You are a child.")
Sure! Here's a short explanation of the if
statement in Python:
The if statement is used to run code only if a condition is True.
if condition: # code to run if condition is True
age = 20
if age >= 18: print("You can vote.")
Output: You can vote.
Use if to control program flow based on conditions. Let me know if you need elif and else too!
a short explanation of the if-else statement in Python:
Use if-else to run one block if a condition is True, and another if it's False.
if condition: # runs if condition is True else: # runs if condition is False
age = 16
if age >= 18: print("Adult") else: print("Minor")
Output: Minor
short explanation of if-elif-else in Python:
Use if-elif-else to check multiple conditions in order.
if condition1: # runs if condition1 is True elif condition2: # runs if condition2 is True else: # runs if none are True
marks = 75
if marks >= 90: print("Grade A") elif marks >= 60: print("Grade B") else: print("Grade C")
Output: Grade B
It checks top-down and runs the first True block only.
Sure! Here's a short quiz on the if
statement in Python:
Question: What will be the output of this code?
x = 10
if x > 5: print("High")
Options: A) High B) Low C) Error D) Nothing is printed
** Answer:** A) High
Explanation: The condition x > 5 is True, so "High" is printed.
Here's a short quiz on the if-elif
statement:
Question: What will be the output of this code?
num = 0
if num > 0: print("Positive") elif num == 0: print("Zero")
Options: A) Positive B) Zero C) Negative D) Nothing is printed
✅ Answer: B) Zero
Explanation:
- num > 0 is False
- num == 0 is True, so "Zero" is printed.
Sure! Here's a short quiz on logical operators in Python:
Question: What will be the output of the following code?
x = 10 y = 5
if x > 5 and y < 10: print("Condition True") else: print("Condition False")
Options: A) Condition True B) Condition False C) Error D) No output
** Answer:** A) Condition True
Explanation:
- x > 5 → True
- y < 10 → True
- True and True → True
CHAPTER 7
loop statements in Python:
Loops are used to repeat a block of code multiple times.
Used to iterate over a sequence (like list, string, range).
for i in range(5): print(i)
Output: 0 1 2 3 4
Repeats as long as the condition is True.
i = 0 while i < 5: print(i) i += 1
Output: 0 1 2 3 4
Use break to stop a loop early, and continue to skip an iteration.
short explanation of the while
loop in Python:
The while loop runs a block of code as long as a condition is True
.
while condition: # code to repeat
i = 1 while i <= 3: print(i) i += 1
Output: 1 2 3
Use while when you don't know how many times to repeat in advance.
Short example using while True
in Python:
while True: user_input = input("Type something (or 'exit' to quit): ") if user_input.lower() == 'exit': print("Exiting the loop. Goodbye!") break else: print("You typed:", user_input)
- while True: creates an infinite loop.
- The break statement is used to exit the loop when the user types "exit".
This format is beginner-friendly and commonly used for input-based loops.
short example of the break statement in Python
while True: user_input = input("Type 'exit' to stop: ") if user_input == "exit": break print("You typed:", user_input)
print("Loop ended.")
- Keeps asking for input.
- Breaks the loop if the user types "exit".
A short example of the continue
statement in Python
for num in range(1, 6): if num == 3: continue # Skip number 3 print("Number:", num)
-
Loops from 1 to 5.
-
Skips printing number 3 using continue.
A short example of the
pass
statement in Python
for num in range(5): if num == 2: pass # Placeholder for future code print("Number:", num)
- Loops through 0 to 4.
- When num is 2, it does nothing and continues — pass acts as a placeholder.
A for loop is used to repeat a block of code a certain number of times, usually when working with sequences like lists, strings, or ranges.
for variable in sequence: # code to repeat
fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(fruit)
for i in range(5): print(i)
This prints: 0 1 2 3 4
- The loop automatically moves to the next item.
- Stops when all items are covered.
- Use range() to repeat something fixed number of times.
Example of the range() function with one parameter in a for
loop:
for i in range(5): print(i)
0 1 2 3 4
Explanation:
range(5) generates numbers from 0
to 4
(not including 5).
Example of range()
with two parameters:
for i in range(2, 6): print(i)
2 3 4 5
Explanation: range(2, 6) starts from 2 and goes up to 5 (6 is not included).
An example of range()
with three parameters:
for i in range(1, 10, 2): print(i)
1 3 5 7 9
Explanation: range(start, stop, step) This means: start at 1, go up to (but not include) 10, increment by 2.
A simple quiz question for the while
loop:
x = 0 while x < 3: print(x) x += 1
A. 0 1 2 3 B. 0 1 2 C. 1 2 3 D. Infinite loop
Correct Answer: B. 0 1 2
A short quiz on the break
statement in Python:
** Quiz: What will be the output of the following code?**
for i in range(5): if i == 3: break print(i)
A. 0 1 2 3 B. 0 1 2 C. 1 2 3 D. 0 1 2 3 4
** Correct Answer: B. 0 1 2**
The loop breaks when
i
is 3, so it doesn’t print 3. Only 0, 1, and 2 are printed.
A short quiz on the continue
statement in Python:
** Quiz: What will be the output of the following code?**
for i in range(5): if i == 2: continue print(i)
A. 0 1 2 3 4 B. 0 1 3 4 C. 1 2 3 4 D. 0 1 2 4
** Correct Answer: B. 0 1 3 4**
The continue skips the iteration when i == 2, so 2 is not printed.
A short quiz on the pass
statement in Python:
** Quiz: What will be the output of the following code?**
for i in range(3): if i == 1: pass print(i)
A. 0 1 2 B. 0 2 C. 1 D. 0 1
** Correct Answer: A. 0 1 2**
The
pass
statement does nothing — it's just a placeholder. So the loop runs normally and prints all values.
A quiz on the for
loop with range()
using one parameter:
** Quiz: What will be the output of the following code?**
for i in range(4): print(i)
A. 1 2 3 4 B. 0 1 2 3 C. 0 1 2 3 4 D. 1 2 3
** Correct Answer: B. 0 1 2 3**
range(4)
generates numbers starting from 0 up to 3 (but not including 4).
A quiz on the for
loop with range()
using two parameters:
** Quiz: What will be the output of the following code?**
for i in range(2, 6): print(i)
A. 2 3 4 5 6 B. 2 3 4 5 C. 3 4 5 6 D. 1 2 3 4 5
** Correct Answer: B. 2 3 4 5**
range(2, 6) starts from 2 and goes up to but not including 6.
Need one for range() with three parameters next?
A quiz on the for
loop with range()
using three parameters:
** Quiz: What will be the output of the following code?**
for i in range(1, 10, 3): print(i)
A. 1 4 7 10 B. 1 3 6 9 C. 1 4 7 D. 1 4 7 9
** Correct Answer: D. 1 4 7 9**
range(1, 10, 3) starts at 1, ends before 10, and increases by 3 each step → 1, 4, 7, 10 (but 10 is not included), so result is 1, 4, 7, 9.
CHAPTER 8
A explanation of **lists in Python:
A list in Python is a collection of items that is ordered, changeable (mutable), and allows duplicates.
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # Output: apple print(fruits[-1]) # Output: cherry (last item)
fruits[1] = "orange" print(fruits) # ['apple', 'orange', 'cherry']
fruits.append("mango") # Add to end fruits.insert(1, "grape") # Insert at position fruits.remove("apple") # Remove item
for fruit in fruits: print(fruit)
print(len(fruits)) # Number of items
my_list = [1, "hello", 3.14, True]
** Tip:** Lists are defined using square brackets []
and are one of the most flexible data structures in Python.
A short example of declaring and displaying a list in Python:
numbers = [10, 20, 30, 40]
print(numbers)
Output:
[10, 20, 30, 40]
A simple example of displaying a specific element from a list:
fruits = ["apple", "banana", "cherry"]
print(fruits[1])
Output:
banana
Remember: List indexing starts at 0, so
fruits[1]
gives the second item.
A simple example to display all elements in a list using a loop:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits: print(fruit)
Output:
apple banana cherry
This is the most common way to loop through and print all items in a list.
A short explanation on list modification in Python:
You can change list items because lists are mutable.
fruits = ["apple", "banana", "cherry"] fruits[1] = "orange" print(fruits) # ['apple', 'orange', 'cherry']
fruits.append("mango") # Add to end fruits.insert(1, "grape") # Add at position
fruits.remove("apple") # Remove by value fruits.pop() # Remove last item
Lists can grow, shrink, and change — great for dynamic data!
A short explanation on adding elements to a list in Python:
fruits = ["apple", "banana"] fruits.append("cherry") print(fruits) # ['apple', 'banana', 'cherry']
fruits.insert(1, "orange") print(fruits) # ['apple', 'orange', 'banana', 'cherry']
fruits.extend(["mango", "grape"]) print(fruits) # ['apple', 'orange', 'banana', 'cherry', 'mango', 'grape']
Use
append()
for single items,extend()
for adding multiple, andinsert()
to control position.
A short explanation on removing elements from a list in Python:
fruits = ["apple", "banana", "cherry"] fruits.remove("banana") print(fruits) # ['apple', 'cherry']
fruits.pop() # Removes 'cherry' fruits.pop(0) # Removes 'apple'
fruits = ["apple", "banana"] del fruits[1] # Deletes 'banana'
fruits.clear() print(fruits) # []
Use
remove()
by value,pop()
ordel
by index, andclear()
to wipe everything.
A explanation of other common list functions in Python:
fruits = ["apple", "banana", "cherry"] print(len(fruits)) # Output: 3
numbers = [5, 2, 9, 1] numbers.sort() print(numbers) # [1, 2, 5, 9]
nums = [3, 1, 4] print(sorted(nums)) # [1, 3, 4] print(nums) # [3, 1, 4] (original unchanged)
fruits.reverse() print(fruits) # ['cherry', 'banana', 'apple']
fruits = ["apple", "banana", "cherry"] print(fruits.index("banana")) # Output: 1
nums = [1, 2, 2, 3] print(nums.count(2)) # Output: 2
These functions help manage, search, and manipulate lists efficiently.
A short and clear explanation on adding elements to a list in Python:
You can add items to a list using three main methods:
fruits = ["apple", "banana"] fruits.append("cherry") print(fruits) # ['apple', 'banana', 'cherry']
fruits.insert(1, "orange") print(fruits) # ['apple', 'orange', 'banana', 'cherry']
fruits.extend(["mango", "grape"]) print(fruits) # ['apple', 'orange', 'banana', 'cherry', 'mango', 'grape']
Use
append()
for one item,insert()
to control position, andextend()
to add many at once.
A simple example of adding an element to the end of a list using append()
:
fruits = ["apple", "banana"]
fruits.append("cherry")
print(fruits)
Output:
['apple', 'banana', 'cherry']
append()
always adds the item to the end of the list.
A simple example of adding an element to a specific position in a list using insert()
:
fruits = ["apple", "banana", "cherry"]
fruits.insert(1, "orange")
print(fruits)
Output:
['apple', 'orange', 'banana', 'cherry']
insert(index, item)
places the item before the given index.
A simple example of adding multiple elements (a list) to another list using extend()
:
fruits = ["apple", "banana"]
more_fruits = ["cherry", "mango"]
fruits.extend(more_fruits)
print(fruits)
Output:
['apple', 'banana', 'cherry', 'mango']
extend()
adds each item from the second list to the first one — not as a sublist.
fruits = ["apple", "banana"] fruits.append(["cherry", "mango"]) print(fruits)
Output:
['apple', 'banana', ['cherry', 'mango']]
append()
adds the whole list as a single item, not individual elements.
A short and clear explanation on removing elements from a list in Python:
Python provides multiple ways to remove items from a list:
fruits = ["apple", "banana", "cherry"] fruits.remove("banana") print(fruits) # ['apple', 'cherry']
(If index is not given, removes the last item)
fruits = ["apple", "banana", "cherry"] fruits.pop(1) print(fruits) # ['apple', 'cherry']
fruits.pop() print(fruits) # ['apple']
fruits = ["apple", "banana", "cherry"] del fruits[0] print(fruits) # ['banana', 'cherry']
fruits = ["apple", "banana"] fruits.clear() print(fruits) # []
Use:
remove()
when you know the valuepop()
ordel
when you know the indexclear()
to empty the list
A simple example of removing elements from a list using different methods:
fruits = ["apple", "banana", "cherry"] fruits.remove("banana") print(fruits) # ['apple', 'cherry']
fruits = ["apple", "banana", "cherry"] fruits.pop(1) # Removes item at index 1 print(fruits) # ['apple', 'cherry']
fruits = ["apple", "banana"] fruits.clear() # Removes all elements print(fruits) # []
remove()
= by valuepop()
= by indexclear()
= remove all
removing an element by its position using the pop()
method:
fruits = ["apple", "banana", "cherry", "date"]
removed_item = fruits.pop(2)
print("Removed:", removed_item) print("Updated list:", fruits)
Removed: cherry
Updated list: ['apple', 'banana', 'date']
pop(index) removes the item at the given position and returns it. If the index doesn't exist, it will raise an IndexError.
removing all elements from a list using the .clear()
method:
numbers = [10, 20, 30, 40, 50]
numbers.clear()
print("List after clearing:", numbers)
List after clearing: []
- .clear() removes all elements from the list.
- The list still exists but becomes empty.
the number of elements in a list
numbers = [10, 20, 30, 40, 50]
count = len(numbers)
print("Number of elements in the list:", count)
Number of elements in the list: 5
sort a list of strings alphabetically
fruits = ["banana", "apple", "cherry", "date"]
fruits.sort()
print("Sorted list:", fruits)
Sorted list: ['apple', 'banana', 'cherry', 'date']
If you want to sort without changing the original list, use sorted()
instead:
sorted_fruits = sorted(fruits)
copy a list (GitHub-friendly):
original_list = [1, 2, 3, 4, 5]
copied_list = original_list.copy()
print("Original List:", original_list) print("Copied List:", copied_list)
Original List: [1, 2, 3, 4, 5] Copied List: [1, 2, 3, 4, 5]
copied_list = original_list[:]
copied_list = list(original_list)
The number of times a specific element appears in a list
colors = ["red", "blue", "green", "red", "yellow", "red"]
red_count = colors.count("red")
print("Number of times 'red' appears:", red_count)
To find the position (index) of an element in a list
fruits = ["apple", "banana", "cherry", "date"]
position = fruits.index("cherry")
print("Position of 'cherry':", position)
Position of 'cherry': 2
⚠ Note: Indexing starts from 0, and
.index()
gives the position of the first occurrence.
focused on displaying a list of freelancers (suitable for beginners):
You are given a list of freelancer names. Write a Python program to display each freelancer name one by one using a loop.
freelancers = ["Alice", "Bob", "Charlie", "Diana"]
Alice Bob Charlie Diana
Great! Here's a Python quiz for modifying a list of freelancers:
You are given a list of freelancers. Task: Add a new freelancer "Eve" to the end of the list and remove "Charlie" from the list.
freelancers = ["Alice", "Bob", "Charlie", "Diana"]
['Alice', 'Bob', 'Diana', 'Eve']
To test copying a list of freelancers:
You are given a list of freelancers. Task: Make a copy of the list and store it in a new variable called copied_freelancers. Then, print the copied list.
freelancers = ["Alice", "Bob", "Charlie", "Diana"]
['Alice', 'Bob', 'Charlie', 'Diana']
CHAPTER 9
To declare a dictionary in Python, with examples.
A dictionary is a collection of key-value pairs. It allows you to store and access data using keys instead of numeric indexes (like lists).
freelancer = { "name": "Alice", "skill": "Web Development", "experience": 3
}
print(freelancer["name"]) # Output: Alice print(freelancer["experience"]) # Output: 3
freelancer["location"] = "Chennai" # Add new key-value freelancer["experience"] = 4 # Update value del freelancer["skill"] # Remove a key
To find values by keys in a dictionary :
freelancer = { "name": "Alice", "skill": "Graphic Design", "experience": 5 }
print("Name:", freelancer["name"]) print("Skill:", freelancer["skill"]) print("Experience:", freelancer["experience"])
Name: Alice Skill: Graphic Design Experience: 5
You can also use .get() to avoid errors if the key doesn’t exist:
print(freelancer.get("location", "Not available"))
print the price of a product using a dictionary
product = { "name": "Laptop", "brand": "Dell", "price": 55000 }
print("Price of the product:", product["price"])
Price of the product: 55000
To display both keys and values from a dictionary
product = { "name": "Smartphone", "brand": "Samsung", "price": 20000 }
for key, value in product.items(): print(key, ":", value)
name : Smartphone brand : Samsung price : 20000
To add elements to a dictionary
product = { "name": "Headphones", "brand": "Sony" }
product["price"] = 1500 product["warranty"] = "1 year"
print(product)
{'name': 'Headphones', 'brand': 'Sony', 'price': 1500, 'warranty': '1 year'}
Example of removing elements from a dictionary in Python:
product_prices = { "apple": 30, "banana": 10, "orange": 25 }
removed_price = product_prices.pop("banana")
print("Removed price:", removed_price) print("Updated dictionary:", product_prices)
Removed price: 10 Updated dictionary: {'apple': 30, 'orange': 25}
- Using
del
keyword:
del product_prices["apple"]
- Using
clear()
to remove all items:
product_prices.clear()
A quiz on finding the number of elements in a dictionary:
students = { "Alice": 85, "Bob": 90, "Charlie": 78, "David": 92 }
print(len(students))
A) 3 B) 4 C) 5 D) Error
B) 4
len() returns the number of key-value pairs in the dictionary.
A short quiz on printing dictionary elements:
person = {"name": "John", "age": 25}
for k, v in person.items(): print(k, ":", v)
What is the output?
A) name age B) John 25 C)
name : John
age : 25
D) Error
C
Explanation of how to declare a function in Python:
def greet(): print("Hello, world!")
- def → keyword to define a function
- greet() → function name (can be any valid name)
- : → colon to start the function block
- print(...) → code that runs when the function is called
greet()
A example of a function that stores and displays contact data:
def contact_info(): contact = { "name": "Arun Kumar", "phone": "+91-9876543210", "email": "arun@example.com", "city": "Chennai" }
for key, value in contact.items():
print(key.title() + ":", value)
contact_info()
Name: Arun Kumar
Phone: +91-9876543210
Email: arun@example.com
City: Chennai
A explanation of a function without arguments in Python
A function without arguments means it doesn't take any input when called.
def say_hello(): print("Hello, welcome!")
say_hello()
- def say_hello(): → defines a function with no parameters.
- print(...) → code that runs when you call the function.
- say_hello() → calling the function to execute it.
A simple example of a function with one argument
A simple example of a function with one argument
def greet(name): print("Hello,", name)
greet("Arun")
Hello, Arun
A function with two arguments in Python:
def add_numbers(a, b): result = a + b print("Sum:", result)
add_numbers(5, 3)
- a and b are parameters (inputs).
- add_numbers(5, 3) passes two arguments.
- It prints: Sum: 8
A function that returns a value in Python:
A function can return a result using the return keyword.
def square(num): return num * num
result = square(4) print("Square is:", result)
- return num * num → sends the result back to where the function was called.
- result = square(4) → stores the returned value.
- Output: Square is: 16
A quiz based on a simple function calculator in Python:
def calculator(a, b, op): if op == "+": return a + b elif op == "-": return a - b else: return "Invalid operation"
print(calculator(10, 5, "-"))
A) 5 B) 15 C) -5 D) Invalid operation
A) 5
The function returns 10 - 5 which is 5.
CHAPTER 10
A short and clear explanation of exceptions in Python:
Exceptions are errors that happen during program execution. Python stops the program unless the error is handled.
try: num = int(input("Enter a number: ")) print(10 / num) except ZeroDivisionError: print("Cannot divide by zero!") except ValueError: print("Please enter a valid number.")
- try: Code that might cause an error
- except: Handles the error
- ZeroDivisionError, ValueError: Common exception types
A explanation syntax errors in Python
A syntax error happens when the Python code is not written correctly — it breaks the rules of the language.
if 5 > 3 print("Hello")
SyntaxError: expected ':'
if 5 > 3: print("Hello")
Syntax errors happen before the code runs. Python won’t run the program until the syntax is correct.
A explanation of runtime errors in Python
A runtime error happens while the program is running — the syntax is correct, but something goes wrong during execution.
num = int(input("Enter a number: ")) print(10 / num)
ZeroDivisionError: division by zero
- ZeroDivisionError` → Dividing by 0
- ValueError → Wrong data type
- IndexError → List index out of range
- TypeError → Invalid operation on wrong types
try: print(10 / int(input("Enter a number: "))) except ZeroDivisionError: print("Can't divide by zero!")
A explanation** of logical errors in Python
A logical error happens when the program runs without crashing, but the output is wrong due to a mistake in logic.
def calculate_area(length, width): return length + width # ❌ wrong logic (should be *)
print("Area:", calculate_area(4, 5))
Area: 9
def calculate_area(length, width): return length * width # ✔️ correct logic
Logical errors are the hardest to find because there’s no error message — you must test and debug your code carefully.
A explanation of a logical error
A logical error occurs when code runs without crashing but produces incorrect results. It means the logic of the code is flawed, not the syntax.
Example (Python):
def area(length, width): return length + width # Logical error: should be length * width
Note: Logical errors are hard to spot because the program runs normally — you must test outputs carefully!
division by zero to demonstrate error handling with try
/ except
def safe_divide(a, b): try: result = a / b print(f"Result: {result}") except ZeroDivisionError: print("Error: Cannot divide by zero.")
safe_divide(10, 2) # Output: Result: 5.0 safe_divide(5, 0) # Output: Error: Cannot divide by zero.
try
: runs code that might raise an error.except ZeroDivisionError
: catches the specific error and handles it gracefully.
Example of a TypeError in Python — along with how to handle it:
def add_numbers(a, b): return a + b
result = add_numbers(5, "3") # Can't add int and str
TypeError: unsupported operand type(s) for +: 'int' and 'str'
def add_numbers(a, b): try: return a + b except TypeError: print("Error: Both inputs must be numbers of the same type.")
print(add_numbers(5, 3)) # Output: 8 print(add_numbers(5, "3")) # Output: Error message
Example of an IndexError, and how to handle it:
fruits = ["apple", "banana", "cherry"]
print(fruits[5]) # Index 5 is out of range
IndexError: list index out of range
def get_fruit(index): fruits = ["apple", "banana", "cherry"] try: return fruits[index] except IndexError: return "Error: Index out of range."
print(get_fruit(1)) # Output: banana print(get_fruit(5)) # Output: Error message
try: # This will raise a ZeroDivisionError result = 10 / 0
# This will raise a NameError
print(unknown_variable)
except ZeroDivisionError: print("You can't divide by zero!")
except NameError: print("A variable used was not defined.")
except Exception as e: print(f"An unexpected error occurred: {e}")
else: print("Everything worked fine!")
finally: print("This will always run.")
- The code in the
try
block can raise different types of exceptions. - We handle specific exceptions (
ZeroDivisionError
,NameError
) separately. - The
Exception
block is a generic catch-all for anything unexpected. finally
runs no matter what — useful for cleanup (e.g., closing files or DB connections).
try: file = open("example.txt", "r") content = file.read() print("File content:") print(content)
except FileNotFoundError: print("The file was not found.")
finally: # This will run whether an exception occurred or not print("Closing the file (if it was opened).") try: file.close() except NameError: pass # file was never opened
- The
try
block attempts to open and read from a file. - If the file doesn't exist, a
FileNotFoundError
is raised and handled. - The
finally
block always executes — even if an exception was raised — ensuring resources are cleaned up (like closing the file).
Question: What will be the output of the following code?
try: result = 10 / 0 print("Result is:", result) except ZeroDivisionError: print("You can't divide by zero!")
A. Result is: 0
B. ZeroDivisionError
C. You can't divide by zero!
D. Program crashes
Correct Answer: C. You can't divide by zero!
Question: What will be the output of the following code?
my_list = [10, 20, 30] try: print(my_list[5]) except IndexError: print("Index out of range!")
A. 30
B. None
C. Index out of range!
D. Error in list
**Correct Answer: C. Index out of range!
Question: What will be the output of the following code?
try: number = int("abc") except: print("Something went wrong!")
A. abc
B. Something went wrong!
C. ValueError
D. Program crashes
**Correct Answer: B. Something went wrong!
This is because the int("abc")
raises a ValueError
, and the except
block catches it without specifying the error type.
CHAPTER 11
The random
module in Python is used to generate random numbers or make random selections.
When you write:
import random
You are telling Python to load the built-in random
module, so you can use its functions like:
Function | Description |
---|---|
random.random() |
Returns a random float between 0.0 and 1.0 |
random.randint(a, b) |
Returns a random integer between a and b (inclusive) |
random.choice(list) |
Randomly picks an element from a list |
random.shuffle(list) |
Randomly rearranges the items in a list |
random.uniform(a, b) |
Returns a random float between a and b |
import random
num = random.randint(1, 10) print("Random number:", num)
This will print a random number between 1 and 10.
The random.randrange()
function is used to generate a random number from a specific range.
It works like the range()
function, but picks one randomly.
random.randrange(start, stop, step)
start
– (optional) the beginning of the range (default is 0)stop
– (required) the end of the range (not included)step
– (optional) the difference between numbers (default is 1)
import random
num = random.randrange(1, 10) print(num)
This will print a random number from 1 to 9 (10 is not included).
random.randrange(0, 20, 2)
This returns a random even number between 0 and 18.
A short example using import random
:
import random
num = random.randint(1, 5) print("Random number:", num)
🎲 This prints a random number between 1 and 5.
A example of dice roll simulator using random
:
import random
dice = random.randint(1, 6) print("🎲 You rolled:", dice)
This simulates rolling a 6-sided dice. Each run gives a number between 1 and 6.
A example for rolling two dice:
import random
dice1 = random.randint(1, 6) dice2 = random.randint(1, 6)
print("🎲 Dice 1:", dice1) print("🎲 Dice 2:", dice2)
This simulates rolling two 6-sided dice.
Explanation of date and time
It helps you:
- Get the current date and time
- Format date and time
- Do date/time calculations (like yesterday/tomorrow)
- Convert between strings and dates
import datetime
import datetime
now = datetime.datetime.now() print("Current date and time:", now)
Output:
Current date and time: 2025-07-30 18:15:23.456789
CHAPTER 12
today = datetime.date.today() print("Today's date:", today)
time_now = datetime.datetime.now().time() print("Current time:", time_now)
d = datetime.date(2025, 7, 30) print("Specific date:", d)
t = datetime.time(14, 30, 0) print("Specific time:", t)
now = datetime.datetime.now()
formatted = now.strftime("%d-%m-%Y %H:%M:%S") print("Formatted:", formatted)
Common format codes:
%d
= Day%m
= Month%Y
= Year%H
= Hour%M
= Minute%S
= Second
from datetime import timedelta, date
today = date.today() tomorrow = today + timedelta(days=1) yesterday = today - timedelta(days=1)
print("Tomorrow:", tomorrow) print("Yesterday:", yesterday)
from datetime import datetime
date_str = "30-07-2025" date_obj = datetime.strptime(date_str, "%d-%m-%Y")
print("Converted date:", date_obj)
example for printing the current date in Python:
import datetime
today = datetime.date.today()
print("Today's date is:", today)
Output:
Today's date is: 2025-07-30
A example to print a selected date:
import datetime
selected_date = datetime.date(2025, 12, 25)
print("Selected date is:", selected_date)
Output:
Selected date is: 2025-12-25
You can change the values to any date you need.
A example of updating a selected date by adding or subtracting days using timedelta
:
import datetime
selected_date = datetime.date(2025, 12, 25) print("Original date:", selected_date)
updated_date = selected_date + datetime.timedelta(days=5) print("Updated date (after 5 days):", updated_date)
earlier_date = selected_date - datetime.timedelta(days=7) print("Updated date (before 7 days):", earlier_date)
Output:
Original date: 2025-12-25 Updated date (after 5 days): 2025-12-30 Updated date (before 7 days): 2025-12-18
This is useful for calculating deadlines, future events, or past dates. Let me know if you want to update months or years too (that needs a different approach).
A example of formatting a date using strftime
:
import datetime
today = datetime.date.today()
formatted_date = today.strftime("%d-%m-%Y") print("Formatted date:", formatted_date)
Output:
Formatted date: 30-07-2025
%d
– Day (01 to 31)%m
– Month (01 to 12)%Y
– Year (4 digits)%B
– Full month name (e.g., July)%A
– Full weekday name (e.g., Wednesday)
formatted = today.strftime("%A, %d %B %Y") print("Formatted date:", formatted)
Output:
Wednesday, 30 July 2025
A example for formatting the current date** in Python:
import datetime
today = datetime.date.today()
formatted_date = today.strftime("%d/%m/%Y")
print("Current date (formatted):", formatted_date)
Output:
Current date (formatted): 30/07/2025
print(today.strftime("%B %d, %Y")) # July 30, 2025
print(today.strftime("%Y-%m-%d")) # 2025-07-30
A example for formatting the current time in Python:
import datetime
now = datetime.datetime.now()
formatted_time = now.strftime("%H:%M:%S")
print("Current time (formatted):", formatted_time)
Output:
Current time (formatted): 18:45:10
%H
– Hour (00–23)%I
– Hour (01–12)%M
– Minute (00–59)%S
– Second (00–59)%p
– AM/PM
formatted_time_am_pm = now.strftime("%I:%M %p") print("Time with AM/PM:", formatted_time_am_pm)
Output:
Time with AM/PM: 06:45 PM
A example to format both current date and time using datetime
and strftime
:
import datetime
now = datetime.datetime.now()
formatted = now.strftime("%d-%m-%Y %H:%M:%S")
print("Formatted date and time:", formatted)
Output:
Formatted date and time: 30-07-2025 18:45:30
%d
– Day%m
– Month%Y
– Year%H
– Hour (24-hour)%M
– Minute%S
– Second
Python quiz on date:
What will be the output of the following code?
import datetime
d = datetime.date(2023, 1, 15) new_date = d + datetime.timedelta(days=10) print("Updated date:", new_date)
A) 2023-01-25 B) 2023-01-05 C) 2023-01-10 D) Error
A explanation of files, directories, and the os
module in Python:
Files are used to store data permanently (like .txt
, .csv
, etc.).
f = open("data.txt", "r") # "r" = read, "w" = write, "a" = append
content = f.read()
f.close()
CHAPTER 13
A directory is a container for files or other folders.
Example: C:/Users/John/Documents/
is a directory path.
Python's os
module lets you interact with the file system.
import os
print(os.getcwd())
print(os.listdir())
os.mkdir("new_folder")
print(os.path.exists("data.txt"))
To create directories (folders) in Python, you can use the os
module.
import os
os.mkdir("my_folder")
This will create a folder named my_folder
in the current directory.
import os
os.makedirs("parent/child/grandchild")
os.makedirs()
creates all intermediate folders if they don't exist.
import os
folder_name = "my_folder"
if not os.path.exists(folder_name): os.mkdir(folder_name) print("Folder created!") else: print("Folder already exists.")
A example for creating a directory in Python using the os
module:
import os
directory_name = "MyFolder"
os.mkdir(directory_name)
print(f"Directory '{directory_name}' created successfully!")
Note:
- This will create the folder in the current working directory.
- If the folder already exists, Python will throw a
FileExistsError
. - To create nested directories, use
os.makedirs()
instead.
A example for creating a subdirectory in Python:
import os
parent_dir = "MainFolder"
sub_dir = "SubFolder"
path = os.path.join(parent_dir, sub_dir)
os.makedirs(path)
print(f"Subdirectory '{sub_dir}' created inside '{parent_dir}' successfully!")
Notes:
-
os.makedirs()
will create both the parent folder and the subfolder if they don’t exist. -
If the folders already exist, it will raise an error unless you pass
exist_ok=True
like:os.makedirs(path, exist_ok=True)
A example to check if a directory exists in Python:
import os
directory_name = "MyFolder"
if os.path.exists(directory_name): print(f"Directory '{directory_name}' exists.") else: print(f"Directory '{directory_name}' does not exist.")
Tip: You can also check specifically if it’s a directory (not a file) using:
os.path.isdir(directory_name)
Removing directories depends on whether the directory is empty or contains files.
You can use os.rmdir()
for an empty directory:
import os
os.rmdir("MyFolder") # Deletes only if empty print("Empty directory removed.")
If the directory has files/subfolders, os.rmdir()
will throw an error.
You can use shutil.rmtree()
to delete a directory and everything inside it:
import shutil
shutil.rmtree("MyFolder") # Deletes folder even if it has files/subfolders print("Directory and its contents removed.")
Be careful! shutil.rmtree()
is permanent and cannot be undone.
It’s a good practice to check if the directory exists before removing:
import os import shutil
folder = "MyFolder"
if os.path.exists(folder): shutil.rmtree(folder) print(f"Directory '{folder}' removed.") else: print(f"Directory '{folder}' does not exist.")
A example for removing an empty directory in Python:
import os
directory_name = "MyFolder"
os.rmdir(directory_name)
print(f"Directory '{directory_name}' removed successfully!")
Note:
os.rmdir()
works only if the directory is empty.- If it has files or subdirectories, you need to use
shutil.rmtree()
instead.
Example for removing a directory with files:
import shutil
shutil.rmtree("MyFolder") print("Directory and its contents removed successfully!")
CHAPTER 13
creating and working with files in Python.
We use Python’s built-in open()
function:
file = open("example.txt", "w") # 'w' creates a new file or overwrites if exists file.write("Hello, this is my first file!\n") file.close()
Modes in open()
:
Mode | Meaning |
---|---|
"w" | Write (create new / overwrite) |
"a" | Append (create if not exists, add to end) |
"r" | Read (must exist) |
"x" | Create new file (error if exists) |
"b" | Binary mode (e.g., "wb" ) |
"t" | Text mode (default, e.g., "wt" ) |
with open("example.txt", "w") as file: file.write("Line 1\n") file.write("Line 2\n")
Using with
automatically closes the file.
with open("example.txt", "r") as file: content = file.read() print(content)
Other ways to read:
file.readline() # Read one line file.readlines() # Read all lines into a list
with open("example.txt", "a") as file: file.write("This is an extra line.\n")
import os
if os.path.exists("example.txt"): print("File exists!") else: print("File not found!")
import os
if os.path.exists("example.txt"): os.remove("example.txt") print("File deleted.")
A example to create a file in Python:
file = open("myfile.txt", "w") file.write("Hello! This is my new file.\n") file.close()
print("File created successfully!")
Tip:
If you want to create a file only if it does not already exist, use the "x"
mode:
file = open("myfile.txt", "x") file.write("This file is created only once!\n") file.close()
let’s break down writing to an existing file in Python.
When you write to a file in Python using "w" mode:
- If the file exists → its contents are erased before writing new data.
- If the file does not exist → it will be created automatically.
with open("myfile.txt", "w") as file: file.write("This is new content.\n") file.write("The old content is gone.\n")
print("File updated successfully!")
✅ with
automatically closes the file after writing.
Use "a" mode (append) instead:
with open("myfile.txt", "a") as file: file.write("This is an extra line.\n")
Mode | Action |
---|---|
"w" | Overwrite (or create if not exists) |
"a" | Append to the end |
"x" | Create new file, error if exists |
If you want, I can give you a short table comparing "w" and "a" mode so you can quickly remember which to use.
A simple example for writing to a file in Python:
with open("myfile.txt", "w") as file: file.write("Hello, world!\n") file.write("This is my first line in the file.\n")
print("Data written to file successfully!")
Notes:
- "w" mode will create the file if it doesn’t exist.
- If the file exists,
"w"
will overwrite its content. - Always use
with
to ensure the file closes automatically.
The breakdown for reading an existing file in Python.
We use the open() function with "r" mode (read mode):
with open("myfile.txt", "r") as file: content = file.read() print(content)
- "r" means read only (file must already exist).
- If the file does not exist, Python raises a
FileNotFoundError
.
Method | Description |
---|---|
read() | Reads the entire file as one string. |
readline() | Reads one line at a time. |
readlines() | Reads all lines and returns them as a list. |
Example:
with open("myfile.txt", "r") as file: print(file.readline()) # First line print(file.readline()) # Second line
with open("myfile.txt", "r") as file: for line in file: print(line.strip()) # strip() removes extra spaces/newlines
import os if os.path.exists("myfile.txt"): with open("myfile.txt", "r") as file: print(file.read()) else: print("File not found!")
A example for reading a file in Python:
with open("myfile.txt", "r") as file: content = file.read() print(content)
Notes:
- "r" means read mode — the file must already exist.
- file.read() reads the entire file as one string.
- Using with ensures the file closes automatically after reading.
A example of reading a file line by line using a loop with readline():
with open("myfile.txt", "r") as file: line = file.readline() while line: print(line.strip()) # strip() removes extra spaces/newlines line = file.readline()
How it works:
- readline() reads one line at a time.
- The while line: loop keeps going until no more lines exist.
- strip() cleans up newline characters at the end of each line.
A example for listing all files and directories in Python:
import os
path = "."
items = os.listdir(path)
print("Files and Directories in", path, ":") for item in items: print(item)
Notes:
- os.listdir(path) returns a list of names (files + directories) in the given path.
- "." means the current directory.
- To check whether an item is a file or directory, you can use
os.path.isfile()
andos.path.isdir()
.
Example with filtering:
for item in items: if os.path.isfile(os.path.join(path, item)): print(f"File: {item}") else: print(f"Directory: {item}")
A example to check the current operating system in Python:
import os
os_name = os.name print("OS Name:", os_name)
import platform print("System:", platform.system()) print("Release:", platform.release())
Output example (Windows):
OS Name: nt System: Windows Release: 10
Notes:
- os.name returns short codes like
"nt"
(Windows),"posix"
(Linux/Mac). - platform.system()
gives a readable OS name (
Windows,
Linux,
Darwin`). platform.release()
shows the OS version/release.
A quiz question for creating a map (dictionary) in Python:
Quiz: Which of the following is the correct way to create a dictionary (map) in Python that stores country → capital pairs?
A) countries = ["India": "New Delhi", "France": "Paris"]
B) countries = {"India": "New Delhi", "France": "Paris"}
C) countries = ("India": "New Delhi", "France": "Paris")
D) countries = {"India", "New Delhi", "France", "Paris"}
Correct Answer: B
Because in Python, a dictionary is created using curly braces {}
with key: value pairs.
A quiz question for creating and writing into a file in Python:
Quiz:
Which of the following correctly creates a file named notes.txt
and writes "Hello World"
into it?
A) with open("notes.txt", "r") as file: file.write("Hello World")
B) with open("notes.txt", "w") as file: file.write("Hello World")
C) with open("notes.txt", "a") as file: file.read("Hello World")
D) open("notes.txt", "x") file.write("Hello World")
Correct Answer: B
- "w" mode creates the file if it doesn’t exist and writes data (overwrites if it exists).
- "r" mode cannot write, and
"a"
mode appends instead of overwriting.