Artificial Intelligence Class – IX
Introduction to Python Language
What is Python?
- Python is a high-level, interpreted, and general-purpose programming language.
- Created by Guido van Rossum.
- Known for its simple syntax and readability, making it ideal for beginners.
Why learn Python?
- Easy to read and write.
- Widely used in:
- Artificial Intelligence (AI)
- Machine Learning (ML)
- Data Science
- Web Development
- Automation
- Game Development
Features of Python
- Interpreted (no need to compile)
- Dynamically typed (no need to declare data types)
- Large libraries (NumPy, Pandas, TensorFlow, etc.)
- Cross-platform (runs on Windows, Mac, Linux)
2. Python Basics
2.1 Variables
A variable is a container used to store data.
Examples
name = "Aditi"
age = 15
marks = 92.5
2.2 Data Types
Data types are used to categorize different kinds of values or information for data management and processing.

| Type | Example | Description |
|---|---|---|
int | 10, -5, 1000 | Whole numbers |
float | 3.14, -2.5 | Decimal values |
str | “Hello”, ‘A’ | Text values |
Type Conversion
Type conversion in Python refers to the process of changing the data type of a value from one type to another.
a = int("10") # string to integer
b = float(5) # int to float
c = str(22) # int to string
2.3 Using print() and input() functions
print() is a built-in Python function used to display/output information on the screen. It is used to show text, numbers, results, or values of variables.
input() is a built-in Python function used to take input from the user. It always returns the input as a string.
name = input("Enter your name: ")
print("Hello", name)
Operators
Operators are special symbols that perform operations on values or variables. They are categorized into several types:
2.4 Arithmetic Operators
| Operator | Meaning | Example |
|---|---|---|
+ | Addition | 3 + 2 |
- | Subtraction | 5 – 1 |
* | Multiplication | 2 * 4 |
/ | Division | 9 / 3 |
// | Floor division | 10 // 3 |
% | Modulus | 10 % 3 |
** | Exponent | 2 ** 3 |
2.6 Comparison Operators
| Operator | Meaning |
|---|---|
== | Equal to |
!= | Not equal to |
> | Greater than |
< | Less than |
>= | Greater or equal |
<= | Less or equal |
2.7 Logical Operators
| Operator | Meaning | Example |
|---|---|---|
and | Both true | x > 10 and x < 20 |
or | At least one true | x > 10 or y == 5 |
not | Reverses truth value |
2.8 Assignment Operators
| Operator | Meaning | Example |
|---|---|---|
= | Assign | x = 5 |
+= | Add and assign | x += 2 |
-= | Sub and assign | x -= 3 |
Python Operator Precedence
Here is a clean, clear table of Python operator precedence from highest to lowest:
| Precedence Level | Operators | Description / Examples |
|---|---|---|
| 1 (Highest) | (...) | Parentheses — override default precedence |
| 2 | ** | Exponentiation (right-associative) |
| 3 | +x, -x, ~x | Unary plus, unary minus, bitwise NOT |
| 4 | *, /, //, % | Multiplication, division, floor division, modulo |
| 5 | +, - | Addition and subtraction |
| 6 | <, <=, >, >=, !=, ==, is, is not, in, not in | Comparison, identity, and membership operators |
| 7 | not | Boolean NOT |
| 8 | and | Boolean AND |
| 9 (Lowest) | or | Boolean OR |
Sample Practice
a = int(input("Enter number: "))
b = int(input("Enter number: "))
print("Sum =", a + b)
print("Square of sum =", (a + b)**2)
Expression:
Expressions are combinations of operators, variables and values that evaluate to a single value.
For example:
result=(5 + 3) * 2
3. Flow of Control (Conditionals & Loops)
The flow of control dictates the order in which statements are executed within a program. By default, Python executes code sequentially, from top to bottom and left to right.
3.1 Conditional Statements (if, elif, else)
Conditional statements direct a program’s flow by executing code blocks based on whether a condition is true or false. This allows a program to make decisions.
Syntax
if condition:
statements
elif condition:
statements
else:
statements
Example
age = int(input("Enter age: "))
if age >= 18:
print("Adult")
else:
print("Minor")
3.2 Looping Statements
(a) for loop
Used when we know the number of repetitions.
for i in range(5):
print("Hello")
(b) while loop
Used when the number of repetitions is unknown.
count = 1
while count <= 5:
print(count)
count += 1
Practice Examples
- Print numbers 1 to 10
for i in range(1, 11):
print(i)
- Sum of numbers 1 to n
n = int(input("Enter n: "))
total = 0
for i in range(1, n + 1):
total += i
print(total)
Types of Errors:
Errors in Python are messages that indicate something went wrong during or before the execution of a program. There are three main types of errors as follows:
i. Syntax Errors
A syntax error occurs when the rules (grammar) of the programming language are broken.
The program cannot run until the error is fixed.
Causes
- Missing punctuation
- Incorrect indentation (especially in Python)
- Misspelled keywords
- Wrong structure of statements
Example (Python)
print("Hello"
# Missing closing parenthesis → SyntaxError
if x > 5
print("Hi")
# Missing colon → SyntaxError
Key Points
- Detected before execution (during compilation or interpretation).
- The interpreter usually points to where the error occurred.
- Must be corrected before the program runs.
ii. Runtime Errors
Errors that occur while the program is running. The program may start successfully but crashes during execution.
Causes
- Dividing by zero
- Accessing invalid indexes
- Using an undefined variable
- Invalid type conversion
Example
x = 10 / 0
# ZeroDivisionError
numbers = [1, 2, 3]
print(numbers[5])
# IndexError
int("abc")
# ValueError
Key Points
- Program runs but stops when the error occurs.
- Often handled using exception handling (try-except).
iii. Logical Errors
Errors where the program runs without crashing, but produces incorrect or unexpected results.
Causes
- Wrong formulas
- Incorrect conditions in loops or if-statements
- Misplaced statements
- Wrong algorithm or logic flow
Example
# Intent: find average of two numbers
x = 10
y = 20
average = x + y / 2 # Wrong logic
print(average)
Correct logic:
average = (x + y) / 2
Another example:
if score > 90:
grade = "Fail" # Wrong logic
Key Points
- Hardest to detect because the program still runs.
- No error messages are shown.
- Requires testing and debugging to find.
Summary Table
| Error Type | Detected When? | Does Program Run? | Example | Difficulty |
|---|---|---|---|---|
| Syntax Error | Before execution | ❌ No | Missing : | Easy |
| Runtime Error | During execution | ⚠️ Runs then crashes | Divide by zero | Medium |
| Logical Error | After execution (output incorrect) | ✅ Yes | Wrong formula | Hard |
4. Python Lists
4.1 What is a List?
- A list is an ordered collection of items.
- Written inside square brackets [ ].
- Can store multiple data types.
Example
fruits = ["apple", "banana", "mango"]
4.2 Accessing List Elements
print(fruits[0]) # apple
print(fruits[-1]) # mango
4.3 Basic List Operations
| Operation | Example |
|---|---|
| Append element | fruits.append("orange") |
| Insert element | fruits.insert(1, "pear") |
| Remove element | fruits.remove("banana") |
| Length of list | len(fruits) |
| Slicing | fruits[1:3] |
4.4 Looping Through Lists
for item in fruits:
print(item)
Practice Exercise
- Create list and print largest number
numbers = [12, 45, 3, 67, 89]
print("Max:", max(numbers))
- Add 5 numbers from user
nums = []
for i in range(5):
value = int(input("Enter number: "))
nums.append(value)
print(nums)
✨ Summary
- Python is a simple and powerful language used widely in AI.
- You learned variables, data types, operators, print/input.
- You practiced conditional statements and loops.
- You explored lists and basic list operations.
📘 20 Multiple Choice Questions (MCQs)
1. Which function is used to display output in Python?
a) display()
b) print()
c) show()
d) output()
Answer: b
2. What does the input() function return?
a) Integer
b) Float
c) String
d) Boolean
Answer: c
3. Which of the following is a valid variable name?
a) 2name
b) first-name
c) first_name
d) first name
Answer: c
4. What is the correct operator for exponentiation?
a) ^
b) **
c) //
d) %%
Answer: b
5. What is the output of print(10 // 3)?
a) 3
b) 3.33
c) 4
d) Error
Answer: a
6. Which is a comparison operator?
a) =
b) ==
c) +=
d) and
Answer: b
7. Which data type does 4.56 belong to?
a) int
b) float
c) str
d) bool
Answer: b
8. What is the result of int("8") + 2?
a) 82
b) “82”
c) 10
d) Error
Answer: c
9. Which loop is used when the number of iterations is known?
a) while
b) for
c) if
d) else
Answer: b
10. Which keyword is used for conditional branching?
a) repeat
b) switch
c) if
d) do
Answer: c
11. What is the correct syntax of a while loop?
a) while (condition)
b) while condition:
c) while: condition
d) while = condition
Answer: b
12. Which of the following is a list?
a) {1, 2, 3}
b) (1, 2, 3)
c) [1, 2, 3]
d) <1, 2, 3>
Answer: c
13. Which method is used to add an element to a list?
a) push()
b) append()
c) add()
d) insert()
Answer: b
14. What will len([3, 5, 7]) return?
a) 5
b) 7
c) 3
d) Error
Answer: c
15. What does a += 3 mean?
a) a = a + 3
b) a = 3
c) a = a * 3
d) a = a – 3
Answer: a
16. Which of these is a logical operator?
a) ++
b) or
c) ==
d) <=
Answer: b
17. What is the output of print("AI" * 3)?
a) AI3
b) 3AI
c) AAA
d) AIAIAI
Answer: d
18. Which function is used to find the largest value in a list?
a) big()
b) largest()
c) max()
d) maximum()
Answer: c
19. Which of the following is correct list indexing?
a) list(1)
b) list[1]
c) list{1}
d) list<1>
Answer: b
20. What is the output of:
for i in range(3):
print(i)
a) 0 1 2
b) 1 2 3
c) 1 2
d) 0 1 2 3
Answer: a
📝 Worksheet
A. Short Answer Questions
- Define a variable in Python.
- What is the difference between
=and==? - Why do we use the
input()function? - What are lists? Give two examples.
- What is the use of the
ifstatement?
B. Write the Output
print(15 % 4)
a = 5
b = 2
print(a ** b)
print("AI" + "Python")
nums = [1, 2, 3]
print(nums[1])
for i in range(2):
print("Hi")
C. Solve the Following (Coding)
1. Take a user’s name and print a greeting message.
Example:
Input: Rahul
Output: Hello Rahul!
2. Write a program to add two numbers entered by the user.
3. Write a program to check if a number is even or odd.
4. Print numbers from 1 to 20 using a for loop.
5. Create a list of 5 fruits and print the second and last fruit from the list.
6. Write a program to find the largest number in a list of 5 numbers.
7. Using a while loop, print numbers from 10 to 1 in reverse order.
8. Ask the user for 3 marks and print their average.
Important Questions on Class IX Artificial Intelligence:
Q1. What are errors in Python? How are they classified?
Errors in Python are problems in a program that stop it from running correctly.
They usually happen because of wrong syntax, wrong logic, or unexpected input.
Types of Errors in Python
- Syntax Errors
- Occur when rules of Python syntax are broken.
- Example:
print("Hello" # missing bracket
- Runtime Errors
- Happen while the program is running.
- Example:
10 / 0 # division by zero
- Logical Errors
- The program runs but gives wrong output because logic is incorrect.
- Example:
print(5 * 2) # when user wanted addition
Q2. Describe the role of Python in artificial intelligence.
Python plays a major role in Artificial Intelligence (AI) because:
- It is simple and easy to learn, even for beginners.
- Python has a large number of AI libraries such as:
- NumPy (mathematics),
- Pandas (data handling),
- TensorFlow, PyTorch (machine learning),
- OpenCV (computer vision).
- Python supports rapid development, making it easier to build prototypes quickly.
- It has a huge community support, tutorials, and documentation.
- Python works well with data analysis, which is the core of AI.
Because of these features, Python is the most preferred language for developing AI applications.
Q3. What are comments in Python? Explain their purpose.
Comments are notes written inside a Python program that the computer ignores.
They are meant for humans to understand the code.
Types of Comments
- Single-line comment – starts with
## This is a single-line comment - Multi-line comment – written using triple quotes
""" This is a multi-line comment explaining the code """
Purpose of Comments
- To explain the code for better understanding.
- To make programs easier to read and maintain.
- To temporarily disable lines of code during testing.
Q4. What are tokens in Python? Provide examples.
Tokens are the smallest building blocks of a Python program.
Everything written in Python is made of tokens.
Types of Python Tokens
- Keywords ( Keywords are the reserved words used for some specific purposes )
Example:if,else,while,for - Identifiers (names given to variables, functions)
Example:age,total_amount - Literals (constant values)
Example:10,"Hello",3.14,True - Operators
Example:+,-,*,/,== - Punctuators / Delimiters
Example:(),{},:,,
Q5. What are the steps involved in computer problem-solving and why is each step important?
Computer problem-solving follows a methodical approach:
i. Understanding the Problem
- Read and analyze what needs to be done.
- Important because incorrect understanding leads to wrong solutions.
ii. Planning the Solution (Algorithm)
- Write step-by-step instructions.
- Important because it provides a clear method to follow.
iii. Creating a Flowchart (Optional but useful)
- Draw the process using symbols.
- Important because it visually shows the flow of the solution.
iv. Writing the Program (coding)
- Convert the algorithm into code.
- Important because the computer can only follow programming language instructions.
v. Testing and Debugging
- Run the program to check errors.
- Important because it ensures the program works correctly.
Q6. What are keywords in Python?
Keywords are special words in Python that have fixed meanings and are used to define the structure of a program. You cannot use them as variable names.
Examples of Python Keywords
if, else, elif, while, for, break, continue, True, False, None, def, class, return, import
Q7. Difference between Keywords and Identifiers
| Keywords | Identifiers |
|---|---|
| Keywords are special reserved words in Python. | Identifiers are names given to variables, functions, classes, etc. |
| They have a predefined meaning and purpose in Python. | They are user-defined, meaning we create them. |
| We cannot use keywords as variable names. | We can choose any name (following rules) for identifiers. |
Keywords are fixed and limited in number (like if, while, True). | Identifiers can be any number, unlimited. |
| Keywords must be exact words defined by Python. | Identifiers must follow rules (no spaces, cannot start with a number, etc.). |
Example : if, else, for, True, def | Example: name, age, total_sum, calculateMarks() |