📚 UNIT 5: INTRODUCTION TO PYTHON
Touchpad AI | Class 9 | Code 417 | Pages 357–428
Shalini Harisukh & Anjana Virmani | Orange Education
1. Computer Problem Solving ke Steps
1. Understanding the problem – Main objective samjho, requirements gather karo
2. Analysing the problem – Chote parts mein todo, inputs/outputs identify karo
3. Developing the solution – Algorithm aur flowchart banao
4. Coding and implementation – Computer language mein likho
2. Control Structures (3 Types)
Type Kya Hota Hai
Sequential Flow Ek ke baad ek statements — default flow
Selection Flow Condition ke basis par branching (if-else)
Repetition Flow Loop — baar baar repeat karna
3. Algorithm
Definition: Step-by-step approach to identify and solve a problem in finite time. Simple English-like
statements use karta hai.
⭐ Brainy Fact: "Algorithm" word ek Persian mathematician Al-Khwarizmi ke naam se aaya!
Advantages
Step-by-step solution deta hai
Simple English jaisi language
Program mein convert karna aasaan
Disadvantages
Koi standard rule nahi — varies drastically
Time-consuming
Branching/looping dikhana mushkil
4. Flowchart
Definition: Algorithm ka graphical representation. Symbols aur arrows use karta hai.
Symbol Shape Purpose
START/STOP Oval Flowchart start aur stop karne ke liye
INPUT/OUTPUT Parallelogram Input lena aur output dikhana
PROCESS Rectangle Mathematical/processing operations
DECISION Diamond Decision-making (branching/looping)
FLOW Arrow Information flow ki direction
Algorithm vs Flowchart
Algorithm Flowchart
Step-by-step textual approach Graphical representation
Natural language/pseudocode Standardised symbols
Branching/looping difficult Easily represents branching/looping
Simple, complex, long programs Only for simple processes
5. What is Python?
Definition: Python is a general-purpose, object-oriented, easy-to-learn and high-level programming
language. Guido van Rossum ne 1991 mein design kiya. Naam BBC show "Monty Python's Flying Circus"
se liya.
Important Features
High-Level Language – Human language ke close, machine language se door
Easy to Learn and Use – Simple, English-like statements
Free and Open Source – [Link] se free download
Cross-platform – Windows, Linux, Mac, Raspberry Pi sab par kaam karta hai
Interpreted Language – Source code line by line execute hota hai
Object-Oriented – Classes aur objects support karta hai
Large Standard Library – Bahut saare built-in modules
Role in AI
Built-in Libraries: Numpy, PyBrain, Scipy, Pandas
Platform Independence – Kisi bhi platform par run karo
Matplotlib – Charts aur histograms ke liye
Applications
Web Development (Django, Flask)
Scientific Calculation (SciPy, Pandas)
Game Development (PySoy, PyGame)
Database Access
Business Applications
⭐ Brainy Fact: Facebook, Google, NASA, MIT, Nokia, IBM sab Python use karte hain!
6. Working in Python (IDLE)
IDLE = Integrated Development and Learning Environment
Two Modes
Interactive Mode (Shell): >>> prompt par ek command at a time. Save nahi hoti.
Script Mode (Editor): Saare commands .py file mein save karke run karo (F5 press karo).
7. Statements in Python
Simple Statement: Enter key se end hota hai. Ek line = ek statement.
a = 5
Multiline Statement: Backslash (\) use karo.
a = 4 + 5 + \
6 + 7
Multiple Statement: Semicolon (;) se separate karo.
a = 5; b = 10; c = a + b; print(c)
8. Tokens (5 Types)
Tokens = smallest meaningful unit of a program
Keywords – Reserved words (if, else, for, while, etc.) — identifier ke roop mein use nahi ho sakte
Identifiers – User-defined names of variables, list, etc.
Literals – Data stored in variable (String, Numeric, Boolean, None)
Punctuators – Special symbols: ' " # \ {} [] @ , : ; =
Operators – Mathematical, logical, relational operations
Identifier Rules
Letter (a-z, A-Z) ya underscore (_) se shuru ho
Alphabets, numbers, underscore allowed
Special characters ($, ., space) allowed NAHI
Python keyword nahi hona chahiye
Case-sensitive hai (Name ≠ name)
Invalid Reason
First name Space not allowed
Last&Name Special character not allowed
9thclass Cannot begin with number
else Keyword not allowed
9. Operators
Arithmetic Operators
Operator Name Example Output
+ Addition 2+4 6
- Subtraction 6-2 4
* Multiplication 2*3 6
/ Division 11 / 2 5.5
% Modulus 5%2 1
** Exponential 5 ** 2 25
// Floor Division 11 // 2 5
Relational Operators
Operator Name Purpose
== Equal to True if both values same
!= Not equal to True if values different
> Greater than True if first > second
< Less than True if first < second
>= Greater than or equal True if first >= second
<= Less than or equal True if first <= second
Logical Operators
Operator Purpose Example Output
and True if BOTH operands True 5<10 and 2<5 True
or True if EITHER operand True 5>10 or 2<5 True
not Reverses result not(10<5) True
Operator Precedence (Highest → Lowest)
Order Operators
1 (Highest) ( ) Parentheses
2 ** Exponential
3 *, /, %, //
4 +, -
5 <=, <, >, >=
6 ==, !=
7 =, %=, /=, //=, -=, +=, *=, **=
8 (Lowest) not, and, or
10. Variables & Data Types
Variable: Memory location ka naam jo ek specific value hold karta hai.
# 3 ways to assign: a = 5 # Method 1 a = 5; b = 10 # Method 2 a = b = c = 10 # Method 3
Data Types
Data Type Description Example
int Whole numbers 10, -45, 0
float Decimal numbers 15.5, 12.0
complex Real + Imaginary 3+2j
None NULL value None
bool True or False only True, False
str UNICODE characters 'Hello', "Python"
list Ordered, mutable [ ] [1, 2, 'abc']
tuple Ordered, immutable ( ) (1, 2, 'abc')
set Unique elements { } {21, 52, 33}
dict Key:Value pairs { } {'name':'Yash'}
Type Conversion
int() float() str() bool() list() tuple() set() >>> float(12) # 12.0 >>> int(15.5) # 15 >>>
str(12) # '12' >>> type(10) # <class 'int'>
11. Comments in Python
Single Line: # se shuru
# This is a comment
Multi Line: ''' ya """ se
"""This is a multiline comment"""
12. print() aur input() Functions
print() — Screen par output dikhata hai
print(object(s), sep=separator, end=end) print("hello") # hello print("hello", "friends") #
hello friends print("hello", "friends", sep="$") # hello$friends print("hello", end="!") #
hello!
input() — User se input leta hai
⚠️ input() ALWAYS string return karta hai! Math ke liye int() ya float() use karo!
name = input("Enter your name: ") a = int(input("Enter number: ")) # integer ke liye b =
float(input("Enter number: ")) # float ke liye
13. Errors in Python
Error Kab Hota Hai Example
Syntax Error Python ke rules violate hone par. Sabse common. a + b = c → SyntaxError
Logical Error Program run hota hai par output galat aata hai. p = marks/2 instead of (m1+m2)/2
Runtime Error Execution ke during — zero se divide, undefined variable. a/b jab b=0 → ZeroDivisionError
14. Control Statements
A. if Statement
if (condition): statements
Example — Certificate if % > 80:
percent = int(input("Enter percentage:")) if percent > 80: print("Congratulations")
print("You are awarded Certificate of Excellence")
B. if...else Statement
if (condition): Statements for True else: Statements for False
Example — Bigger of two numbers:
N1 = int(input("Enter First Number:")) N2 = int(input("Enter Second Number:")) if N1 > N2:
print(N1, "is bigger") else: print(N2, "is bigger")
Example — Even or Odd:
Num = int(input("Enter a Number:")) if Num % 2 == 0: print(Num, "is EVEN") else: print(Num,
"is ODD")
C. if...elif...else Statement
if (condition1): Statements 1 elif (condition2): Statements 2 else: Statements when all False
Example — Positive, Negative or Zero:
Num = int(input("Enter a number:")) if Num == 0: print("You entered zero") elif Num > 0:
print("You entered a positive number") else: print("You entered a negative number")
D. for Loop (Definite/Fixed Loop)
for <var> in range(<Start>, <End>, <Step>): Statements
⚠️ End value NOT included! range(1,6) = 1,2,3,4,5
Command Output
range(1,6,1) 1,2,3,4,5
range(10) 0,1,2,3,4,5,6,7,8,9
range(5,0,-1) 5,4,3,2,1
range(1,10,2) 1,3,5,7,9
range(5,5) No output
E. while Loop (Indefinite/Entry-controlled Loop)
while <condition>: Statements
⚠️ Agar condition change nahi hui to Infinite Loop ban jaata hai!
Example — Sum of first 5 natural numbers:
num = 1 sum = 0 while num < 6: sum = sum + num num = num + 1 print("Sum is", sum) # Output:
15
15. Lists in Python
List: Ordered aur mutable collection. Different data types store kar sakti hai. Square brackets [ ] use hote
hain.
Important Features
Mutable (changeable) data type
Ordered sequence
Elements comma se separate, [ ] mein
Index number se access hota hai (starts from 0)
Creating a List
list1 = [] # Empty list friends = ["Saisha", "Advika", "Arshia"] # List of strings marks =
[92, 91, 89, 95, 93] # List of numbers L1 = [10] * 5 # [10,10,10,10,10]
Indexing
L1 = ['P','Y','T','H','O','N'] # Forward: 0 1 2 3 4 5 # Backward:-6 -5 -4 -3 -2 -1
print(L1[0]) # P print(L1[-1]) # N
Adding Elements
# append() — end mein ek element add fruits = ["apple","banana"] [Link]("mango") #
['apple','banana','mango'] # extend() — multiple elements add n = [1,2,3,4] [Link]([5,6]) #
[1,2,3,4,5,6] # insert(index, value) — specific position par add L = [10,20,30] [Link](1,
40) # [10,40,20,30]
Modifying Elements
L1 = [10, 20, 40, 50] L1[3] = 100 print(L1) # [10, 20, 40, 100]
Removing Elements
# remove() — first occurrence remove karta hai marks = [23, 34, 23, 45] [Link](23) #
[34, 23, 45] # pop() — index se remove, value return karta hai vowels = ['a','e','i','o','u']
val = [Link](2) # val = 'i' [Link]() # Last element remove
Other List Functions
Function Purpose
len() List ki length return karta hai
clear() Saare elements remove karta hai
reverse() List ko reverse karta hai
sort() Ascending order mein sort karta hai
sort(reverse=True) Descending order mein sort
index(value) Value ka index number return karta hai
List Operators
A = [1,2,3] B = [4,5,6] C = A + B # [1,2,3,4,5,6] — Concatenation D = A * 3 #
[1,2,3,1,2,3,1,2,3] — Replication
16. Important Programs (Exam ke liye)
Program: Table of a number
num = int(input("enter a number: ")) for i in range(1,11): print(num, "*", i, "=", num*i)
Program: Largest of three numbers
a = int(input("enter first number: ")) b = int(input("enter second number: ")) c =
int(input("enter third number: ")) larg = a if b > larg: larg = b if c > larg: larg = c
print("largest of all is", larg)
Program: Sum of even and odd numbers
n = int(input("Enter range: ")) sumeven = sumodd = 0 i = 0 while i <= n: if i%2 == 0: sumeven
+= i else: sumodd += i i += 1 print("Sum of even:", sumeven) print("Sum of odd:", sumodd)
Program: Search value in list
L = [10,23,45,10,12,34,10,56] s = int(input("Enter value to search: ")) count = 0 for i in L:
if i == s: count += 1 print(s, "occurs", count, "times")
Program: Area and Perimeter of Rectangle
Length = int(input('Enter Length:')) Breadth = int(input('Enter Breadth:')) Area = Length *
Breadth Perimeter = 2 * (Length + Breadth) print("Area is:", Area) print("Perimeter is:",
Perimeter)
17. Important Q&A (Exam)
Q. How did Python get its name?
Ans. Guido van Rossum ne 1991 mein release kiya. BBC show "Monty Python's Flying Circus" ke naam par
rakha.
Q. What are tokens?
Ans. Tokens smallest meaningful unit of a program hain. Types: Keywords, Identifiers, Literals,
Punctuators, Operators.
Q. What is iteration?
Ans. The process of repeating a set of instructions based on a condition is called iteration.
Q. Difference between for and while loop?
Ans. for loop definite (fixed iterations), while loop indefinite (condition-based). for = definite loop, while =
indefinite/entry-controlled loop.
Q. What is the use of pop() function?
Ans. pop() removes an element from list based on index number and returns the deleted value.
Q. What is negative indexing?
Ans. Index begins with -1 till -length, referring to elements from right to left.
Q. Difference between append() and extend()?
Ans. append() adds single element at end. extend() adds multiple elements at a time.
Q. What is type conversion?
Ans. Converting value of one data type to another. Two types: Implicit (Python automatically) and Explicit
(programmer manually using int(), float(), str() etc.).
🎯 ALL THE BEST FOR YOUR EXAM! 💪
Touchpad AI Class 9 | Unit 5 | Pages 357–428 | Orange Education