ЁЯФм
ЁЯзм
ЁЯФн
ЁЯкР
ЁЯзк
тЖР Back to Dashboard
Font Size:

1. Introduction

Python is a high-level, interpreted and general-purpose programming language known for its simple and readable syntax. It is the language used throughout the NCERT Class 11 and 12 Computer Science syllabus, and this chapter is the first of two revision tours that consolidate the fundamentals before the advanced data structures and algorithms are studied. The tour assumes the learner has already encountered these topics in Class 11 and focuses on accurate recall of syntax, semantics and common pitfalls.

A Python program is a sequence of statements executed by the interpreter. Python is case-sensitive, uses indentation to define blocks instead of braces, and dynamically infers the type of a variable from the value assigned to it. Variables do not need type declarations, and a variable can change type during its lifetime. Comments begin with the hash symbol and are ignored by the interpreter.

This chapter revises tokens and keywords, variables and data types, operators and expressions, and the input/output functions. Together these form the alphabet and grammar of every Python program. The second tour continues with strings, lists, tuples, dictionaries, control flow and functions. Mastery of this material is assumed in all later chapters, so careful revision of each topic and its exact syntax is essential.

2. Tokens and Keywords

The smallest units of a Python program are called tokens. The interpreter breaks source code into tokens of five kinds:

marks = 92            # 'marks' identifier, '=' operator, '92' literal
if marks >= 90:       # 'if' keyword
    print("A grade")  # print is a built-in function, not a keyword

2.1 Rules for Identifiers

Identifiers cannot be keywords, cannot start with a digit, cannot contain spaces or special characters other than the underscore, and must be unique within their scope. Python is case-sensitive, so Marks and marks are different identifiers. Although names can be any length, they should be meaningful.

3. Variables and Data Types

A variable is a name that refers to a value stored in memory. Python uses dynamic typing: the type is inferred from the value and can change when a new value is assigned. The built-in function type() reports the type of a value.

x = 10            # int
y = 3.14          # float
name = "Python"   # str
is_valid = True   # bool
data = [1, 2, 3]  # list

3.1 Mutable and Immutable Types

Python types are classified by mutability. Immutable types cannot be changed after creation; any "change" creates a new object. Integers, floats, strings, tuples and booleans are immutable. Mutable types can be modified in place; lists, dictionaries and sets are mutable. This distinction is fundamental and appears repeatedly in examinations and in tricky questions about function arguments.

t = (1, 2, 3)
# t[0] = 9   -> TypeError: tuple does not support item assignment

lst = [1, 2, 3]
lst[0] = 9   # allowed, list is mutable
print(lst)   # [9, 2, 3]

4. Operators and Expressions

An expression combines literals, variables and operators to compute a value. Python groups operators by kind.

4.1 Arithmetic Operators

+ addition, - subtraction, * multiplication, / float division, // floor division, % modulus (remainder) and ** exponentiation. Floor division returns the largest integer not greater than the exact quotient; with positive operands it discards the fractional part.

print(10 / 3)    # 3.333...
print(10 // 3)   # 3
print(10 % 3)    # 1
print(2 ** 5)    # 32

4.2 Relational and Logical Operators

Relational operators compare values and return a Boolean: ==, !=, <, >, <=, >=. Logical operators combine Booleans: and (true only if both true), or (true if at least one true), not (negation).

print(5 > 3 and 5 < 10)   # True
print(5 > 10 or 3 == 3)   # True
print(not True)           # False

4.3 Assignment and Compound Operators

The = assigns a value. Compound operators combine assignment with an operation: +=, -=, *=, /=, //=, %=, **=. The statement x += 5 is equivalent to x = x + 5.

n = 10
n += 5    # n = 15
n *= 2    # n = 30
print(n)

4.4 Operator Precedence

Precedence decides which operation is evaluated first. From highest to lowest the main groups are: parentheses, exponentiation **, unary -/+, * / // %, + -, relational comparisons, not, and, or, then assignment. Parentheses always override precedence, so (a + b) * c is not the same as a + b * c.

5. Input and Output

The input() function reads a line from the keyboard and always returns a string. Numeric input must be converted with int() or float() before arithmetic. The print() function writes values to the screen, separating multiple values by spaces and adding a newline at the end.

name = input("Enter name: ")
marks = int(input("Enter marks: "))
print("Name:", name, "Marks:", marks)

5.1 print() Options

The sep argument changes the separator between values, and end changes the terminating character. The default separator is a space and the default end is a newline.

print("A", "B", "C", sep="-", end="!")
print("D")
# Output: A-B-C!D

5.2 Formatted Output

The format() method and f-strings provide controlled formatting. F-strings embed expressions directly inside string literals prefixed with f, inserting values with { }.

marks = 92.5
print(f"Marks: {marks:.1f}")     # Marks: 92.5
print("Marks: {:.1f}".format(marks))

6. Type Conversion

Type conversion changes a value from one type to another. Implicit conversion happens automatically when Python widens a type, such as int to float in 5 + 2.5. Explicit conversion uses functions like int(), float(), str(), bool(), list() and tuple().

a = 5          # int
b = 2.5        # float
print(a + b)   # 7.5 implicit conversion

s = "123"
n = int(s)     # explicit conversion
print(n + 1)   # 124

A string containing non-numeric characters cannot be converted to a number and raises ValueError.

Quick Revision Tables

Table 1: Python Tokens

Token Type Example
Keyword if, for, while, def, return
Identifier marks, student_name
Literal 25, 3.14, "Python", True
Operator +, //, %, **, ==
Punctuator ( ) [ ] { } , :

Table 2: Mutable vs Immutable Types

Category Types Can change in place?
Immutable int, float, str, tuple, bool No
Mutable list, dict, set Yes

Mind Map

flowchart TD A[Python Revision Tour I] --> B[Tokens] B --> B1[Keywords] B --> B2[Identifiers] B --> B3[Literals] B --> B4[Operators] A --> C[Variables and Types] C --> C1[Dynamic typing] C --> C2[Mutable list dict set] C --> C3[Immutable int str tuple] A --> D[Operators] D --> D1[Arithmetic] D --> D2[Relational and Logical] D --> D3[Assignment] D --> D4[Precedence] A --> E[Input and Output] E --> E1[input returns string] E --> E2[print sep end] A --> F[Type Conversion] F --> F1[Implicit widening] F --> F2[Explicit int float str]

Important Diagrams (SVG)

Diagram 1: Data Types and Mutability

Python Data Types and Mutability BUILT-IN DATA TYPES IMMUTABLE MUTABLE int, float, str, tuple, bool list, dict, set tuple[0] = 9 raises TypeError list[0] = 9 modifies in place Golden Rule: Immutable objects cannot change; mutable objects change in place.

Diagram 2: Operator Precedence Ladder

Operator Precedence (High to Low) ( ) Parentheses * Exponentiation / // % Multiplication group + - Addition group < > <= >= == != Relational not and or Logical = += -= Assignment (lowest) Golden Rule: Use parentheses to override precedence and make expressions clear.

Common Mistakes

  1. Using keywords as variable names: Names like if, for or True raise a SyntaxError because they are reserved.
  2. Starting an identifier with a digit: 2marks is invalid; identifiers must start with a letter or underscore.
  3. Treating / and // the same: 10 / 3 is 3.33 (float) while 10 // 3 is 3 (floor division).
  4. Forgetting that input() returns a string: Comparing or computing directly with input() fails; convert with int() or float().
  5. Mutating a tuple: tuple assignment raises TypeError; students must remember tuples are immutable.
  6. Ignoring operator precedence: a + b * c computes bc first, surprising students who expect (a+b)c.
  7. Mixing indentation styles: Using tabs in one place and spaces elsewhere creates IndentationError or logical errors.
  8. Assuming Python is case-insensitive: Python is case-sensitive; Marks and marks are different variables.

Exam Tips

  1. Practise tracing expressions like 2 + 3 * 4 ** 2 using the precedence ladder to verify outputs.
  2. Memorise the mutability table since questions about tuple and list modification appear frequently.
  3. Remember that input() always returns a string and show the conversion in every input-based program.
  4. Know print() options: sep controls the separator, end controls the terminator; both appear in output questions.
  5. Revise the floor division and modulus rules for negative numbers, a classic tricky question.
  6. Write clean, consistent indentation (4 spaces) in code-writing answers.
  7. Use f-strings for formatted output and know {:.2f} formats a float to two decimal places.

Conclusion

This first revision tour rebuilt the foundations of Python: tokens and keywords, variables with dynamic typing, mutable and immutable data types, the full family of operators with their precedence, and the input and output functions. These pieces form the grammar of every program that follows. The distinction between mutable and immutable types is especially important because it influences how lists, dictionaries and tuples behave, and how function arguments are passed. With these fundamentals refreshed, the next tour continues the revision with compound data types and control structures, completing the toolkit needed for the data structures and algorithms of the remaining chapters.