1.1 What is Programming?
Just as we use English or Hindi to talk to people, we use programming languages to give instructions to computers.
1.2 What is Python?
🔹 Why is Python Called a "High-Level" Language?
Because Python is written in simple, English-like words that are close to how humans think – unlike low-level languages (like Assembly) which are close to machine code and hard to understand.
1.3 Features of Python
1.4 Applications of Python
1.5 How to Install & Run Python
🔹 Ways to Run Python
- Install Python: Download from python.org and install on your computer.
- Use IDLE: The default Python editor that comes with Python.
- Online Python Compilers: replit.com, programiz.com/python-programming/online-compiler, onlinegdb.com – no installation needed!
- Jupyter Notebook: Popular for AI / Data Science.
- Code Editors: VS Code, PyCharm with Python extension.
1.6 Your First Python Program
Let's start with the classic "Hello World" program:
print("Hello, World!")
That's it! Just one line of code and your first program is ready.
1.7 Comments in Python
# This is a single-line comment print("Hello") # Comment at end of line """ This is a multi-line comment """
1.8 Variables in Python
🔹 How to Create a Variable
# Syntax: variable_name = value name = "Ravi" age = 15 height = 5.6 print(name) print(age) print(height)
🔹 Rules for Naming Variables
- Must start with a letter or underscore (_).
- Cannot start with a number (e.g.,
2nameis invalid). - Can contain letters, numbers, and underscores.
- Are case-sensitive:
Age,age, andAGEare different. - Cannot use reserved keywords (like
print,if,for). - Should be meaningful: use
student_ageinstead ofa. - No spaces allowed (use
_instead).
1.9 Data Types in Python
Data types tell Python what kind of value a variable is holding. Python has these main data types:
1. Integer (int)
Whole numbers without decimals.Examples: 10, -5, 2026, 0
2. Float
Numbers with decimal point.Examples: 3.14, 2.5, -0.7
3. String (str)
Text in quotes " " or ' '.Examples: "Hello", 'Python'
4. Boolean (bool)
Has only two values: True or False. Used for decision making.Examples: is_student = True, has_failed = False
# Examples of different data types a = 10 # int b = 3.14 # float c = "Python" # string d = True # boolean print(type(a)) # shows the data type print(type(b)) print(type(c)) print(type(d))
1.10 Type Conversion
| Function | Converts To | Example |
|---|---|---|
int() | Integer | int("10") → 10 |
float() | Float | float("3.14") → 3.14 |
str() | String | str(100) → "100" |
bool() | Boolean | bool(1) → True |
# Type conversion examples x = "25" # x is a string y = int(x) # y is now integer 25 print(y + 5) # prints 30 num = 3.7 print(int(num)) # prints 3 (removes decimal)
1.11 print() and input() Functions
📤 print() Function
The print() function is used to display output on the screen.
print("Hello") # prints Hello print("Name:", "Ravi") # prints Name: Ravi print(5 + 3) # prints 8 print("Age:", 15, "years") # combines items
📥 input() Function
The input() function is used to take input from the user. It always returns a string.
name = input("Enter your name: ") print("Hello,", name)
int() or float().
age = int(input("Enter your age: ")) print("Next year you will be", age + 1)
1.12 Operators in Python
➕ 1. Arithmetic Operators
Used for mathematical calculations.
| Operator | Name | Example | Result |
|---|---|---|---|
+ | Addition | 5 + 3 | 8 |
- | Subtraction | 10 - 4 | 6 |
* | Multiplication | 6 * 2 | 12 |
/ | Division | 10 / 3 | 3.333 |
// | Floor Division | 10 // 3 | 3 |
% | Modulus (remainder) | 10 % 3 | 1 |
** | Power (exponent) | 2 ** 3 | 8 |
🎯 2. Assignment Operators
Used to assign values to variables.
| Operator | Example | Same As |
|---|---|---|
= | x = 5 | Simple assignment |
+= | x += 3 | x = x + 3 |
-= | x -= 2 | x = x - 2 |
*= | x *= 4 | x = x * 4 |
/= | x /= 2 | x = x / 2 |
%= | x %= 3 | x = x % 3 |
⚖️ 3. Comparison Operators
Used to compare two values. They return either True or False.
| Operator | Meaning | Example | Result |
|---|---|---|---|
== | Equal to | 5 == 5 | True |
!= | Not equal to | 5 != 3 | True |
> | Greater than | 10 > 5 | True |
< | Less than | 3 < 10 | True |
>= | Greater or equal | 5 >= 5 | True |
<= | Less or equal | 4 <= 3 | False |
= is for assignment, == is for comparison. Don't mix them up!
🧠 4. Logical Operators
Used to combine multiple conditions.
| Operator | Meaning | Example |
|---|---|---|
and | True if BOTH are true | (5 > 3) and (10 > 5) → True |
or | True if AT LEAST ONE is true | (5 > 3) or (10 < 5) → True |
not | Reverses the result | not(5 > 3) → False |
1.13 Expressions in Python
# Examples of expressions result = 10 + 5 * 2 # result = 20 area = length * width # expression with variables is_pass = marks >= 33 # boolean expression
🔹 Operator Precedence (PEMDAS / BODMAS)
- Parentheses –
( ) - Exponents –
** - Multiplication, Division, Modulus –
*, /, //, % - Addition, Subtraction –
+, -
2.1 Conditional Statements (if – elif – else)
🔹 Syntax
if condition: # code to run if condition is True elif another_condition: # code if another condition is True else: # code if all above are False
if block. Use 4 spaces for indentation.
🔹 Examples
Example 1: Check Positive, Negative or Zero
num = int(input("Enter a number: ")) if num > 0: print("Positive number") elif num < 0: print("Negative number") else: print("Zero")
Example 2: Check Voting Eligibility
age = int(input("Enter your age: ")) if age >= 18: print("You can vote!") else: print("You cannot vote yet.")
Example 3: Grade Calculator
marks = int(input("Enter marks: ")) if marks >= 90: print("Grade: A+") elif marks >= 75: print("Grade: A") elif marks >= 60: print("Grade: B") elif marks >= 33: print("Grade: C") else: print("Grade: Fail")
2.2 Loops in Python
🔁 for Loop
The for loop is used to repeat a code a fixed number of times or iterate over a list, string, etc.
🔹 Syntax with range()
for variable in range(start, stop, step): # code to repeat
range() generates a sequence of numbers:
range(5)→ 0, 1, 2, 3, 4range(1, 6)→ 1, 2, 3, 4, 5range(1, 10, 2)→ 1, 3, 5, 7, 9
Example 1: Print First 10 Natural Numbers
for i in range(1, 11): print(i)
Example 2: Print First 10 Even Numbers
for i in range(2, 21, 2): print(i)
Example 3: Sum of First 10 Natural Numbers
total = 0 for i in range(1, 11): total += i print("Sum =", total)
🔄 while Loop
The while loop repeats code as long as a condition is True.
while condition: # code to repeat
Example: Print Numbers 1 to 5
i = 1 while i <= 5: print(i) i += 1 # VERY IMPORTANT – update the variable
while loop! If you forget, the loop will run forever (infinite loop).
🔹 for vs while – When to Use
| Use "for" loop when... | Use "while" loop when... |
|---|---|
| You know the exact number of repetitions. | You want to loop until a condition becomes false. |
| Iterating over a list or range. | Number of iterations is unknown. |
3.1 What is a List?
[ ] and separated by commas.
# Creating a list fruits = ["apple", "banana", "mango"] numbers = [10, 20, 30, 40, 50] mixed = [1, "hi", 3.14, True]
🔹 Features of a List
- Can store different types of data.
- Is ordered – items have fixed positions.
- Is changeable (mutable) – can add / remove items.
- Allows duplicate values.
- Can contain another list (nested list).
3.2 List Indexing
Each item in a list has an index (position number) starting from 0.
fruits = ["apple", "banana", "mango", "orange"] # 0 1 2 3 (positive index) # -4 -3 -2 -1 (negative index) print(fruits[0]) # apple print(fruits[2]) # mango print(fruits[-1]) # orange (last item)
3.3 List Operations
| Operation | Example | Use |
|---|---|---|
| Access Item | list[index] | Get item at position |
| Length | len(list) | Count items |
| Append | list.append(x) | Add item at end |
| Insert | list.insert(i, x) | Add at position i |
| Remove | list.remove(x) | Remove item by value |
| Pop | list.pop(i) | Remove item at index |
| Delete | del list[i] | Delete item at index |
| Extend | list.extend([items]) | Add multiple items |
| Sort | list.sort() | Sort in ascending order |
| Reverse | list.reverse() | Reverse the list |
| Count | list.count(x) | Count occurrences |
| Index | list.index(x) | Find position of item |
3.4 List Slicing
Slicing means getting a part of the list. Syntax: list[start:end] (end is excluded).
nums = [10, 20, 30, 40, 50] print(nums[1:4]) # [20, 30, 40] print(nums[:3]) # [10, 20, 30] print(nums[2:]) # [30, 40, 50] print(nums[-3:-1]) # [30, 40]
4.1 PRINT Category Programs
Program 1: Print Personal Information
print("Name: Rohan Sharma") print("Father's Name: Mr. Ajay Sharma") print("Class: IX-B") print("School: XYZ Public School")
Program 2(a): Print Star Pattern – Increasing Triangle
print("*") print("**") print("***") print("****") print("*****")
Program 2(b): Print Star Pattern – Decreasing Triangle
print("*****") print("****") print("***") print("**") print("*")
Program 3: Find Square of 7
num = 7 square = num ** 2 print("Square of", num, "is", square)
Program 4: Sum of Two Numbers (15 and 20)
a = 15 b = 20 total = a + b print("Sum =", total)
Program 5: Convert Kilometers to Meters
km = 5 meters = km * 1000 print(km, "km =", meters, "meters")
Program 6: Table of 5 (up to 5 terms)
print(5 * 1) print(5 * 2) print(5 * 3) print(5 * 4) print(5 * 5) # OR using a loop for i in range(1, 6): print("5 x", i, "=", 5*i)
Program 7: Calculate Simple Interest
principle_amount = 2000 rate_of_interest = 4.5 time = 10 SI = (principle_amount * rate_of_interest * time) / 100 print("Simple Interest =", SI)
4.2 INPUT Category Programs
Program 8: Area and Perimeter of Rectangle
length = float(input("Enter length: ")) breadth = float(input("Enter breadth: ")) area = length * breadth perimeter = 2 * (length + breadth) print("Area =", area) print("Perimeter =", perimeter)
Program 9: Area of Triangle
base = float(input("Enter base: ")) height = float(input("Enter height: ")) area = 0.5 * base * height print("Area of triangle =", area)
Program 10: Average Marks of 3 Subjects
m1 = float(input("Enter marks of subject 1: ")) m2 = float(input("Enter marks of subject 2: ")) m3 = float(input("Enter marks of subject 3: ")) average = (m1 + m2 + m3) / 3 print("Average marks =", average)
Program 11: Discounted Amount
price = float(input("Enter price: ")) discount = float(input("Enter discount %: ")) discount_amount = (price * discount) / 100 final_price = price - discount_amount print("Discount amount =", discount_amount) print("Final price =", final_price)
Program 12: Surface Area and Volume of Cuboid
l = float(input("Enter length: ")) b = float(input("Enter breadth: ")) h = float(input("Enter height: ")) surface_area = 2 * (l*b + b*h + h*l) volume = l * b * h print("Surface Area =", surface_area) print("Volume =", volume)
4.3 IF / FOR / WHILE Category Programs
Program 13: Check if Person Can Vote
age = int(input("Enter your age: ")) if age >= 18: print("You are eligible to vote.") else: print("You are not eligible to vote.")
Program 14: Check Grade of Student
marks = int(input("Enter marks: ")) if marks >= 90: print("Grade: A+") elif marks >= 75: print("Grade: A") elif marks >= 60: print("Grade: B") elif marks >= 40: print("Grade: C") else: print("Grade: Fail")
Program 15: Check Positive, Negative or Zero
num = int(input("Enter a number: ")) if num > 0: print("The number is positive.") elif num < 0: print("The number is negative.") else: print("The number is zero.")
Program 16: Print First 10 Natural Numbers
for i in range(1, 11): print(i)
Program 17: Print First 10 Even Numbers
for i in range(2, 21, 2): print(i)
Program 18: Print Odd Numbers from 1 to n
n = int(input("Enter n: ")) for i in range(1, n+1, 2): print(i)
Program 19: Sum of First 10 Natural Numbers
total = 0 for i in range(1, 11): total += i print("Sum =", total)
Program 20: Sum of All Numbers in a List
numbers = [10, 20, 30, 40, 50] total = 0 for num in numbers: total += num print("Sum =", total)
4.4 LIST Category Programs
Program 21: Science Quiz Students List
students = ["Arjun", "Sonakshi", "Vikram", "Sandhya", "Sonal", "Isha", "Kartik"] # Print the whole list print("Original list:", students) # Delete "Vikram" students.remove("Vikram") # Add "Jay" at the end students.append("Jay") # Remove item at position 2 (second position, index 1) students.pop(1) print("Final list:", students)
Program 22: List Indexing
num = [23, 12, 5, 9, 65, 44] # Print length of list print("Length:", len(num)) # Elements from 2nd to 4th position (positive indexing) print(num[1:4]) # Elements from 3rd to 5th position (negative indexing) print(num[-4:-1])
Program 23: First 10 Even Numbers + 1
# Create list of first 10 even numbers evens = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] # Add 1 to each item for i in range(len(evens)): evens[i] += 1 print("Final list:", evens)
Program 24: Extend and Sort a List
List_1 = [10, 20, 30, 40] # Extend with new elements List_1.extend([14, 15, 12]) # Sort in ascending order List_1.sort() print("Sorted list:", List_1)
5.1 Common Errors in Python
| Error Type | Cause |
|---|---|
| SyntaxError | Wrong spelling / missing brackets / colons. |
| IndentationError | Incorrect indentation / spaces. |
| NameError | Using a variable that is not defined. |
| TypeError | Wrong data type operations (e.g., adding string + number). |
| ValueError | Wrong value passed to a function. |
| ZeroDivisionError | Dividing by zero. |
| IndexError | Accessing a position that doesn't exist in a list. |
5.2 Good Programming Practices
- Use meaningful variable names –
student_ageinstead ofa. - Add comments to explain tricky parts of your code.
- Use proper indentation – always 4 spaces.
- Test your code with different inputs.
- Break big problems into smaller steps.
- Don't repeat code – use loops and functions.
- Save your work frequently.
- Learn from errors – they help you understand better.
- Practice daily – coding is a skill built by doing.
Quick Revision – Key Points to Remember
- Python = high-level programming language created by Guido van Rossum in 1991.
- Features: Easy, free, cross-platform, interpreted, huge libraries.
- Applications: AI, Data Science, Web, Games, Scientific Computing.
- Variable = named container to store data. Rules: start with letter/_, no spaces, case-sensitive.
- Data Types: int (whole numbers), float (decimals), string (text), bool (True/False).
- Type Conversion: int(), float(), str(), bool().
- Functions: print() for output, input() for input (always returns string).
- Arithmetic Operators: + − * / // % **
- Comparison Operators: == != > < >= <=
- Logical Operators: and, or, not.
- Assignment Operators: = += −= *= /= %=.
- Conditions: if, elif, else – use indentation (4 spaces).
- Loops: for (fixed times), while (until condition false).
- range(start, stop, step) generates a sequence of numbers.
- List = collection of items in square brackets [ ]; indexing starts from 0.
- List methods: append, insert, remove, pop, extend, sort, reverse, len, count, index.
- Comments: # for single-line, """ """ for multi-line.