4. Elements of Python
Higher Secondary · Computer Applications / Commerce

Elements of Python

Python is an interpreted, dynamically-typed, easy-to-learn language created by Guido van Rossum in 1991. This chapter covers how Python programs run, comments, keywords, identifiers, variables, data types, operators, precedence, and input/output — with a live REPL to try it yourself.

"Programming isn't about what you know; it's about what you can figure out." — Chris Pine
4.1.2 · Live Tool

Try the Python Shell

The Python interpreter (Python Shell) shows the >>> prompt when it is ready for a command — this is Interactive Mode. Type an expression below and see it evaluate immediately, the same way it would in IDLE.

Python Interactive Shell

● live
>>>
Result
—
type()
—
Category
—
10 // 3 10 % 3 2 ** 5 8 == 5 'New' + 'Delhi' 'Hi' * 3 (30 - 20) * 5 not (5 < 3) 8 > 5 and 3 < 5
Supports arithmetic (+ - * / // % **), comparisons, and / or / not, parentheses, and quoted strings — enough to explore operators and precedence from this chapter.
4.1

Introduction & Program Execution

Python is free, open-source, and platform-independent — the interpreter executes code line by line. It can be downloaded from python.org and written using an interpreter, an IDE, or an online platform. There are three ways to write and run a Python program.

Interactive Modei

REPL (Read–Eval–Print–Loop). Type a statement at the >>> prompt and it executes immediately. Good for testing single-line statements — but nothing is saved.

Scripting Modeii

Write multiple statements and save the file with a .py extension using an editor such as IDLE, and run it with Run → Run Module (F5).

Online Platform Modeiii

Write and run Python in a web browser with no local installation — e.g. Google Colab, Replit, Kaggle Notebooks, Deepnote, Binder.

Advantages of Online Platforms

No installation required · runs in the browser · instant output · works on any operating system.

Limitations of Online Platforms

Needs an internet connection · limited file handling · not suitable for large projects.

IDLE Shell — Interactive Mode
>>> 5+3 8 >>> 8-2 6 >>>
sample.py — Scripting Mode (Run Module → output on shell)
print("Python") print("Programming") ===== RESTART: sample.py ===== Python Programming
4.2

Python Comments

Comments explain notes within the code for programmers to read and understand. The Python interpreter completely ignores comments during execution — they exist purely for internal documentation.

Single-line Comment

Begins with #. Anything written after # on that line is ignored.

Multi-line Comment

Python has no dedicated symbol — a string in triple quotes (''' or """) acts as a comment if it is not assigned to a variable or used in code.

Program 4.1 — Single-line comment
# Simple program print("Welcome to Python") Output: Welcome to Python
Program 4.2 — Multi-line comment
'''Program 4.2 Multi-line Comment''' print("Welcome to Python") Output: Welcome to Python
4.3 – 4.4

Keywords & Identifiers

A keyword is a reserved word with a special meaning in Python — all keywords except None, True and False are lowercase. An identifier is a name used to define a variable, function, class, or module.

Table 4.1 — Python Keywords

False
await
else
import
pass
None
break
elif
in
raise
True
class
except
is
return
and
continue
finally
lambda
try
as
def
for
nonlocal
while
assert
del
from
not
with
async
if
global
or
yield
—

Rules for Naming Identifiers

Rules

Only letters, digits, or underscore allowed · must not start with a digit · Python keywords cannot be used · no whitespace or special characters · case-sensitive (Grade, grade, GRADE are all different).

Valid vs Invalid

Valid: totalamount, score1, value, basic_pay
Invalid: user@name (special character), return (keyword), total value (whitespace), 2A (starts with digit)

4.5 – 4.6

Variables & Data Types

Variables are symbolic names used to store data that may change during execution — assigned using =. Python is dynamically typed, so a variable's data type changes automatically when reassigned. A data type specifies what kind of value a variable can hold.

Example 4.1 — Variables
rollno = 12 # rollno is an integer name = "Arun" # name is a string price = 85.5 # price is floating point n = 10 # n is an integer n = "Hello" # now n is string n = True # now n is Boolean

Classification of Python Data Types

Numericint / float / complex

Integer (whole numbers, e.g. 27, -36), Float (fractional, e.g. 3.5, -12.75), Complex (a + bj — real part a, imaginary part b).

Booleanbool

One of two logical values: True or False.

Sequencestr / list / tuple

Ordered values accessed by index (starting at 0).
String — immutable characters.
List — mutable, in [ ].
Tuple — immutable, in ( ).

NoneNoneType

Represents the absence of a value — nothing, null, or empty result.

Setset

An unordered collection of unique elements in { } — mutable, duplicates are eliminated, not accessed by index.

Mappingdict

Dictionary — stores key–value pairs in { }, values accessed via their key. Mutable; keys can be added or removed.

Mutable vs Immutable

Mutable objects

Value can be changed after creation — List, Set, Dictionary.

Immutable objects

Value cannot be modified after creation — Numeric, String, Boolean, Tuple.

Example 4.4 & 4.5 — String and List indexing
>>> s1 = "Programming" >>> print(s1[0]) P >>> print(s1[-1]) # last character g >>> x = [10, "Delhi", 65.5, 'A2', 40] >>> print(x[3]) A2 >>> print(x[-2]) # same position as x[3] A2
Example 4.10 — Dictionary
>>> mark = {'Diya': 70, 'Biju': 65, 'Thomas': 58} >>> print(mark['Biju']) # Key Biju, Value 65 65 >>> mark['Fathima'] = 75 # Adding a new key-value pair >>> del mark['Diya'] # Removing a key-value pair >>> print(mark) {'Biju': 65, 'Thomas': 58, 'Fathima': 75}
4.7

Operators

Operators are special symbols that carry out operations on values or variables: Arithmetic, Assignment, Relational, Logical, Identity, and Membership operators.

4.7.1 Arithmetic Operators

OperatorNameDescriptionExample
+Addition / ConcatenationAdds two numbers, or joins two strings5 + 2 = 7 · 'New'+'Delhi' = 'NewDelhi'
-SubtractionSubtracts two numbers5 - 2 = 3
*MultiplicationMultiplies two numbers, or repeats a string by an integer5 * 2 = 10 · 'Hi'*3 = 'HiHiHi'
/DivisionDivides two numbers5 / 2 = 2.5
//Floor DivisionReturns floored (rounded down) integer quotient5//2 = 2 · -5//2 = -3
%ModulusReturns remainder after division5 % 2 = 1
**ExponentiationRaises base to the power of exponent5**2 = 25

4.7.2 Assignment Operators

OperatorNameSame asExample
=Assignment—a = 10
+=Addition Assignmenta = a + 5a=10 → a+=5 → 15
-=Subtraction Assignmenta = a - 5a=10 → a-=5 → 5
*=Multiplication Assignmenta = a * 5a=10 → a*=5 → 50
/=Division Assignmenta = a / 5a=10 → a/=5 → 2.0
//=Floor Division Assignmenta = a // 5a=10 → a//=5 → 2
%=Modulus Assignmenta = a % 5a=10 → a%=5 → 0
**=Exponent Assignmenta = a ** 5a=10 → a**=5 → 100000

4.7.3 Relational Operators

OperatorNameExample (a=8, b=5)
==Equala==b → False
!=Not equala!=b → True
<Less thana<b → False
>Greater thana>b → True
<=Less than or equala<=b → False
>=Greater than or equala>=b → True

4.7.4 Logical Operators

OperatorNameDescriptionExample (a=20, b=10)
andLogical ANDTrue only if both expressions are Truea>b and b<a → True
orLogical ORTrue if at least one expression is Truea<b or b>a → False
notLogical NOTReverses the resultnot(a<b) → True

4.7.5 Identity Operators (used to check whether two variables refer to the same object in memory)

OperatorDescriptionExample
isTrue if two variables refer to the same object in memoryx=[1,2,3]; y=[1,2,3]; x is y → False (different objects)
is notTrue if two variables do NOT refer to the same objectz=x; x is not z → False (same object)

4.7.6 Membership Operators (used to check whether a value or variable is found in a sequence)

OperatorDescriptionExample
inTrue if a value is found in a sequencea=[10,20,30]; 10 in a → True
not inTrue if a value is NOT found in a sequencetext='Python'; 'P' not in text → False
4.8

Precedence of Operators

An expression is a combination of values, variables, and operators. When an expression has more than one operator, precedence decides which operation happens first. Precedence level 1 is the highest priority.

LevelOperator(s)Description
1( )Parentheses — group expressions, override normal precedence
2**Exponentiation
3+, -Unary plus, unary minus
4*, /, //, %Multiplication, division, floor division, modulus
5+, -Addition, Subtraction
6==, !=, >, <, >=, <=, is, is not, in, not inRelational, identity, and membership operators
7notLogical NOT
8andLogical AND
9orLogical OR
Worked examples
40 + 50 * 3 # * has higher precedence than + 40 + 150 190 (30 - 20) * 5 # parentheses override normal precedence 10 * 5 50 60 / 5 - (6 + 2) # parentheses first, then / before - 60 / 5 - 8 12.0 - 8 4.0
4.9

Input and Output Statements

Python uses the built-in functions input() and print() to take data from the keyboard and display output on screen.

Input Statement

variable = input("Prompt message") — always returns a string value.

Output Statement

print("Display message") — can print strings, numbers, or the values of variables.

Example 4.11 — Input
name = input("Enter your name : ") print("Entered Name : " + name) Output: Enter your name : Akhil Entered Name : Akhil
Example 4.12 — Add two integers
num1 = int(input("Enter first number : ")) num2 = int(input("Enter second number : ")) total = num1 + num2 print("Total :", total) Output: Enter first number : 10 Enter second number : 20 Total : 30
Try Yourself

Quick Recap

Tap a question to reveal the answer.

Who developed the Python programming language, and when?

Guido van Rossum, in 1991.

What does the symbol >>> represent?

The Python prompt — it indicates the interpreter is ready to accept a command (Interactive Mode).

What symbol begins a single-line comment, and what extension is used to save a Python program?

Single-line comments begin with #. Python programs are saved with the .py extension.

What is the // operator used for?

Floor division — it returns the floored (rounded-down) integer quotient of a division, e.g. -5//2 = -3.

Which data type stores key–value pairs, and which collection type is unordered?

Dictionary (dict) stores key–value pairs. Set is the unordered collection among List, Tuple, Set, and String.

Which operator is used to check object identity?

is (and its negation is not) — they check whether two variables refer to the same object in memory, not just equal values.

Identify the error: 1stNumber=50

Invalid identifier — it starts with a digit. Identifiers must begin with a letter or underscore.

What is the output of: a=5, b=2, print(a % b)?

1 — the modulus operator returns the remainder of 5 divided by 2.