03 Brief Overview of Python

CBSE Class 11 Informatics Practices

3.1 Introduction to Python

Before learning any programming language, it is important to understand what a program and a programming language actually are.

An ordered set of instructions or commands given to a computer to perform a specific task is called a program. These instructions must be written in a language that the computer can understand. Such a language is known as a programming language. Examples of programming languages include Python, C, C++, Java, and many others.

This chapter introduces Python, which is a popular, easy-to-learn programming language. Python was created by Guido van Rossum and first released in 1991. Over the years, Python has gained wide acceptance because of its simplicity, readability, and versatility. It is used in many fields such as software development, web development, scientific computing, data analysis, artificial intelligence, and automation.

Python is particularly suitable for students who are learning programming for the first time because it allows them to focus on problem solving and logic, rather than on complicated syntax rules.


Nature and Features of Python

Python is described as a high-level, interpreter-based programming language. Each of these terms has a specific meaning.

A high-level language is a language that is close to human language and far from machine language. Python programs are written using English-like words and symbols, which makes them easy to read and understand. Unlike low-level languages, Python does not require the programmer to manage memory or hardware-related details.

Python is also an interpreted language. This means that Python programs are executed line by line by a program called the Python interpreter. There is no separate compilation step. As soon as a line of code is entered, the interpreter checks it and executes it.

Python is an open-source language, which means it is freely available. Anyone can download Python, use it, modify it, and distribute it. This has resulted in a large community of users and developers who continuously improve the language and create useful libraries.

Another important feature of Python is portability. A Python program written on one operating system (such as Windows) can be executed on another operating system (such as Linux or macOS) without any change, provided that Python is installed on that system.


Working with Python

To write and execute a Python program, we need a Python interpreter installed on the computer. The interpreter is also known as the Python shell. When the interpreter is started, it displays a special symbol called the Python prompt, written as:

>>>

This prompt indicates that Python is ready to accept instructions from the user. The user can type Python statements at this prompt and execute them.

The NCERT textbook explains that Python programs can be executed in two different modes, depending on the nature of the task being performed.


3.1.1 Execution Modes in Python

There are two ways to run a Python program using the Python interpreter:

  1. Interactive Mode
  2. Script Mode

Each mode serves a different purpose and is used in different situations.


(A) Interactive Mode

In interactive mode, Python executes instructions one line at a time. The user types a statement at the >>> prompt and presses the Enter key. The interpreter immediately executes the statement and displays the result.

This mode is mainly used for:

  • Testing small pieces of code
  • Performing simple calculations
  • Understanding how Python statements work

Example (Interactive Mode):

>>> 5 + 10
15
>>> x = 20
>>> x * 2
40

In this example, Python evaluates each statement as soon as it is entered. The result is displayed immediately.

However, interactive mode has a limitation. The statements entered in this mode cannot be saved for future use. If the interpreter is closed, all previously typed statements are lost, and they must be typed again.

Because of this limitation, interactive mode is suitable only for experimentation and learning, not for writing complete programs.


(B) Script Mode

In script mode, Python programs are written in a file, saved, and then executed. Such files have a .py extension and are called Python scripts.

Script mode is used when:

  • Programs contain many lines
  • Programs need to be saved for future use
  • Programs need to be modified or reused

A Python script can be written using any text editor or an Integrated Development Environment (IDE).

Example (Script Mode):

# Program to calculate sum of two numbers
a = 10
b = 20
sum = a + b
print("Sum =", sum)

When this file is executed, Python reads the program from top to bottom and executes each statement in sequence.

The NCERT textbook clearly states that beginners often start with interactive mode, but as programs grow longer and more meaningful, script mode should always be used.


Important Observation (NCERT-aligned)

  • Interactive mode is useful for learning and testing
  • Script mode is essential for writing real programs
  • Python programs are saved with the .py extension

Version of Python Used

The programs in the NCERT textbook are written using Python 3.7.0. However, any Python 3 version can be used to practice the programs, as the basic syntax remains the same.


Indentation in Python

Python is different from many other programming languages because it uses indentation to define blocks of code. Unlike languages such as C or Java, Python does not use curly braces { } to group statements.

Proper indentation is mandatory in Python. Incorrect indentation leads to errors.

This design choice ensures that Python code is always well-structured and readable, as stated by Guido van Rossum himself.


3.2 Python Keywords

When learning a programming language, one of the first things a learner must understand is that not all words are free to be used as names. Every programming language has certain reserved words that already have a fixed meaning defined by the language itself. In Python, such reserved words are called keywords.

A keyword is a word that is predefined by Python and has a special meaning. These words form the syntax and structure of Python programs. Because their meaning is already fixed, keywords cannot be used as identifiers, that is, they cannot be used as names for variables, functions, or any other program elements.

Python keywords are an essential part of the language because they tell the interpreter what action to perform. For example, keywords such as if, else, and for are used to control the flow of a program, while keywords like def and return are used when working with functions.


Characteristics of Python Keywords

The NCERT textbook highlights several important characteristics of Python keywords:

  1. Keywords have predefined meanings that cannot be changed.
  2. Keywords cannot be used as variable names or function names.
  3. Python keywords are case-sensitive.
  4. The set of keywords depends on the version of Python being used.

For example, True and False are keywords in Python, but true and false are not keywords and are treated as normal identifiers.


Commonly Used Python Keywords

Although Python has many keywords, beginners frequently encounter a smaller set of keywords while writing simple programs. These keywords are grouped according to their purpose.

Purpose Python Keywords
Decision Making if, else, elif
Looping for, while, break, continue
Boolean Values True, False, None
Function Definition def, return
Module Handling import, from, as

Each of these keywords plays a specific role in Python programming and will be discussed in detail in later chapters.


Viewing the List of Python Keywords

Python provides a built-in module called keyword that allows the user to view all the keywords supported by the current Python version.

import keyword
print(keyword.kwlist)

When this program is executed, Python displays a list containing all the keywords. This list may vary slightly depending on the Python version installed on the system.


Using Keywords Incorrectly

If a programmer tries to use a keyword as an identifier, Python raises a syntax error.

Example:

if = 10

This statement produces an error because if is a keyword and cannot be used as a variable name.

πŸ“Œ NCERT Exam Point Using a keyword as an identifier always results in a syntax error, and the program will not execute.


3.3 Identifiers

In Python programs, names are required to refer to different program elements such as variables, functions, objects, and modules. These names are called identifiers.

An identifier is a name given to a program element so that it can be identified and accessed during program execution.

Unlike keywords, identifiers are created by the programmer, but they must follow certain rules defined by Python.


Rules for Naming Identifiers

The NCERT textbook clearly specifies the rules that must be followed while naming identifiers in Python:

  1. An identifier can contain letters (a–z, A–Z), digits (0–9), and the underscore (_) character.
  2. An identifier must begin with a letter or an underscore.
  3. An identifier cannot begin with a digit.
  4. Keywords cannot be used as identifiers.
  5. Special symbols such as @, #, $, %, and - are not allowed.
  6. Identifiers are case-sensitive.

Examples of Valid and Invalid Identifiers

Identifier Valid / Invalid Reason
total Valid Starts with a letter
_count Valid Starts with underscore
marks1 Valid Contains digit (not at start)
1marks Invalid Starts with digit
for Invalid Keyword
total-marks Invalid Hyphen not allowed

Case Sensitivity in Identifiers

Python treats uppercase and lowercase letters as different characters. Therefore, identifiers that differ only in case are considered different identifiers.

Example:

marks = 85
Marks = 90
print(marks)
print(Marks)

Output:

85
90

Here, marks and Marks are treated as two separate variables.

πŸ“Œ NCERT Exam Point Python is a case-sensitive language, so identifiers must be used consistently.


Meaningful Identifier Names

Although Python allows many valid identifiers, programmers are encouraged to use meaningful and descriptive names. This improves readability and makes programs easier to understand and debug.

Example:

totalMarks = 450
studentAge = 16

Such names clearly indicate the purpose of the variable, which is especially useful in larger programs.


Difference Between Keywords and Identifiers

Keywords Identifiers
Reserved by Python Created by programmer
Fixed meaning Meaning decided by programmer
Cannot be modified Can be changed
Cannot be used as names Used to name variables, functions

Understanding this difference is essential for writing correct Python programs.

3.4 Variables

In any program, data must be stored temporarily in the computer’s memory so that it can be processed. For this purpose, programming languages provide a mechanism called variables.

A variable is a named memory location used to store data during the execution of a program. The value stored in a variable can change during program execution, which is why it is called a β€œvariable”.

In Python, variables play a very important role because Python programs rely heavily on variables to store user input, intermediate results, and final output.


Creating and Assigning Variables in Python

Unlike some other programming languages, Python does not require variables to be declared before use. A variable is created automatically when a value is assigned to it for the first time.

Example:

x = 10
name = "Ravi"
marks = 88.5

In the above statements:

  • x stores an integer value
  • name stores a string
  • marks stores a floating-point value

The assignment operator = assigns the value on the right-hand side to the variable on the left-hand side.


Dynamic Typing in Python

One of the most important features of Python, highlighted in the NCERT textbook, is dynamic typing.

Dynamic typing means that:

  • The data type of a variable is decided at runtime
  • The programmer does not need to specify the data type explicitly
  • The same variable can store values of different data types at different times

Example:

x = 10
print(x, type(x))

x = "Python"
print(x, type(x))

Output:

10 <class 'int'>
Python <class 'str'>

In this example, the variable x first stores an integer value and later stores a string value. Python automatically updates the data type of the variable.

πŸ“Œ NCERT Observation This flexibility makes Python easier to use but requires the programmer to be careful while writing programs.


Rules for Variable Names

Since variable names are identifiers, they must follow the same rules as identifiers:

  1. Variable names must begin with a letter or underscore.
  2. They can contain letters, digits, and underscores.
  3. They cannot start with a digit.
  4. Keywords cannot be used as variable names.
  5. Variable names are case-sensitive.

Example:

totalMarks = 450
_total = 100
marks1 = 75

Multiple Assignment

Python allows multiple variables to be assigned values in a single statement. This feature makes programs concise and readable.

Example:

a, b, c = 5, 10, 15
print(a, b, c)

This statement assigns:

  • a the value 5
  • b the value 10
  • c the value 15

Assigning Same Value to Multiple Variables

Python also allows the same value to be assigned to multiple variables in one statement.

Example:

x = y = z = 0
print(x, y, z)

All three variables store the value 0.


Understanding Variable Storage (Conceptual)

Although Python hides memory management from the programmer, it is useful to understand conceptually that:

  • Variables refer to objects stored in memory
  • The variable name acts as a label for the value

When the value of a variable changes, Python internally updates the reference to the new value.


3.5 Data Types

Every value stored in a variable has a data type. A data type defines:

  • The kind of data stored
  • The operations that can be performed on that data

Python provides several built-in data types. In this chapter, the NCERT textbook focuses mainly on basic data types that are sufficient for beginner-level programming.


Common Built-in Data Types in Python

Data Type Description Example
int Whole numbers 10, -5, 0
float Decimal numbers 3.14, -2.5
str Sequence of characters "Python"
bool Logical values True, False

Integer (int) Data Type

The int data type is used to store whole numbers without any decimal part.

Examples:

a = 10
b = -25
c = 0

Integers are commonly used for:

  • Counting
  • Loop control
  • Indexing
  • Mathematical calculations

Floating Point (float) Data Type

The float data type is used to store numbers with decimal points.

Examples:

pi = 3.14
temperature = 36.5

Floating-point numbers are used when:

  • Precision is required
  • Fractions or measurements are involved

String (str) Data Type

A string is a sequence of characters enclosed in single quotes (' ') or double quotes (" ").

Examples:

name = "Asha"
subject = 'Informatics Practices'

Strings are used to store:

  • Names
  • Messages
  • Textual information

Strings can be concatenated using the + operator.

Example:

firstName = "Asha"
lastName = "Sharma"
fullName = firstName + " " + lastName
print(fullName)

Boolean (bool) Data Type

The Boolean data type has only two possible values:

  • True
  • False

Example:

result = True
isPassed = False

Boolean values are commonly used in:

  • Conditional statements
  • Logical expressions
  • Decision making

Checking the Data Type of a Variable

Python provides a built-in function type() to determine the data type of a variable.

Example:

x = 10
y = 3.14
z = "Python"
print(type(x))
print(type(y))
print(type(z))

Type Conversion (Type Casting)

Python allows the conversion of one data type into another using built-in functions such as int(), float(), and str().

Example:

age = int("16")
price = float("99.5")
marks = str(85)

⚠️ If the conversion is not valid, Python raises a runtime error.

Example:

x = int("Python")   # Error

3.6 Operators

In Python, as in all programming languages, operations must be performed on data to produce meaningful results. These operations include tasks such as adding numbers, comparing values, making decisions, and assigning results to variables. To perform such tasks, Python provides special symbols and keywords known as operators.

An operator is a symbol or keyword that tells Python to perform a specific operation on one or more values, known as operands. The result of an operation depends on both the operator used and the type of operands involved.

For example, in the expression:

c = a + b
  • + is the operator
  • a and b are operands
  • c stores the result of the operation

Python supports several types of operators, but in this chapter, the NCERT textbook focuses on the most commonly used ones that beginners need to understand.


Types of Operators in Python

The main categories of operators discussed at this level are:

  1. Arithmetic Operators
  2. Relational (Comparison) Operators
  3. Logical Operators
  4. Assignment Operators

Each category serves a different purpose and is used in different programming situations.


3.6.1 Arithmetic Operators

Arithmetic operators are used to perform mathematical calculations such as addition, subtraction, multiplication, and division. These operators work primarily with numeric data types such as integers and floating-point numbers.

Arithmetic Operators in Python

Operator Meaning Example
+ Addition 10 + 5
- Subtraction 10 - 5
* Multiplication 10 * 5
/ Division 10 / 5
// Floor Division 10 // 3
% Modulus (Remainder) 10 % 3
`` Exponentiation 2 3

Addition (+) Operator

The addition operator is used to add two numbers.

Example:

a = 15
b = 20
sum = a + b
print("Sum =", sum)

Output:

Sum = 35

The addition operator can also be used to concatenate strings.

Example:

firstName = "Asha"
lastName = "Verma"
print(firstName + " " + lastName)

Subtraction (-) Operator

The subtraction operator subtracts one number from another.

Example:

a = 50
b = 20
difference = a - b
print("Difference =", difference)

Output:

Difference = 30

Multiplication (*) Operator

The multiplication operator multiplies two numbers.

Example:

length = 5
breadth = 4
area = length * breadth
print("Area =", area)

Output:

Area = 20

Division (/) Operator

The division operator divides one number by another and always returns a float, even if the result is a whole number.

Example:

a = 10
b = 2
result = a / b
print(result)
print(type(result))

Output:

5.0
<class 'float'>

This behavior is important and often tested in exams.


Floor Division (//) Operator

The floor division operator divides two numbers and returns the integer part of the result by removing the decimal portion.

Example:

a = 10
b = 3
result = a // b
print(result)

Output:

3

Floor division is useful when only the quotient is required, without the remainder.


Modulus (%) Operator

The modulus operator returns the remainder of a division operation.

Example:

a = 10
b = 3
remainder = a % b
print(remainder)

Output:

1

The modulus operator is commonly used to:

  • Check whether a number is even or odd
  • Find remainders in calculations

Example:

number = 7
if number % 2 == 0:
    print("Even")
else:
    print("Odd")

Exponentiation (``) Operator

The exponentiation operator raises a number to the power of another number.

Example:

base = 2
power = 3
result = base  power
print(result)

Output:

8

Complete Arithmetic Example

The following program demonstrates all arithmetic operators together:

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("Exponent:", a  b)

This type of program is frequently used in practical exams.


3.6.2 Relational (Comparison) Operators

Relational operators are used to compare two values. The result of a relational operation is always a Boolean value, either True or False.

Relational Operators in Python

Operator Meaning
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
== Equal to
!= Not equal to

Examples of Relational Operators

a = 10
b = 20

print(a > b)
print(a < b)
print(a == b)
print(a != b)

Output:

False
True
False
True

Relational operators are commonly used in:

  • Conditional statements
  • Loop conditions
  • Logical expressions

3.6.3 Logical Operators

Logical operators are used to combine multiple conditions. They are especially useful when a decision depends on more than one comparison.

Logical Operators in Python

Operator Meaning
and True if both conditions are true
or True if at least one condition is true
not Reverses the result

Examples of Logical Operators

marks = 75
attendance = 80

print(marks >= 40 and attendance >= 75)
print(marks >= 40 or attendance >= 90)
print(not(marks < 40))

Output:

True
True
True

Logical operators are widely used in decision-making programs.


3.6.4 Assignment Operators

Assignment operators are used to assign values to variables. The most common assignment operator is =.

Assignment Operators in Python

Operator Meaning
= Assign
+= Add and assign
-= Subtract and assign
*= Multiply and assign
/= Divide and assign

Examples of Assignment Operators

x = 10
x += 5
print(x)

Output:

15

Expanded form:

x = x + 5

3.7 Expressions

In Python, instructions are not written as isolated symbols. Instead, meaningful statements are formed by combining values, variables, and operators. Such meaningful combinations are known as expressions.

An expression is a combination of constants, variables, and operators that is evaluated by Python to produce a result. Every expression has a value, and in many cases, this value is stored in a variable or used to make a decision.

For example:

result = a + b

Here:

  • a + b is an expression
  • Python evaluates the expression
  • The result is stored in the variable result

Expressions are the backbone of all Python programs, as calculations, comparisons, and decisions are all based on expressions.


Types of Expressions

The NCERT textbook classifies expressions based on the type of operators used in them. At this level, the most important types are:

  1. Arithmetic Expressions
  2. Relational Expressions
  3. Logical Expressions

Each type of expression serves a different purpose and is used in different contexts.


3.7.1 Arithmetic Expressions

An arithmetic expression consists of numeric values (constants or variables) combined using arithmetic operators.

Examples:

10 + 5
a * b
(x + y) / 2

Evaluation of Arithmetic Expressions

Python evaluates arithmetic expressions by following a fixed order of operations, known as operator precedence.

For example:

result = 10 + 5 * 2
print(result)

Output:

20

In this expression, multiplication (*) is performed before addition (+).


Using Parentheses in Arithmetic Expressions

Parentheses are used to change the order of evaluation.

Example:

result = (10 + 5) * 2
print(result)

Output:

30

This time, the expression inside the parentheses is evaluated first.

πŸ“Œ NCERT Observation Using parentheses improves both correctness and readability of expressions.


Complete Arithmetic Expression Program

a = 10
b = 5
c = 2

result1 = a + b * c
result2 = (a + b) * c

print("Without parentheses:", result1)
print("With parentheses:", result2)

Output:

Without parentheses: 20
With parentheses: 30

3.7.2 Relational Expressions

A relational expression is formed using relational (comparison) operators. These expressions compare two values and always produce a Boolean result, either True or False.

Examples:

marks >= 40
a == b
x != y

Evaluating Relational Expressions

marks = 75
print(marks >= 40)
print(marks < 40)

Output:

True
False

Relational expressions are most commonly used in:

  • if statements
  • Loop conditions
  • Logical expressions

Relational Expressions with Variables

a = 10
b = 20

print(a > b)
print(a <= b)
print(a == b)

Output:

False
True
False

πŸ“Œ NCERT Exam Point Relational expressions always return Boolean values.


3.7.3 Logical Expressions

A logical expression is formed by combining two or more relational expressions using logical operators such as and, or, and not.

Logical expressions are used when a decision depends on multiple conditions.

Example:

marks >= 40 and attendance >= 75

Evaluating Logical Expressions

marks = 65
attendance = 80

print(marks >= 40 and attendance >= 75)
print(marks >= 40 or attendance >= 90)
print(not(marks < 40))

Output:

True
True
True

Truth Table Concept (Explanation)

Although NCERT does not present formal truth tables here, it expects students to understand how logical operators work:

  • and returns True only if both conditions are true
  • or returns True if any one condition is true
  • not reverses the result

This understanding is crucial for writing correct conditional statements.


Mixed Expressions

In real programs, expressions often contain arithmetic, relational, and logical operators together. Such expressions are called mixed expressions.

Example:

marks = 70
attendance = 80

result = (marks + 10) >= 80 and attendance >= 75
print(result)

Python evaluates mixed expressions by applying:

  1. Arithmetic operations
  2. Relational operations
  3. Logical operations

Step-by-Step Evaluation Example

marks = 60
attendance = 85

expression = marks + 10 >= 70 and attendance >= 75
print(expression)

Explanation:

  1. marks + 10 β†’ 70
  2. 70 >= 70 β†’ True
  3. attendance >= 75 β†’ True
  4. True and True β†’ True

Operator Precedence (Conceptual)

When multiple operators appear in an expression, Python follows a fixed order of precedence.

Simplified precedence order:

  1. Parentheses ()
  2. Exponentiation ``
  3. Multiplication, Division, Modulus
  4. Addition, Subtraction
  5. Relational operators
  6. Logical operators

πŸ“Œ NCERT Exam Tip Always use parentheses to avoid ambiguity and ensure correct evaluation.


3.8 Input and Output

A computer program becomes useful only when it can accept data, process it, and display results. In Python, these tasks are performed using input and output statements. The NCERT textbook emphasises that understanding input and output is essential because almost every program requires interaction with the user.

In Python, input refers to the data entered by the user, while output refers to the information displayed by the program after processing that data.


3.8.1 Input in Python

Python provides a built-in function called input() to accept input from the user. When the input() function is executed, the program waits for the user to type some data and press the Enter key.

Basic Use of input()

name = input("Enter your name: ")
print(name)

In this program:

  • The message inside the quotes is displayed on the screen.
  • The user types a value.
  • The value entered by the user is stored in the variable name.

Important Property of input()

A very important point highlighted in the NCERT textbook is that:

The input() function always returns data as a string, regardless of what the user enters.

Example:

age = input("Enter your age: ")
print(age)
print(type(age))

Even if the user enters a number, Python treats it as a string.

Output:

16
<class 'str'>

3.8.2 Type Conversion of Input

Since input data is always read as a string, it often needs to be converted into the required data type before performing calculations. This process is known as type conversion or type casting.

Converting Input to Integer

age = int(input("Enter your age: "))
print(age)
print(type(age))

Here:

  • input() reads the value as a string
  • int() converts it into an integer

Converting Input to Float

price = float(input("Enter price: "))
print(price)

Common Mistake (NCERT Emphasis)

If type conversion is not done, arithmetic operations may produce incorrect results or errors.

Example:

a = input("Enter first number: ")
b = input("Enter second number: ")
print(a + b)

If the user enters 10 and 20, the output will be:

1020

This happens because string concatenation occurs instead of addition.

Correct program:

a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print(a + b)

Runtime Error During Input Conversion

If the user enters invalid data, type conversion causes a runtime error.

Example:

x = int(input("Enter a number: "))

If the user enters abc, Python raises an error. This concept is discussed further in the chapter on Exception Handling.


3.8.3 Output in Python

Python uses the print() function to display output on the screen. The output may include:

  • Text
  • Variable values
  • Results of expressions

Basic Use of print()

print("Welcome to Python")

Printing Variables

name = "Amit"
print(name)

Printing Multiple Values

The print() function can display multiple values separated by commas.

a = 10
b = 20
print("Sum =", a + b)

Python automatically inserts a space between values.


Printing Expressions

x = 5
y = 3
print(x * y)

Using print() with Strings and Numbers

marks = 85
print("Marks obtained:", marks)

This is the most common and recommended way of displaying output.


3.8.4 Formatting Output (Conceptual)

While NCERT does not introduce advanced formatting here, it expects students to understand clear and readable output.

Example:

length = 10
breadth = 5
area = length * breadth
print("Length =", length)
print("Breadth =", breadth)
print("Area =", area)

Clear output improves program readability and user understanding.


Complete Input–Output Program Example

name = input("Enter student name: ")
marks1 = int(input("Enter marks in Subject 1: "))
marks2 = int(input("Enter marks in Subject 2: "))

total = marks1 + marks2
average = total / 2

print("Student Name:", name)
print("Total Marks:", total)
print("Average Marks:", average)

This program demonstrates:

  • Input using input()
  • Type conversion
  • Arithmetic expressions
  • Output using print()

Such programs are frequently asked in practical exams.


The NCERT textbook implicitly points out several common errors:

  1. Forgetting to convert input to numeric type
  2. Mixing strings and numbers incorrectly
  3. Writing unclear output statements
  4. Assuming input() returns numbers automatically

Understanding these issues helps avoid logical and runtime errors.


3.9 Debugging

While writing programs, it is very common for errors to occur. A program may fail to run, may terminate unexpectedly, or may produce incorrect results. The process of finding and correcting these errors is known as debugging.

The NCERT textbook emphasises that debugging is an essential skill for programmers. Writing error-free programs in the first attempt is rare, especially for beginners. Therefore, understanding different types of errors and learning how to correct them is a fundamental part of programming.


Types of Errors in Python

Errors in Python programs are broadly classified into three main categories:

  1. Syntax Errors
  2. Runtime Errors
  3. Logical Errors

Each type of error occurs at a different stage of program execution and requires a different approach to identify and correct it.


3.9.1 Syntax Errors

A syntax error occurs when the rules of the Python language are violated. Syntax errors are detected before the program starts executing. When such an error occurs, Python displays an error message and does not execute the program until the error is corrected.

Common Causes of Syntax Errors

  • Missing colon (:) after if, for, or while
  • Incorrect indentation
  • Missing or mismatched brackets
  • Incorrect spelling of keywords

Example of Syntax Error

if marks >= 40
    print("Pass")

This program produces a syntax error because the colon after the if statement is missing.


Indentation Errors

Python uses indentation to define blocks of code, unlike many other programming languages that use braces { }. Therefore, incorrect indentation results in a syntax error.

Example:

if marks >= 40:
print("Pass")

In this case, the print() statement is not properly indented.

πŸ“Œ NCERT Observation Indentation is mandatory in Python, and even a small indentation mistake can cause a syntax error.


3.9.2 Runtime Errors

A runtime error occurs while the program is running. These errors are not detected by the interpreter until the program reaches the line that causes the error.

Runtime errors usually occur due to:

  • Invalid operations
  • Incorrect input
  • Mathematical errors

Example of Runtime Error

a = 10
b = 0
print(a / b)

This program results in a runtime error because division by zero is not allowed.


Another Runtime Error Example

x = int(input("Enter a number: "))

If the user enters a non-numeric value, Python raises a runtime error.


Handling Runtime Errors

In this chapter, NCERT only introduces the concept of runtime errors. Techniques for handling such errors using exception handling are discussed in a later chapter.


3.9.3 Logical Errors

A logical error occurs when the program runs without any error messages but produces incorrect output.

Logical errors are the most difficult to identify because the program appears to run normally.

Example of Logical Error

length = 10
breadth = 5
area = length + breadth   # Incorrect formula
print("Area =", area)

The program executes successfully, but the output is incorrect because the formula for area is wrong.


Identifying Logical Errors

Logical errors can be identified by:

  • Carefully checking program logic
  • Verifying formulas and conditions
  • Testing the program with different inputs
  • Comparing output with expected results

3.9.4 Debugging Techniques

Although NCERT does not introduce advanced debugging tools in this chapter, it suggests simple techniques that beginners should follow:

  1. Read error messages carefully
  2. Check syntax and indentation
  3. Verify variable values
  4. Test the program with simple inputs
  5. Execute the program step by step

Using print() for Debugging

One of the simplest debugging techniques is using the print() function to display intermediate values.

Example:

a = int(input("Enter a: "))
b = int(input("Enter b: "))
print("a =", a)
print("b =", b)
print("Sum =", a + b)

This helps verify whether the input values are correct.


Difference Between Syntax, Runtime, and Logical Errors

Error Type When Detected Program Executes? Example
Syntax Error Before execution ❌ No Missing colon
Runtime Error During execution ❌ Stops midway Division by zero
Logical Error During execution βœ”οΈ Yes Wrong formula

Understanding this difference is essential for effective debugging.


3.10 Functions

As programs become longer and more complex, writing all instructions repeatedly becomes inefficient and difficult to manage. To solve this problem, Python provides a powerful concept called functions.

A function is a named block of code that performs a specific task. Once a function is defined, it can be called (used) multiple times in a program. This helps in reducing repetition, improving readability, and making programs easier to debug and maintain.

The NCERT textbook introduces functions at this stage to help students understand how large problems can be broken into smaller, manageable parts.


Why Functions Are Needed

Without functions:

  • Code becomes repetitive
  • Programs become lengthy and difficult to understand
  • Errors are harder to locate and fix

With functions:

  • Code can be reused
  • Programs become structured
  • Changes need to be made at only one place

Basic Structure of a Function

A function in Python is defined using the keyword def.

def function_name():
    statements
  • def tells Python that a function is being defined
  • function_name is the name of the function
  • Statements inside the function must be indented

To use a function, it must be called.

function_name()

Types of Functions in Python

Python supports two types of functions:

  1. Built-in Functions
  2. User-defined Functions

3.10.1 Built-in Functions

Built-in functions are functions that are already available in Python. These functions can be used directly without defining them.

Some commonly used built-in functions at this level are:

  • print()
  • input()
  • len()
  • type()
  • range()

Example 1: Using Built-in Functions

name = "Informatics Practices"
print(name)
print(len(name))
print(type(name))

Explanation:

  • print() displays output
  • len() returns number of characters in the string
  • type() shows the data type of the variable

This example shows how built-in functions simplify common tasks.


3.10.2 User-Defined Functions

A user-defined function is a function created by the programmer to perform a specific task.

Let us now understand user-defined functions through multiple detailed examples.


Example 2: Simple User-Defined Function (No Parameters)

def greet():
    print("Welcome to Python Programming")
    print("This is Informatics Practices")

greet()

Explanation:

  1. The function greet() is defined using def
  2. It contains two print statements
  3. The function is executed only when it is called
  4. Calling greet() runs all statements inside the function

πŸ“Œ Important NCERT Point Defining a function does not execute it. A function runs only when it is called.


Example 3: Function to Display Square of a Number

def display_square():
    number = int(input("Enter a number: "))
    square = number * number
    print("Square =", square)

display_square()

Explanation:

  • Input is taken inside the function
  • Calculation is performed inside the function
  • Output is displayed inside the function
  • The function performs a complete task independently

This example shows how functions encapsulate logic.


3.10.3 Functions with Parameters

Functions become more useful when they accept parameters. A parameter is a value passed to a function when it is called.


Example 4: Function with One Parameter

def show_square(num):
    print("Number =", num)
    print("Square =", num * num)

show_square(5)
show_square(8)

Explanation:

  1. num is a parameter
  2. The value passed during function call is assigned to num
  3. Same function works for different values
  4. Code reuse is achieved

Example 5: Function with Two Parameters (Addition Program)

def add_numbers(a, b):
    result = a + b
    print("Sum =", result)

add_numbers(10, 20)
add_numbers(5, 7)

Explanation:

  • a and b receive values during function call
  • Function performs addition
  • Same logic reused multiple times

This is a very common exam-level function example.


3.10.4 Function Returning a Value

Sometimes a function needs to send a result back to the calling statement. This is done using the return statement.


Example 6: Function Returning a Value

def calculate_average(m1, m2, m3):
    total = m1 + m2 + m3
    avg = total / 3
    return avg

average = calculate_average(80, 70, 90)
print("Average Marks =", average)

Explanation:

  1. Function calculates average
  2. return sends the value back
  3. Returned value is stored in average
  4. Function separates calculation from output

πŸ“Œ NCERT Observation A function can return a value and that value can be used later in the program.


3.10.5 Function with Decision Making

Functions can contain conditional statements.


Example 7: Function to Check Pass or Fail

def check_result(marks):
    if marks >= 40:
        return "Pass"
    else:
        return "Fail"

result1 = check_result(75)
result2 = check_result(32)

print("Student 1:", result1)
print("Student 2:", result2)

Explanation:

  • Function checks condition internally
  • Different return values based on logic
  • Output handled outside the function
  • Improves modularity of code

Function Call Flow (Conceptual Explanation)

When a function is called:

  1. Python jumps to the function definition
  2. Parameters receive values
  3. Statements inside the function execute
  4. return sends value back (if present)
  5. Control returns to the calling statement

Understanding this flow is very important for exams and debugging.


Common Errors While Using Functions

NCERT expects students to avoid these mistakes:

  • Forgetting parentheses while calling function
  • Using variables inside function without parameters
  • Confusing print() with return
  • Indentation errors inside function

Difference Between print() and return

print() return
Displays output Sends value back
Cannot be reused Can be reused
Used for output Used for computation

3.11 if..else Statements

In real-life situations, decisions are taken based on certain conditions. Similarly, in programming, a program often needs to make decisions and execute different blocks of code depending on whether a condition is true or false. Python provides conditional statements to handle such situations.

The most commonly used conditional statement in Python is the if..else statement. The NCERT textbook introduces this concept to help students understand how programs can react differently to different inputs.


Understanding Conditions

A condition is an expression that evaluates to either True or False. Conditions are usually formed using relational operators and logical operators.

Example conditions:

marks >= 40
age < 18
number % 2 == 0

The result of each condition is a Boolean value.


3.11.1 Simple if Statement

The simplest form of decision-making statement is the if statement.

Syntax of if Statement

if condition:
    statement(s)
  • If the condition evaluates to True, the statements inside the if block are executed.
  • If the condition evaluates to False, the statements inside the if block are skipped.

Example 1: Simple if Statement

marks = int(input("Enter marks: "))

if marks >= 40:
    print("Pass")

Explanation:

  1. Marks are taken as input
  2. Condition marks >= 40 is checked
  3. If true, "Pass" is printed
  4. If false, nothing happens

This program demonstrates one-way decision making.


3.11.2 if..else Statement

The if..else statement is used when two alternative actions are required.

Syntax of if..else Statement

if condition:
    statement(s)
else:
    statement(s)
  • The if block executes when the condition is True
  • The else block executes when the condition is False

Example 2: if..else Statement

marks = int(input("Enter marks: "))

if marks >= 40:
    print("Pass")
else:
    print("Fail")

Explanation:

  • If marks are 40 or more, student passes
  • Otherwise, student fails
  • Exactly one block executes

This is a two-way decision structure.


3.11.3 if..elif..else Ladder

Sometimes a decision involves more than two choices. In such cases, Python provides the if..elif..else ladder.

Syntax

if condition1:
    statements
elif condition2:
    statements
elif condition3:
    statements
else:
    statements

Python checks conditions from top to bottom. The first condition that evaluates to True is executed.


Example 3: Grading System

marks = int(input("Enter marks: "))

if marks >= 90:
    print("Grade A")
elif marks >= 75:
    print("Grade B")
elif marks >= 60:
    print("Grade C")
elif marks >= 40:
    print("Grade D")
else:
    print("Fail")

Explanation:

  • Conditions are checked sequentially
  • Once a true condition is found, remaining checks are skipped
  • else executes when all conditions are false

πŸ“Œ NCERT Exam Point Only one block in an if..elif..else ladder executes.


3.11.4 Nested if Statements

An if statement written inside another if statement is called a nested if.

Nested if statements are used when a decision depends on multiple levels of conditions.


Example 4: Nested if Statement

age = int(input("Enter age: "))
citizen = input("Are you a citizen (yes/no): ")

if age >= 18:
    if citizen == "yes":
        print("Eligible to vote")
    else:
        print("Not eligible: Not a citizen")
else:
    print("Not eligible: Under age")

Explanation:

  1. First condition checks age
  2. Second condition checks citizenship
  3. Decision depends on both conditions

This example clearly shows decision within a decision.


3.11.5 Using Logical Operators with if Statements

Logical operators allow combining multiple conditions in a single if statement.


Example 5: Logical Operators in if Statement

marks = int(input("Enter marks: "))
attendance = int(input("Enter attendance percentage: "))

if marks >= 40 and attendance >= 75:
    print("Eligible for promotion")
else:
    print("Not eligible for promotion")

Explanation:

  • Both conditions must be true
  • Logical and operator is used
  • Improves clarity and reduces nesting

Indentation in if Statements

Indentation is mandatory in Python and determines the block of code executed under if or else.

Incorrect indentation causes syntax errors or logical errors.

Example of incorrect indentation:

if marks >= 40:
print("Pass")   # Error

Common Errors in if..else Statements

NCERT expects students to avoid:

  • Missing colon after if, elif, or else
  • Incorrect indentation
  • Using assignment = instead of comparison ==
  • Forgetting to convert input to integer

Difference Between if and if..else

if if..else
Executes code only when condition is true Executes one of two blocks
One-way decision Two-way decision
No alternative action Alternative action present

3.12 for Loop

In many programming situations, a set of statements needs to be executed repeatedly. Writing the same statements again and again is inefficient and makes programs lengthy and difficult to understand. To solve this problem, programming languages provide a structure called a loop.

A loop is a control structure that allows a block of code to be executed multiple times. Python provides different types of loops, and the NCERT textbook introduces the for loop first because it is simple and commonly used.

The for loop is generally used when the number of repetitions is known in advance.


Understanding the for Loop

The for loop in Python is used to iterate over a sequence of values. These values may come from:

  • A sequence of numbers
  • A string
  • A range of values

At this level, NCERT focuses on using the for loop with the range() function.


Syntax of for Loop

for variable in sequence:
    statements
  • variable takes one value at a time from the sequence
  • The statements inside the loop are executed once for each value
  • Indentation is mandatory

3.12.1 The range() Function

The range() function is commonly used with the for loop to generate a sequence of numbers.

Forms of range()

  1. range(stop)
  2. range(start, stop)
  3. range(start, stop, step)

range(stop)

This form generates numbers starting from 0 up to (but not including) stop.

Example:

for i in range(5):
    print(i)

Output:

0
1
2
3
4

range(start, stop)

This form generates numbers starting from start up to (but not including) stop.

Example:

for i in range(1, 6):
    print(i)

Output:

1
2
3
4
5

range(start, stop, step)

This form generates numbers with a specific gap (step) between values.

Example:

for i in range(2, 11, 2):
    print(i)

Output:

2
4
6
8
10

3.12.2 Basic for Loop Examples


Example 1: Printing Numbers

for i in range(1, 11):
    print(i)

Explanation:

  • Loop starts at 1
  • Stops at 10
  • Prints numbers from 1 to 10

Example 2: Printing Squares of Numbers

for i in range(1, 6):
    print("Number:", i, "Square:", i * i)

Explanation:

  • i takes values from 1 to 5
  • Square is calculated inside the loop
  • Output is displayed for each iteration

3.12.3 Using for Loop for Calculations


Example 3: Sum of First n Natural Numbers

n = int(input("Enter a number: "))
sum = 0

for i in range(1, n + 1):
    sum = sum + i

print("Sum =", sum)

Explanation:

  1. Variable sum is initialized to 0
  2. Loop runs from 1 to n
  3. Each value is added to sum
  4. Final result is displayed

Example 4: Factorial of a Number

n = int(input("Enter a number: "))
fact = 1

for i in range(1, n + 1):
    fact = fact * i

print("Factorial =", fact)

Explanation:

  • Factorial is calculated using repeated multiplication
  • Loop executes exactly n times

3.12.4 for Loop with Conditional Statements

A for loop can be combined with if statements to perform conditional operations.


Example 5: Display Even Numbers

for i in range(1, 21):
    if i % 2 == 0:
        print(i)

Explanation:

  • Loop iterates from 1 to 20
  • Condition checks even numbers
  • Only even numbers are printed

3.12.5 Using for Loop with Strings

The for loop can also iterate over characters of a string.


Example 6: Display Characters of a String

word = "Python"

for ch in word:
    print(ch)

Explanation:

  • Loop iterates over each character
  • One character is printed per iteration

3.12.6 Nested for Loop (Introduction)

When a for loop is placed inside another for loop, it is called a nested for loop. Nested loops are used when one repetition depends on another.

NCERT introduces nested loops briefly here and explains them in detail in the next section.


Example 7: Simple Nested Loop

for i in range(1, 4):
    for j in range(1, 3):
        print(i, j)

Explanation:

  • Outer loop controls rows
  • Inner loop controls columns
  • Inner loop runs completely for each outer loop iteration

Common Errors in for Loops

Students should avoid the following mistakes:

  • Forgetting colon : after for
  • Incorrect indentation
  • Wrong range values
  • Infinite loops due to incorrect logic

Difference Between for Loop and while Loop (Conceptual)

for Loop while Loop
Used when repetitions are known Used when repetitions are unknown
Uses sequence or range Uses condition
Simpler syntax More flexible

3.13 Nested Loops

In programming, situations often arise where a task must be repeated inside another repeated task. For example, printing rows and columns, generating tables, or creating patterns. To handle such situations, Python allows the use of nested loops.

A nested loop is a loop that is written inside another loop. The loop that contains another loop is called the outer loop, and the loop inside it is called the inner loop.

The NCERT textbook introduces nested loops to help students understand multi-level repetition and how loops interact with each other during execution.


How Nested Loops Work

When loops are nested:

  • The outer loop controls the number of times the inner loop executes
  • For each iteration of the outer loop, the inner loop runs completely

This means:

Inner loop executes fully for every single iteration of the outer loop.


General Syntax of Nested Loops

for outer_variable in outer_sequence:
    for inner_variable in inner_sequence:
        statements

Indentation is very important. Incorrect indentation leads to errors or wrong output.


Understanding Execution Flow (Conceptual)

Consider the following structure:

for i in range(1, 4):
    for j in range(1, 3):
        print(i, j)

Execution happens as follows:

  1. i = 1

    • Inner loop runs with j = 1, 2
  2. i = 2

    • Inner loop runs with j = 1, 2
  3. i = 3

    • Inner loop runs with j = 1, 2

Total executions = outer loop Γ— inner loop


3.13.1 Simple Nested Loop Example

Example 1: Displaying Pairs of Numbers

for i in range(1, 4):
    for j in range(1, 4):
        print(i, j)

Output:

1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

Explanation:

  • Outer loop controls the first number
  • Inner loop controls the second number
  • Each pair is printed one by one

This type of program helps in understanding row–column structure.


3.13.2 Nested Loops for Tables

Example 2: Multiplication Tables (1 to 5)

for i in range(1, 6):
    print("Table of", i)
    for j in range(1, 11):
        print(i, "x", j, "=", i * j)
    print()

Explanation:

  • Outer loop selects the table number
  • Inner loop prints multiples from 1 to 10
  • Blank line improves readability

This is a very common exam-level example.


3.13.3 Nested Loops with Conditions

Nested loops can include if statements to control output.


Example 3: Printing Only Even Products

for i in range(1, 6):
    for j in range(1, 6):
        product = i * j
        if product % 2 == 0:
            print(product, end=" ")
    print()

Explanation:

  • Product is calculated inside inner loop
  • Condition checks even numbers
  • Only even products are printed

3.13.4 Pattern Printing Using Nested Loops

Pattern printing is a classic application of nested loops and is frequently asked in exams.


Example 4: Square Star Pattern

for i in range(1, 5):
    for j in range(1, 5):
        print("*", end=" ")
    print()

Output:

* * * *
* * * *
* * * *
* * * *

Explanation:

  • Outer loop controls rows
  • Inner loop prints stars in each row

Example 5: Right-Angled Triangle Pattern

for i in range(1, 6):
    for j in range(1, i + 1):
        print("*", end=" ")
    print()

Output:

*
* *
* * *
* * * *
* * * * *

Explanation:

  • Inner loop depends on outer loop value
  • Number of stars increases row by row

Example 6: Number Pattern

for i in range(1, 5):
    for j in range(1, i + 1):
        print(j, end=" ")
    print()

Output:

1
1 2
1 2 3
1 2 3 4

Explanation:

  • Numbers reset for each row
  • Demonstrates inner loop variable control

3.13.5 Nested Loops for Matrix-Like Output

Example 7: Displaying Row and Column Numbers

for row in range(1, 4):
    for col in range(1, 4):
        print("(", row, ",", col, ")", end=" ")
    print()

Explanation:

  • Commonly used to represent matrix coordinates
  • Helps visualize two-dimensional data

Common Errors in Nested Loops

NCERT expects students to avoid:

  • Incorrect indentation
  • Confusing outer and inner loop variables
  • Forgetting to reset inner loop
  • Logical mistakes in loop ranges

Key Observations (NCERT-Oriented)

  • Inner loop executes completely for each outer loop iteration
  • Total executions = outer loop Γ— inner loop
  • Nested loops are powerful but must be used carefully
  • Pattern programs help understand loop interaction

Difference Between Single Loop and Nested Loop

Single Loop Nested Loop
One level of repetition Multiple levels of repetition
Simple problems Complex, structured problems
Executes once per iteration Inner loop repeats multiple times

Page last updated: 19-Jan-2026
Last Change: "some changes for timezone and git checkin history pull by hugo" (#b34f1bc)