VM-LEARNING /class.ix ·track.ai ·ch-b5 session: 2026_27
$cd ..

~/Introduction to Python

root@vm-learning ~ $ open ch-b5
PART B ▪ UNIT 5
10
Introduction to Python
Your First Programming Language
Python is a very popular, easy-to-learn programming language that is used all over the world. It is specially designed to be simple and readable – almost like writing English!
Python is the #1 language for AI, Data Science, and Machine Learning. Companies like Google, Netflix, NASA, Facebook, Instagram and YouTube all use Python. Learning Python is your first step into the world of AI programming!
Learning Outcome: Acquire introductory Python programming skills

1.1 What is Programming?

Programming is the process of writing a set of instructions for a computer to follow. These instructions are called a program or code. A person who writes programs is called a programmer.

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?

Python is a high-level, general-purpose programming language created by Guido van Rossum in 1991. It is named after the TV comedy series "Monty Python's Flying Circus" – not the snake!
🔹 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

📖 Easy to LearnSimple, English-like syntax
🆓 Free & Open SourceAnyone can use and share
💻 Cross-PlatformRuns on Windows, Mac, Linux
🔄 InterpretedCode runs line by line
🎯 General PurposeWorks for any type of project
📚 Huge LibrariesThousands of ready-made tools
👥 Large CommunityMillions of Python developers
🔗 PortableSame code runs anywhere
⚙️ ExtensibleCan combine with C, Java, etc.

1.4 Applications of Python

🤖 Artificial Intelligence & MLMain language for AI models, ChatGPT-like tools.
📊 Data Science & AnalyticsAnalysing big data, charts, predictions.
🌐 Web DevelopmentBuilding websites (Instagram, Pinterest use Python).
🎮 Game DevelopmentGames using Pygame library.
🔬 Scientific ComputingUsed at NASA, CERN for research.
🖥️ Desktop ApplicationsCreating software / apps.
🤖 Automation & ScriptingAuto-doing boring tasks, file organising.
💰 Finance / BankingAlgorithmic trading, risk analysis.
📱 Mobile AppsUsing frameworks like Kivy.
🔐 CybersecurityEthical hacking, penetration testing.

1.5 How to Install & Run Python

🔹 Ways to Run Python
  1. Install Python: Download from python.org and install on your computer.
  2. Use IDLE: The default Python editor that comes with Python.
  3. Online Python Compilers: replit.com, programiz.com/python-programming/online-compiler, onlinegdb.com – no installation needed!
  4. Jupyter Notebook: Popular for AI / Data Science.
  5. Code Editors: VS Code, PyCharm with Python extension.
For beginners, use online Python compilers like Replit or Programiz – they work in any web browser without needing to install anything!
📚 Recommended Activity: Before jumping into code, try learning programming concepts through fun gamified platforms like Code Combat (codecombat.com). It teaches programming through an adventure game – perfect for beginners!

1.6 Your First Python Program

Let's start with the classic "Hello World" program:

print("Hello, World!")
Hello, World!

That's it! Just one line of code and your first program is ready.

1.7 Comments in Python

Comments are lines in the program that Python ignores. They are used to write notes and explanations for humans who read the code.
# This is a single-line comment
print("Hello")  # Comment at end of line

"""
This is a
multi-line comment
"""

1.8 Variables in Python

A variable is a named container that stores a value (like a number, word, or true/false) in the computer's memory. We can use the name later to refer to the value.
🔹 How to Create a Variable
# Syntax: variable_name = value
name = "Ravi"
age = 15
height = 5.6

print(name)
print(age)
print(height)
Ravi 15 5.6
🔹 Rules for Naming Variables

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))
<class 'int'> <class 'float'> <class 'str'> <class 'bool'>

1.10 Type Conversion

Type Conversion means changing the data type of a variable from one type to another (e.g., string → integer).
FunctionConverts ToExample
int()Integerint("10") → 10
float()Floatfloat("3.14") → 3.14
str()Stringstr(100) → "100"
bool()Booleanbool(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)
Enter your name: Priya Hello, Priya
input() always returns a string! To use it as a number, convert with 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.

OperatorNameExampleResult
+Addition5 + 38
-Subtraction10 - 46
*Multiplication6 * 212
/Division10 / 33.333
//Floor Division10 // 33
%Modulus (remainder)10 % 31
**Power (exponent)2 ** 38

🎯 2. Assignment Operators

Used to assign values to variables.

OperatorExampleSame As
=x = 5Simple assignment
+=x += 3x = x + 3
-=x -= 2x = x - 2
*=x *= 4x = x * 4
/=x /= 2x = x / 2
%=x %= 3x = x % 3

⚖️ 3. Comparison Operators

Used to compare two values. They return either True or False.

OperatorMeaningExampleResult
==Equal to5 == 5True
!=Not equal to5 != 3True
>Greater than10 > 5True
<Less than3 < 10True
>=Greater or equal5 >= 5True
<=Less or equal4 <= 3False
Important: = is for assignment, == is for comparison. Don't mix them up!

🧠 4. Logical Operators

Used to combine multiple conditions.

OperatorMeaningExample
andTrue if BOTH are true(5 > 3) and (10 > 5) → True
orTrue if AT LEAST ONE is true(5 > 3) or (10 < 5) → True
notReverses the resultnot(5 > 3) → False

1.13 Expressions in Python

An expression is a combination of variables, values, and operators that produces a result.
# 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)
  1. Parentheses – ( )
  2. Exponents – **
  3. Multiplication, Division, Modulus – *, /, //, %
  4. Addition, Subtraction – +, -
FLOW OF CONTROL & CONDITIONS

2.1 Conditional Statements (if – elif – else)

Conditional statements allow programs to take different paths based on conditions. They help the computer make decisions.
🔹 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
Python uses indentation (spaces at the beginning) to show which code belongs inside an 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

A loop is used to repeat a block of code multiple times. Python has two main loops: for loop and while loop.

🔁 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:

Example 1: Print First 10 Natural Numbers
for i in range(1, 11):
    print(i)
1 2 3 4 5 6 7 8 9 10
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)
Sum = 55

🔄 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
1 2 3 4 5
Always update the loop variable inside a 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.
PYTHON LISTS

3.1 What is a List?

A list in Python is a collection of multiple items stored in a single variable. Items are enclosed in square brackets [ ] 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

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

OperationExampleUse
Access Itemlist[index]Get item at position
Lengthlen(list)Count items
Appendlist.append(x)Add item at end
Insertlist.insert(i, x)Add at position i
Removelist.remove(x)Remove item by value
Poplist.pop(i)Remove item at index
Deletedel list[i]Delete item at index
Extendlist.extend([items])Add multiple items
Sortlist.sort()Sort in ascending order
Reverselist.reverse()Reverse the list
Countlist.count(x)Count occurrences
Indexlist.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]
SUGGESTED PROGRAMS FROM CBSE SYLLABUS

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)
Square of 7 is 49
Program 4: Sum of Two Numbers (15 and 20)
a = 15
b = 20
total = a + b
print("Sum =", total)
Sum = 35
Program 5: Convert Kilometers to Meters
km = 5
meters = km * 1000
print(km, "km =", meters, "meters")
5 km = 5000 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)
Simple Interest = 900.0

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)
Sum = 55
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)
Sum = 150

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)
Final list: [3, 5, 7, 9, 11, 13, 15, 17, 19, 21]
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)
Sorted list: [10, 12, 14, 15, 20, 30, 40]

5.1 Common Errors in Python

Error TypeCause
SyntaxErrorWrong spelling / missing brackets / colons.
IndentationErrorIncorrect indentation / spaces.
NameErrorUsing a variable that is not defined.
TypeErrorWrong data type operations (e.g., adding string + number).
ValueErrorWrong value passed to a function.
ZeroDivisionErrorDividing by zero.
IndexErrorAccessing a position that doesn't exist in a list.
When you get an error, read the message carefully! Python tells you exactly what went wrong and on which line. Debugging is a skill every programmer develops.

5.2 Good Programming Practices

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.
🧠Practice Quiz — test yourself on this chapter