Free Study Material

Python Fundamentals

Introduction

This unit moves from computer fundamentals into actually programming a computer. Python is the language CBSE IP uses for that — this topic starts with what kind of language it is, and the two ways you can run it.

Concept

Python is a high-level, interpreted language: you write instructions close to plain English, and Python's interpreter reads and runs them line by line, rather than translating the whole program to machine code first.

Two execution modes:

  • Interactive Mode — type one statement at Python's >>> prompt, and it runs immediately, showing the result right away.
  • Script Mode — write a complete program in a .py file and run the whole file at once, top to bottom.

Worked Example

5 + 3
print(5 + 3)

In Interactive Mode, typing 5 + 3 alone at the prompt shows 8 immediately, with no print() needed. In Script Mode — how every program in this course runs, including this platform's Run button — the bare expression 5 + 3 computes a value but shows nothing at all; only print(5 + 3) actually displays 8.

Note: This platform's Run button executes Script Mode. Always use print() to see a value — writing an expression alone, the way Interactive Mode allows, produces no visible output here.

Explanation

Interactive Mode is for quick, one-off checks; Script Mode is how every real, saved program is written and run — which is exactly why print() becomes essential from this point on: it is the only way Script Mode shows you anything at all.

Summary

Python is a high-level, interpreted language, run in Interactive Mode (one line at a time, results shown automatically) or Script Mode (a full .py file, where only explicit print() output is visible) — this course, and this platform, both use Script Mode.

The Power of Python

Python is a high-level, interpreted, and general-purpose language. It is famous for its readability—meaning the code looks very similar to English. This makes it the perfect "first language" for students and a powerful tool for Data Scientists and AI researchers worldwide.

Interactive Mode (REPL)

Python executes code line-by-line instantly.

Pros: Fast for testing commands.
Cons: Code is NOT saved.

>>> print("Hi")
Hi
Script Mode (.py)

Write the entire program in a file and then run it.

Pros: Can save and edit later.
Cons: Requires an extra step to run.

# saved as hello.py
name = "Aman"
print(name)

The Character Set

  • Letters: A-Z and a-z
  • Digits: 0-9
  • Special Symbols: _ + - * / ( ) [ ] { } % # @ etc.
  • Whitespaces: Blank space, Tab, Newline (Crucial in Python!)

Introduction

Now that you know how Python code runs, this topic covers how it's structured on the page — the rules that decide which lines belong together.

Concept

A Python program is a sequence of statements, executed top to bottom. Python groups related statements into a block using indentation — consistent leading whitespace — instead of curly braces {} like many other languages use.

Worked Example

marks = 88
if marks >= 40:
    print("Result: PASS")
    print("Well done.")
print("Processing complete.")

The two print() lines directly under if marks >= 40: are indented identically, so Python treats them as one block belonging to that if. The final print() is back at the original indentation level, so it isn't part of the if block — it runs regardless of whether marks >= 40 is True or False.

Warning: Mixing tabs and spaces, or indenting two lines of the same block by different amounts, raises an IndentationError. Python treats consistent indentation as part of the code's actual meaning, not just a style choice.

Explanation

This is the clearest structural difference from a language that uses { }: in Python, indentation is the block structure. There's no closing symbol marking where a block ends — it simply ends the moment a line returns to a shallower indentation level.

Summary

A Python program is a sequence of statements, grouped into blocks by consistent indentation rather than braces — every statement in the same block must be indented by exactly the same amount, or Python raises an IndentationError.

📐 The Rules of Structure

Unlike other languages that use curly brackets {}, Python uses Indentation (leading spaces) to define blocks of code. This makes Python code very readable but strict.

1. Indentation

A block of code (like the body of a loop or an 'if' statement) must be indented by the same number of spaces (usually 4 spaces or 1 tab).

2. Comments (The # Symbol)

Comments are notes for humans. Python completely ignores them. They are used to explain what the code is doing.

  • Single-line: Starts with a #.
  • Docstrings: Used for multi-line explanations, enclosed in triple quotes """ ... """.

Introduction

Every program needs somewhere to hold the values it works with. This topic covers what a variable actually is in Python, and a property of every value that CBSE tests directly: whether it can change after creation.

Concept

A variable is a name that refers to a value stored in memory. Python variables need no separate type declaration — a variable's type is decided automatically from the value assigned to it, and can change if a new value of a different type is assigned later.

Every value is also either:

  • Mutable — can be changed in place after creation, without creating a new object.
  • Immutable — cannot be changed in place at all; any "change" actually creates a brand-new value.

Worked Example

marks = 91
print(marks)

marks = "ninety-one"
print(marks)

marks starts out holding the integer 91, prints 91, then is reassigned a string, "ninety-one" — Python allows this without any error, because a variable's type is never fixed; it simply follows whatever value is currently assigned.

Note: An identifier (a variable's name) must start with a letter or underscore, contain only letters/digits/underscores after that, and never be a Python keyword. Python is also case-sensitive — marks and Marks are two different names.

Explanation

Mutability matters beyond terminology: a mutable value can be modified by more than one variable name pointing at it — a real source of confusing bugs once collections like lists are introduced. An immutable value never has that risk, because no operation can ever change it after creation; only replace what a variable points to.

Summary

A variable is a name referring to a stored value, with no separate type declaration needed — its type simply follows whatever value is currently assigned. Every value is also either mutable (can change in place) or immutable (any "change" creates a new value) — which category a specific data type falls into is covered next.

🔑 Python Keywords

Think of Keywords as the "Reserved Words" of the Python language. Python has already claimed these words for its own internal logic. Because they have a specific meaning to the Python interpreter, you cannot use them as names for your variables or functions.

Important Rules for Keywords:

  • Case Sensitivity: Keywords are case-sensitive. Most are lowercase (if, while, def), but three start with a capital letter: True, False, and None.
  • No Substitutes: You cannot use a keyword like class as a variable name because it would confuse the computer.
Category Examples
Logical and, or, not, True, False
Control Flow if, elif, else, for, while, break
Structural def, class, import, return, as

🏷️ Identifiers

An Identifier is simply a name given to an entity in a program, such as a variable, function, or list. While you are free to choose these names, Python enforces strict rules to prevent errors.

The Legal Rules for Naming (Must Follow):

  1. Allowed Characters: Names can contain letters (A-Z, a-z), digits (0-9), and the underscore (_).
  2. The First Character: An identifier cannot start with a digit. user1 is valid, but 1user is an error.
  3. No Special Symbols: You cannot use symbols like @, $, %, or spaces.
  4. No Keywords: As mentioned, you cannot name a variable while or if.
Example Check:
✅ Valid: my_variable, _count, StudentName, total2
❌ Invalid: 2total (Starts with digit), my-var (Hyphen not allowed), class (Keyword)

Constants

A Constant is a type of variable whose value is intended to remain unchanged throughout the program execution.

Technically, Python does not have a "Strict Constant" type, but programmers use a Naming Convention to show a value is constant: Write it in ALL CAPITAL LETTERS.

PI = 3.14
GRAVITY = 9.8
SCHOOL_NAME = "KV CODERS"

Introduction

You now know a variable's type follows its value, and that every value is mutable or immutable. This topic names Python's actual built-in data types, and sorts each into one of those two categories.

Concept

  • int — a whole number (25). Immutable.
  • float — a number with a decimal point (3.14). Immutable.
  • str — text inside quotes ("hello"). Immutable.
  • bool — exactly True or False. Immutable.
  • list — an ordered collection, [1, 2, 3]. Mutable.
  • tuple — an ordered collection, (1, 2, 3). Immutable.
  • dict — key-value pairs, {"name": "Aisha"}. Mutable.

type() reports a value's data type.

Worked Example

name = "Aisha"
marks = [78, 85, 92]

print(type(name))
print(type(marks))
print(type(25))
print(type(3.14))

Running this prints <class 'str'>, <class 'list'>, <class 'int'>, and <class 'float'>, in that order — one line per print() call, each reporting the type of the value passed to type().

Note: list and dict are the two mutable types in this list — everything else (int, float, str, bool, tuple) is immutable. This exact grouping is a common one-mark CBSE question.

Explanation

Knowing which types are mutable matters immediately once you start modifying a collection: a list's elements can be changed, added, or removed after creation with no new object involved, while a tuple — even though it looks similar — can never be changed once made; only entirely replaced with a new tuple.

Summary

Python's core built-in types are int, float, str, bool (all immutable), tuple (also immutable), and list, dict (both mutable) — type() reports which one a given value actually is.

📦 What is a Variable?

In Python, a Variable is a reserved memory location to store values. Think of it as a labeled box. When you create a variable, you are telling the computer to set aside some space in its RAM to hold a specific piece of information.

Dynamic Typing in Python

Unlike languages like C++ or Java, Python is Dynamically Typed. This means you don't need to declare the type of data a variable will hold (like "this is an integer"). Python automatically detects the type based on the value you assign to it.

x = 10       # x is automatically an Integer
x = "Hello"  # Now x is a String (No error in Python!)

The Standard Data Types

Python has several built-in data types to handle different kinds of information:

Type Description & Example
Numeric Integers (5), Floats (5.5), and Complex numbers.
Sequence Strings ("Hi"), Lists ([1,2]), and Tuples.
Mapping Dictionaries ({"key": "value"}).
Boolean Represents logical values: True or False.

🔄 Mutable vs. Immutable

This is a favorite exam topic. It refers to whether or not you can change a value after it has been created in memory.

Immutable (Unchangeable)

Once created, the value at that memory address cannot be altered. If you "change" it, Python creates a new object in memory.

Examples: Integers, Floats, Strings, Tuples.
Mutable (Changeable)

You can modify, add, or delete elements from these objects without changing their identity in memory.

Examples: Lists, Dictionaries, Sets.

Introduction

This topic covers the operators Python provides, and what happens when several of them appear together in the same expression.

Concept

  • Arithmetic: + - / // % * (addition, subtraction, multiplication, division, floor division, modulus, exponent). / always returns a float; // returns the whole-number quotient; % returns the remainder.
  • Relational: == != > < >= <= — always produce a bool result.
  • Logical: and (both must be True), or (at least one True), not (inverts).

When several operators appear in one expression, Python follows a fixed precedence order: parentheses first, then *, then / // %, then + -, then relational operators, then not, and, or.

Worked Example

a = 17
b = 5

print(a // b)
print(a % b)
result = 2 + 3 * 4
print(result)
print(a > b and b > 0)

a // b gives 3 (how many whole times 5 fits into 17); a % b gives 2 (what's left over). 2 + 3 4 evaluates 3 4 first (multiplication outranks addition), giving 12, then 2 + 12 = 14. a > b and b > 0 evaluates both comparisons first (True and True), then combines them with and, giving True.

Note: == (equality, produces a bool) and = (assignment, produces nothing) are easy to confuse — mixing them up is one of the most common beginner errors.

Explanation

When an expression's order of evaluation isn't immediately obvious, add parentheses — even ones not strictly required. (2 + 3) * 4 is exactly as correct as a precedence-table lookup, and far easier to read at a glance.

Summary

Python's arithmetic, relational, and logical operators combine in a fixed precedence order — parentheses, then *, then / // %, then + -, then comparisons, then not/and/or — with explicit parentheses always the safest way to make an intended order clear.

➕ What are Operators?

Operators are special symbols that perform specific operations on operands (variables or values). For example, in x + 5, the + is the operator and x and 5 are operands.

Common Operator Categories:

Category Symbols & Purpose
Arithmetic +, -, *, /, % (Remainder), ** (Exponent), // (Floor Division)
Relational ==, !=, >, <, >=, <= (Used for comparisons)
Logical and, or, not (Used to combine multiple conditions)
Assignment =, +=, -=, *= (Used to assign values to variables)

📏 Operator Precedence (The Order of Operations)

When an expression contains multiple operators, Python follows a specific order called Precedence (similar to BODMAS in math). Operators with higher precedence are evaluated first.

Hierarchy (High to Low):
  1. Parentheses ()
  2. Exponentiation **
  3. Multiplication, Division, Modulo, Floor Division *, /, %, //
  4. Addition and Subtraction +, -
  5. Relational Operators ==, !=, etc.
  6. Logical not, then and, then or

Introduction

This closing topic of the chapter covers taking data in from a user and converting it to the right type — the routine first step of almost every real program.

Concept

  • input("prompt") — displays the prompt, waits for the user to type something, and returns it — always as a string, even if they type digits.
  • print() — displays values; accepts sep (separator between items, default a space) and end (what to print after the last item, default a newline).
  • Type Casting — converting a value from one type to another: int(value), float(value), str(value).

Worked Example

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

age = int(age_text)
print(age + 1)

print("A", "B", "C", sep="-")

age_text holds whatever the user typed, as a str — even "15" — so type(age_text) prints <class 'str'>. int(age_text) casts it to a real integer, so age + 1 works as arithmetic. print("A", "B", "C", sep="-") prints A-B-C, using - instead of the default space between items.

Warning: age_text + 1 (skipping the cast) raises TypeError: can only concatenate str (not "int") to str — input()'s result is always text, and Python never silently converts it to a number.

Explanation

This str-to-number cast is not optional boilerplate — it's the direct consequence of input()'s one fixed rule (always returns a string). Forgetting it is one of the most common early runtime errors, because the code looks like it should already work with plain numbers.

Summary

input() always returns a string, so a value the user types must be explicitly cast with int() or float() before use in arithmetic. print() accepts sep and end to control exactly how output is formatted.

📢 Output: The print() Function

The print() function is used to display information on the screen. You can pass multiple values to it, and it will automatically separate them with a space by default.

Special Arguments in print():

  • sep (Separator): Changes the character between values. Default is a space.
  • end: Changes what appears at the end of the line. Default is a newline (\n).
print("IP", "CS", sep="-")  # Output: IP-CS
print("Hello", end=" ")
print("World")               # Output: Hello World (on same line)

📥 Input: The input() Function

The input() function allows a program to pause and wait for the user to type something. CRITICAL RULE: In Python, the input() function always returns data as a String, even if the user types a number.

Example: age = input("Enter age: ")
If the user types 17, the variable age stores "17" (Text), not the number 17.

🔄 Type Conversion (Type Casting)

Since input() only gives us strings, we need to convert that data into numbers if we want to do math. This is called Type Casting.

Function Purpose
int() Converts a value to an Integer.
float() Converts a value to a Decimal (Float).
str() Converts a number or other value to a String.
# Correct way to take numeric input:
marks = int(input("Enter marks: ")) 

Want the full course?

Unlock all chapters, video lectures, and SQL practice exercises.

Get Full Access