5. Python Fundamentals
Higher Secondary · Computer Science · Science Stream

Python Fundamentals

The building blocks of every Python program — the character set and tokens it's built from, the variables and data types that hold values, the operators that act on them, and the statements that bring input, output, and expressions together.

5.4 · Live Tool

Try the IDLE Shell — Types & Expressions

Type an expression, a print(...) call, or a type(...) call at the prompt below and press Enter. Try type(5), type(3.5), type("hello"), or an arithmetic expression like num1 ** num2.

IDLE Shell 3.10.12

● live
Python 3.10.12 (main, Feb 4 2025, 14:57:36) [GCC 11.4.0] on linux
Type "help", "copyright", "credits" or "license()" for more information.
>>>
Supports print(...), type(...), string concatenation with +, and direct arithmetic — just like typing at the real >>> prompt.
5.1

Character Set

A character set is the collection of valid characters a programming language can recognise and use for writing programs. Every instruction or statement in Python must be composed of these characters.

Letters

All uppercase (A–Z) and lowercase (a–z) letters of the English language.

Digits

All numeric digits, 0 through 9.

Special Symbols

A wide range of symbols such as " ' ; : ! ~ @ # $ % ^ & * ( ) _ + - = { } [ ] \

Whitespace Characters

Blank spaces, tabs, newline and carriage return.

Other Characters

All other ASCII and Unicode characters supported by Python.

5.2

Tokens

A Python instruction consists of tokens, where each token is a collection of one or more characters — the smallest individual unit in a Python program. Python has five types of tokens: Keywords, Identifiers, Literals, Operators and Punctuators.

5.2.1 Keywords

A keyword is a special reserved word with predefined meaning, recognised by the interpreter and used only for its defined purpose. Python is case-sensitive, so keywords must be written exactly as specified — True is a valid keyword, but true is not.

KeywordKeywordKeywordKeywordKeywordKeyword
asdeffinallyinorwhile
anddelforispasswith
asserteliffromlambdaraiseyield
breakelseglobalnonlocalreturn
classexceptifNoneTrue
continueFalseimportnottry
Soft Keywords (Python 3.10+)
match, case, and _ (underscore) act as keywords only in specific contexts — for example, inside a match statement. Being "soft", they remain valid as ordinary identifier names elsewhere. match and case are discussed further in Chapter 6.

5.2.2 Identifiers

Identifiers are user-defined words used to name program elements — variables, functions, objects, classes. An identifier is an arbitrary long sequence of letters, digits and underscores ( _ ) that must satisfy the following conditions.

First Character Rule

The first character must be a letter or an underscore.

No Whitespace/Symbols

Whitespace and special characters are not allowed anywhere in an identifier.

No Keywords

Keywords cannot be used as identifiers. There's no length limit, but short and meaningful names are best.

Valid examples: count, avg_marks, FOR, _1stRank.

5.2.3 Literals

A token that indicates a constant value is called a literal — literals are often called constants. Python supports string, numeric, and Boolean literals, plus the special literal None. Each literal an interpreter processes gets its own memory space, called an object.

1. String Literals

A sequence of characters within single/double/triple quotes — e.g. "Computer Science", 'Python', '''#number2'''. Triple quotes can also hold multiline strings.

2. Numeric Literals

Integer — binary (0b1111), decimal (15), octal (0o17), hex (0xF). Float — real numbers with a fractional part, e.g. -3.14, 0.5. Complex — form a+bj, e.g. 5+3j, 2-5j.

3. Boolean Literals

Two Boolean literals — True and False — represent logical conditions and comparison/logical results.

4. Special Literal — None

None denotes nothing, no value, or the absence of a value.

"""Python makes coding simple! Keep learning, keep growing.""" ← a multiline string using triple quotes

Escape Sequences

Escape SequenceCharacter
'\t' or "\t"Tab
'\n' or "\n"New line
'\'' or "\'"Single quote
'\"' or "\""Double quote
'\\' or "\\"Backslash

Literal Collections

Built-in ways to group multiple literals into a single unit — list, tuple, dictionary, or set.

List

Comma-separated elements within square brackets. Values can be of any type and can be changed. my_list = [25, "Python", 95.5, 'A+']

Tuple

Comma-separated values within round brackets. Any type allowed, but values cannot be changed. my_tup = (23, "Computer Science", 'A', 35.8)

Dictionary

An unordered set of key-value pairs within curly braces. my_dict = {1: 'one', 2: 'two', 3: 'three'}

Set

An unordered collection in curly braces — no duplicates allowed, unlike list and tuple. my_set = {'sat', 'sun', 20, 3.14}

Ordered collections (list, tuple) preserve the sequence elements were added in, and each item has a fixed index. Unordered collections (dictionary, set) don't guarantee a fixed position, so items aren't accessed by index number.

5.2.4 Operators & 5.2.5 Punctuators

Operators

A token or symbol that tells the interpreter about a specific operation, applied on operands. Examples: + * // > !=. Detailed in section 5.5.

Punctuators

Special symbols that help organise the structure of a program — much as punctuation marks structure a sentence. Examples: [ , @ { )

5.3 – 5.4

Variables & Data Types

Every value in a Python program must be stored somewhere in memory. Python creates this memory as needed and lets us refer to it using identifiers called variables.

What Is a Variable?

The statement x = 3 associates the variable x with an object holding the integer literal 3. A variable carries three aspects of that object: its identity (memory address), data type, and value.

No Explicit Declaration

Unlike some languages, Python variables need no type declaration. Assigning a value creates an object with that value, and the variable's data type matches the object it refers to.

Python Data Type Classes

Numeric

int, float, complex

Sequence

str, list, tuple

Dictionary

dict

Boolean

bool

Set

set, frozenset

Python treats both simple data types and their aggregates as classes — the terminology used in Object Oriented Programming, covered in Class XII.

>>> a = 5 >>> print(type(a)) <class 'int'> >>> b = 5.0 >>> print(type(b)) <class 'float'> >>> s = "hello" >>> print(type(s)) <class 'str'> >>> L = [1,2,3] >>> print(type(L)) <class 'list'>

The variable's data type changes whenever it is reassigned a value of a different type — e.g. after num = 10 (int), the statement num = 3.5 makes num a float.

5.4.1 Mutable and Immutable Data Types

Mutable types allow their value to be modified after creation; immutable types do not — updating them creates a brand-new object instead.

Mutable Types

Lists, dictionaries, and sets. Updating them changes the value inside the same memory object — the variable keeps referring to it.

Immutable Types

int, float, str, tuple. Updating them makes Python create a new memory object; the variable is redirected to it, and the old object survives only if some other variable still refers to it.

>>> num = 10 # num refers to an int object containing 10 >>> temp = num # temp refers to the SAME object >>> num = num * num # a NEW object (100) is created; num now refers to it # temp still refers to the original object (10)
5.5

Operators

Operators are special symbols or keywords used to perform operations on operands. Python offers arithmetic, relational, logical, assignment, identity and membership operators. Those needing one operand are unary; those needing two are binary.

5.5.1 Arithmetic Operators

Assume num1 = 5 and num2 = 2.

OperatorOperationDescriptionExample
+Addition & ConcatenationAdds two numeric values; joins two stringsnum1+num2 → 7
"Hello"+"Guys" → HelloGuys
-SubtractionSubtracts right operand from leftnum1-num2 → 3
*Multiplication & RepetitionMultiplies values; repeats a string if the second operand is an intnum1*num2 → 10
"Hello"*2 → HelloHello
/DivisionDivides left by right; always returns a floatnum1/num2 → 2.5
%ModulusReturns the remainder of divisionnum1%num2 → 1
//Floor DivisionDivides and rounds down to the nearest integernum1//num2 → 2
5.0//2.0 → 2.0
**ExponentRaises the left operand to the power of the rightnum1**num2 → 25

The + and - symbols can also act as unary plus/minus. Used with strings, + concatenates; used with a string and an integer, * repeats.

How Operand Type Affects the Result (using +)

Operand 1Operand 2Result TypeExample
intintint7 + 5 → 12
intfloatfloat7 + 2.5 → 9.5
floatintfloat7.5 + 5 → 12.5
floatfloatfloat7.5 + 2.5 → 10.0

5.5.2 Relational Operators

Binary operators that compare two operands and return a Boolean. Assume num1=5, num2=2, num3=5, str1="Good", str2="Bad".

OperatorMeaningExample
==Equal tonum1==num2 → False
str1=="Good" → True
!=Not equal tostr1!=str2 → True
>Greater thannum1>num3 → False
str1>str2 → True
>=Greater than or equal tonum1>=num3 → True
<Less thannum1<num2 → False
<=Less than or equal tonum1<=num3 → True

Strings compare by Unicode/alphabetical precedence — "Good" < "good" is True, since uppercase letters have smaller Unicode values. Comparing a number with a string using operators other than ==/!= raises a Type Error — e.g. 3<"3" — although 3.0<4 works since 4 is implicitly converted to float.

5.5.3 Logical Operators

and

True only if both operands are True.

or

True if either operand is True.

not

Unary — reverses the logical state of its operand.

OperationFirst OperandSecond OperandResult
andTrueXX
andFalseXFalse
orTrueXTrue
orFalseXX

Values like None, False, 0, "", (), [], {} are treated as False; everything else counts as True. So 3 and 0 evaluates to 0, and "Hello" or "" evaluates to "Hello".

>>> num1, num2, num3 = 15, 12, 5 >>> (num1>num2) and (num1>num3) → True >>> (num1<num2) and (num1<0) → False >>> (num1<num2) or (num1>0) → True >>> not (num1>num2) → False

5.5.4 Assignment Operators

The = operator associates a variable with the object holding the value of the right-hand expression. Python also provides compound assignment operators that combine assignment with an arithmetic operation.

Compound OperatorEquivalent To
a += ba = a + b
a -= ba = a - b
a *= ba = a * b
a /= ba = a / b
a %= ba = a % b
a //= ba = a // b
a **= ba = a ** b

5.5.5 Identity Operators

Check whether two variables refer to the same object in memory — useful along with the built-in id() function.

OperatorDescriptionExample
isTrue if both operands refer to the same memory objectnum2=num1; num1 is num2 → True
is notTrue if they do NOT refer to the same objectnum1 is not num2 → False

5.5.6 Membership Operators

Check whether a value belongs to a sequence (string, list, or tuple).

OperatorDescriptionExample
inTrue if the value is found in the sequencea=[10,15,100]; 10 in a → True
not inTrue if the value is NOT found in the sequence'15' not in a → True
5.6 · Live Tool

Expressions & Operator Precedence

An expression combines operands and operators and is evaluated to produce a result — the expression's return value. When several operator types appear together, Python resolves the order using operator precedence.

OrderOperatorsDescription
1**Exponentiation
2+ -Unary plus, unary minus
3* / % //Multiplication, division, modulus, floor division
4+ -Addition, subtraction
5< <= > >= == !=Relational / comparison operators
6= %= /= //= -= += *= **=Assignment & compound assignment
7is is notIdentity operators
8in not inMembership operators
9notLogical NOT
10andLogical AND
11orLogical OR

Parentheses override the usual order — operations inside them are evaluated first. Operators of equal precedence are evaluated left to right.

Step Through an Evaluation

● live
—

—

Compares 5 + 7 - 2 * 4 (precedence rules only) against 5 + (7 - 2) * 4 (parentheses first).
5.7 – 5.8

Statements & Python Programs

A statement is an instruction to perform a task — assignment, input, output, or control flow. Python executes statements one by one in order, called sequential flow.

5.7.1 Assignment Statement

Multiple Assignment

a = b = c = 10 — all three variables refer to the same object holding 10.

Multiple Values, Multiple Variables

a, b, c = 10, 15, 20 — assigns values in order; expressions can be used instead of literals too.

5.7.2 Input Statement

The input([prompt]) function displays an optional prompt, waits for the user to type a value and press Enter, then returns it — always as a string, even if the input looks numeric.

>>> name = input("Enter your name: ") Enter your name: Pavithra

To use numeric input in calculations, convert it with int() or float() — e.g. num1 = int(input("Enter first number: ")).

5.7.3 Output Statement

The print(value [, …, sep=char1, end=char2]) function displays text, numbers, or calculation results. sep sets the separator between values (default: a space); end sets what follows the last value (default: a new line).

>>> print("Hello") Hello >>> print(2.5 * 10) 25.0 >>> print("Hello" + "friends") Hellofriends >>> print("Hello", "friends") Hello friends >>> print(10, 20, 30, sep=' ', end='.') 10 20 30.

5.8.1 Program — Greet the User

Algorithm

Step 1: Start Step 2: Input Name Step 3: Print "Hello", Name, "Welcome" Step 4: Stop

Program & Output

name = input("Enter your name: ") print("Hello", name, "Welcome!") Enter your name: Niketh Hello Niketh Welcome!

5.8.2 Program — Sum of Two Numbers

#accept two numbers num1 = input("Enter first number: ") num2 = input("Enter second number: ") #calculate the sum s = int(num1) + int(num2) #print the result print("Sum = ", s) Enter first number: 12 Enter second number: 43 Sum = 55

Since input() always returns a string, int() converts each entered value to an integer before addition — otherwise Python would concatenate "12" and "43" as text instead of adding them.

5.8.3 Comments in Programs

Single-line Comments

Begin with the # symbol. The interpreter ignores everything from # to the end of that line.

Multi-line Comments

Enclosed in a pair of triple quotes (""" or '''). Comments document code for anyone reading it later — part of the documentation phase of programming.

Let Us Do

Quick Recap

Tap a question to reveal the answer.

Which of these are invalid identifiers — Data_rec, Num#, 2ab, try, My File, _num1, Sum2Num, false, True, File.py?

Num# (special symbol #), 2ab (starts with a digit), try (a keyword), My File (contains a space), and File.py (contains a period) are all invalid. Data_rec, _num1, Sum2Num, false (lowercase, not the keyword), and True (a keyword itself, so actually invalid as an identifier) — note only Data_rec, _num1, Sum2Num and false are valid identifiers.

Classify these literals: 12, 'Num#', '''2ab''', 25.6, -5, "123", {1, 'Ardra', 95}, (2, "Niketh", 'Science'), ["Nived", 20, 'A'].

12 and -5 — Integer. 25.6 — Float. 'Num#', '''2ab''', and "123" — String. {1, 'Ardra', 95} — Set. (2, "Niketh", 'Science') — Tuple. ["Nived", 20, 'A'] — List.

What is the data type of each: n=25, PI=3.14, name="Guido", flag=True?

n is int, PI is float, name is str, and flag is bool.

If a=5, b=10, c=2.5, d="hello", what does a/b return, and what type?

a/b evaluates to 0.5, of type float — the standard division operator / always returns a float, regardless of operand types.

If ans=25 initially, what is ans after ans //= 10?

ans //= 10 means ans = ans // 10, so ans becomes 25 // 10 = 2.

Why does 5 + 7 - 2 * 4 evaluate to 4, while 5 + (7 - 2) * 4 evaluates to 25?

Without parentheses, * (precedence 3) runs before +/- (precedence 4): 2*4=8, then 5+7-8=4. With parentheses, (7-2) is forced to evaluate first regardless of normal precedence: 7-2=5, then 5*4=20, then 5+20=25.

Why must int() be used when adding two numbers entered with input()?

Because input() always returns a string, even for numeric-looking entries. Without converting with int() (or float()), the + operator would concatenate the strings instead of adding numbers.

What's the difference between a mutable and an immutable data type, with an example of each?

A mutable type's value can be changed after creation without creating a new object — e.g. a list. An immutable type cannot be changed in place; any update creates a brand-new object — e.g. an int, float, str, or tuple.