# 🐍 Chapter 5: Python Fundamentals
> [!TIP]
> This chapter is the **foundation of your entire Class 12 CS journey**. Almost every year, 8–10 marks come directly from Tokens, Identifiers, and Variables. Master this chapter and half your syllabus becomes easy to understand!
---
## 5.1 Introduction
Python is a **high-level, interpreted, general-purpose programming language** created by **Guido van Rossum** and first released in **1991**. It is named after the British comedy series *"Monty Python's Flying Circus"* — not the snake! 🐍
::: grid
::: card
🌟 | Why Python? | Simple readable syntax, free & open source, platform independent, huge standard library, supports multiple paradigms | Feels like writing English
::: card
📌 | Key Facts | Creator: Guido van Rossum, Released: 1991, Type: Interpreted high-level language, Extension: `.py` | `print("Hello")`
:::
> [!NOTE]
> Python is an **interpreted language**, meaning the Python interpreter converts source code into machine code **line by line at runtime**, rather than compiling the whole program at once like C/C++.
---
## 5.2 Python Character Set
A **character set** is the set of valid characters that a language can recognize. A character is the smallest unit of a program.
::: grid
::: card
🔤 | Letters | Uppercase and lowercase alphabets | `A–Z`, `a–z`
::: card
🔢 | Digits | Numeric digits 0 to 9 | `0–9`
::: card
➕ | Special Symbols | Symbols used in code for operations and punctuation | `+ - * / % = ! & < > ( ) [ ] { } , : ;`
::: card
␣ | Whitespaces | Characters that create space in code | Blank space, tab, newline, carriage return
:::
> [!IMPORTANT]
> Python 3 supports the full **Unicode character set**, which means you can even use characters from Indian languages (like Bengali or Hindi) in strings and, in special cases, identifiers!
---
## 5.3 Tokens
The smallest individual unit in a Python program is called a **Token** (or lexical unit). The Python interpreter breaks every line of code into tokens before processing it.
```mermaid
flowchart TD
A[Python Tokens] --> B[Keywords]
A --> C[Identifiers]
A --> D[Literals]
A --> E[Operators]
A --> F[Punctuators]
class A normalNode
class B,C,D,E,F tryNode
```
### 5.3.1 Keywords
Keywords are **reserved words** that have special meaning to the Python interpreter. They **cannot be used** as variable names, function names, or any other identifier.
> [!RULE]
> Python 3 has **35 keywords**. All keywords are in lowercase except `True`, `False`, and `None`.
::: grid
::: card
✅ | Sample Keywords | `False` `None` `True` `and` `as` `break` `class` `continue` `def` `elif` `else` `for` `if` `import` `in` `is` `not` `or` `return` `while` and more | 35 keywords total
::: card
🧠 | Memory Trick | Keywords are VIPs of Python — they already have a fixed job assigned | Can't hire `if`, `for`, `class` for a different role
:::
> [!WARNING]
> `print`, `input`, `len`, `range` are **NOT keywords** — they are built-in **functions**. Students often confuse this in exams! You *can* (though should not) use them as variable names.
### 5.3.2 Identifiers (Names)
An identifier is the **name given to entities** like variables, functions, classes, modules, etc.
::: grid
::: card
✔️ | Allowed | Start with a letter or underscore, followed by letters/digits/underscores, case-sensitive, any length | `age`, `_name`, `student1`
::: card
❌ | Not Allowed | Cannot start with a digit, cannot contain special symbols or spaces, cannot be a keyword | `1name`, `na@me`, `my name`, `class`
:::
> [!TIP]
> **Board Exam Favourite:** Examiners love giving a list of 4–5 names and asking "Which are valid identifiers?" Always check: starts with digit? has space? has special symbol? is it a keyword?
### 5.3.3 Literals / Values
A literal is a **raw data value** directly written in the source code.
::: grid
::: card
🔢 | Numeric Literals | Integer, float, and complex number values | `10`, `3.14`, `3+5j`
::: card
🔤 | String Literals | Text written inside quotes | `'Hello'`, `"Hi"`, `'''multi-line'''`
::: card
✅ | Boolean Literals | Only two values, capital first letter | `True`, `False`
::: card
🌀 | Special Literal | Represents absence of a value | `None`
:::
**Numeric literals can further be written in different number systems:**
| System | Prefix | Example |
|---|---|---|
| Binary | `0b` or `0B` | `0b1010` |
| Octal | `0o` or `0O` | `0o17` |
| Decimal | none | `25` |
| Hexadecimal | `0x` or `0X` | `0x1A` |
> [!NOTE]
> A single character in Python (e.g. `'A'`) is *not* a separate data type — it is simply treated as a **string of length 1**.
### 5.3.4 Operators
Operators are special symbols that carry out **arithmetic or logical computation**. The value(s) the operator acts on are called **operands**.
::: grid
::: card
➗ | Arithmetic | Perform mathematical calculations | `+` `-` `*` `/` `//` `%` `**`
::: card
⚖️ | Relational | Compare two values | `==` `!=` `>` `<` `>=` `<=`
::: card
🔗 | Logical | Combine conditional statements | `and` `or` `not`
::: card
📝 | Assignment | Assign or update values | `=` `+=` `-=` `*=` `/=`
::: card
🎯 | Membership | Test membership in a sequence | `in` `not in`
::: card
🪞 | Identity | Compare memory identity | `is` `is not`
:::
> [!IMPORTANT]
> Difference between `/` and `//`:
> - `/` → **True division** → always gives a float → `7 / 2` → `3.5`
> - `//` → **Floor division** → gives the floor (integer part) → `7 // 2` → `3`
### 5.3.5 Punctuators
Punctuators are symbols used to organize sentence structure, indicate operations, and structure the program. Examples:
`'` `"` `#` `\` `( )` `[ ]` `{ }` `@` `,` `:` `.` `=` `;` `+=` `-=` `*=` `/=`
> [!NOTE]
> Punctuators are **not the same as operators** — a punctuator's main role is structural (grouping, separating, terminating), even though some symbols overlap (like `=`).
---
## 5.4 Barebones of a Python Program
A minimal Python program has a very simple, indentation-based structure — **no semicolons, no curly braces required**.
```python
# This is my first Python program
print("Hello, World!")
```
::: grid
::: card
📐 | Indentation | Whitespace defines blocks of code instead of `{ }`, must be consistent | Mandatory, not optional
::: card
💬 | Comments | Notes ignored by the interpreter | Single-line `#`, multi-line `''' ... '''`
::: card
🧩 | Statements | A logical line of code | Usually one statement per line
::: card
🔠 | Case Sensitivity | Python treats uppercase and lowercase differently | `Print` ≠ `print`
:::
> [!WARNING]
> **Common Exam Mistake:** Inconsistent indentation (mixing tabs and spaces) causes an `IndentationError`. Always use **4 spaces** per indentation level consistently.
```mermaid
flowchart TD
A[Start Program] --> B[Comment / Docstring]
B --> C[Import Statements]
C --> D[Statements with proper Indentation]
D --> E[End Program]
class A normalNode
class B,C,D tryNode
class E normalNode
```
---
## 5.5 Variables and Assignments
A **variable** is a named location in memory used to store a value that can change during program execution.
### 5.5.1 Creating a Variable
In Python, you don't need to *declare* a variable's type separately — a variable is created the **moment you assign a value to it**.
```python
age = 17 # integer variable
name = "Riya" # string variable
height = 5.4 # float variable
```
> [!TIP]
> Unlike C/C++, Python has **no separate declaration statement**. Assignment *is* declaration!
### 5.5.2 Multiple Assignments
Python allows assigning values to multiple variables in different flexible ways:
| Style | Syntax | Example |
|---|---|---|
| Same value to many variables | `a = b = c = value` | `a = b = c = 10` |
| Different values in one line | `a, b, c = v1, v2, v3` | `a, b, c = 10, 20, 30` |
| Swapping without a third variable | `a, b = b, a` | `a, b = b, a` |
> [!IMPORTANT]
> **Board Exam Gold:** Swapping two variables *without* a third variable using `a, b = b, a` is a very frequently asked one-mark / output-based question.
### 5.5.3 Variable Definition
A variable in Python is essentially a **reference (name) bound to an object** stored somewhere in memory. Python variables have:
| Property | Meaning |
|---|---|
| **Name** | The identifier used to refer to the variable |
| **Value** | The data currently stored |
| **Type** | Determined automatically from the value assigned |
| **id()** | Unique memory address identifier of the object |
```python
x = 10
print(id(x)) # shows the memory address of the object 10
print(type(x)) # shows <class 'int'>
```
### 5.5.4 Dynamic Typing
Python is a **dynamically typed language** — the type of a variable is decided **at runtime**, based on the value assigned, and can change if reassigned.
```python
x = 10 # x is int
x = "Hello" # now x becomes str — perfectly valid!
x = 3.14 # now x becomes float
```
> [!NOTE]
> This is different from **statically typed** languages like C/C++/Java, where the data type of a variable is fixed at the time of declaration and cannot change.
::: grid
::: card
🧠 | Memory Trick | Static is like a steel pipe with a fixed shape forever | Dynamic is like water taking the shape of its container
::: card
⚠️ | Common Confusion | Dynamic typing does not mean "no data types" | Python is strongly typed too — `"5" + 5` still fails
:::
---
## 5.6 Simple Input and Output
### 5.6.1 Reading Numbers
The built-in `input()` function **always returns a string**, even if the user types a number. To use it as a number, you must **explicitly type-cast** it.
```python
age = input("Enter your age: ") # age is a string, e.g. "17"
age = int(input("Enter your age: ")) # age is now an integer 17
height = float(input("Enter height: ")) # for decimal numbers
```
> [!WARNING]
> **Most common runtime error for beginners:** Forgetting to type-cast `input()` before doing arithmetic → `TypeError: unsupported operand type(s)`. Always wrap with `int()` or `float()` when expecting numbers!
::: grid
::: card
📥 | input() Key Facts | Always returns type `str`, takes an optional prompt message, pauses execution until Enter is pressed | `input("Enter name: ")`
::: card
🔁 | Type Casting Functions | Convert string input into the required type | `int()`, `float()`, `str()`
:::
### 5.6.2 Output Through print() Function
The `print()` function displays output on the screen. It has several useful optional parameters:
```python
print("Hello", "World", sep="-", end="!\n")
# Output: Hello-World!
```
| Parameter | Purpose | Default |
|---|---|---|
| `sep` | Separator between multiple values | `' '` (space) |
| `end` | What to print at the end | `'\n'` (newline) |
| `*objects` | One or more values to print | — |
Modern **f-strings** are the CBSE-recommended way to combine text and variables:
```python
name = "Amit"
marks = 95
print(f"{name} scored {marks} marks")
```
::: grid
::: card
🧠 | Memory Trick | sep stands for spaces between words | end stands for ending punctuation of the print statement
:::
> [!TIP]
> Practice predicting output for `print()` statements with custom `sep` and `end` — these appear almost every year as 1–2 mark output-based questions.
---
## 📝 Board Exam Practice Zone
**1 Mark Questions**
1. Name the creator of Python.
2. What will `type(True)` return?
3. Is `input()` output a `str`, `int`, or `float` by default?
4. What is the default value of `sep` in `print()`?
5. Which of these is a valid identifier: `2fruit`, `_fruit`, `for`, `fruit#1`?
**2 Mark Questions**
1. Differentiate between Keywords and Identifiers with one example each.
2. Differentiate between `/` and `//` operators with example.
3. What is dynamic typing? Explain with an example.
4. Write the rules for naming a valid Python identifier.
**3 Mark Questions**
1. Write a program to swap two numbers without using a third variable.
2. Explain any three types of literals in Python with examples.
3. Predict the output:
```python
a, b, c = 5, 10, 15
print(a, b, c, sep="*", end="#")
```
**4 Mark / Output-Based Questions**
1. Identify errors, if any, in the following code and rewrite it correctly:
```python
1name = input(Enter name)
Age = int(input("Enter age"))
print(Name, "is", age, "years old")
```
2. Write a program that takes two numbers as input and prints their sum, difference, product, and floor division result, each on a separate line.
> [!RULE]
> **Golden Rule for This Chapter:** Whenever a question mixes *keywords vs identifiers* or *type-casting of input()*, examiners are testing whether you actually understand the **rules**, not just memorized examples. Always apply the rule step-by-step rather than guessing.
---
## 🎯 Quick Revision Summary
::: grid
::: card
✅ | Must Remember | Python has 35 keywords, `input()` always returns a string, identifiers cannot start with a digit or be a keyword, Python is dynamically typed | Indentation replaces `{ }`
::: card
⚠️ | Common Pitfalls | Confusing `print`/`input` with keywords, forgetting to type-cast numeric input, mixing tabs and spaces | A single character is just a string of length 1
:::
Back to List
Calculating...