Chapter 05: Getting Started with Python
5.1 Introduction to Python
Before learning how to write programs in Python, we must first understand what a program really is and why Python is needed at all.
A computer is a machine that can process data very fast, but it cannot think or make decisions on its own. It only follows instructions given to it. A program is nothing more than an ordered set of instructions written to tell the computer exactly what to do, step by step.
However, computers do not understand human languages like English. At the lowest level, they only understand machine language, which consists of 0s and 1s. Writing programs directly in machine language is extremely difficult, error-prone, and impractical for humans.
To bridge this gap, high-level programming languages were developed. These languages allow humans to write instructions in a readable form, which are then translated into machine language.
Python is one such high-level programming language.
Python was developed by Guido van Rossum and was designed with a clear goal:
Programming should be simple, readable, and close to human thinking.
Why Python is called an interpreted language
Python does not convert the entire program into machine language at once. Instead, it uses an interpreter, which:
- reads one statement at a time,
- translates it into machine instructions,
- executes it immediately.
This means:
- Errors are detected as soon as Python reaches the faulty line
- Program execution stops immediately when an error occurs
This behaviour is very important and will later help us understand runtime errors and debugging.
Key Characteristics of Python (as emphasised by NCERT)
Python has the following important features:
High-level language Python hides complex machine-level details from the programmer.
Interpreted language Programs are executed line by line.
Readable and simple syntax Python uses English-like words and minimal symbols.
Case-sensitive
marksandMarksare treated as different names.Platform independent The same Python program can run on Windows, Linux, or macOS.
Rich standard library Python provides many built-in functions and modules.
Indentation-based structure Blocks of code are defined by indentation, not braces.
5.1.2 Working with Python
To run Python programs, we need a Python interpreter, also known as the Python shell.
Python provides two execution modes, each serving a different purpose.
Interactive Mode
In interactive mode:
- Commands are typed directly at the
>>>prompt - Python executes each statement immediately
- Results are shown instantly
- Code is not saved
This mode is useful for:
- learning Python syntax
- testing small expressions
- experimenting quickly
Example:
>>> 5 + 3
8
>>> print("Hello Python")
Hello Python
Script Mode
In script mode:
- Programs are written in a file with
.pyextension - Code can be saved, edited, and reused
- Suitable for real programs
Example (hello.py):
print("Welcome to Python programming")
Script mode is used for all serious programming work.
5.2 Python Keywords
While learning Python, students often wonder:
“Why can’t I use certain words as variable names?”
The answer lies in keywords.
Keywords are reserved words that have special meaning to the Python interpreter. Python already knows what these words mean, so they cannot be redefined.
If Python allowed keywords to be used freely, it would no longer be able to understand program structure.
Complete Python Keyword List (NCERT)
False class finally is return
None continue for lambda try
True def from nonlocal while
and del global not with
as elif if or yield
assert else import pass
break except in raise
Important points:
- Keywords are case-sensitive
Trueis a keyword,trueis not- Using a keyword as a variable name causes a syntax error
Example:
if True:
print("Correct usage")
# if = 10 ❌ invalid
5.3 Identifiers
An identifier is the name used to identify:
- a variable
- a function
- or any other program element
Identifiers are essential because they allow us to refer to data stored in memory.
Rules for Identifiers (explained logically)
Must start with a letter or underscore This helps Python distinguish names from numbers.
Cannot start with a digit Otherwise Python cannot tell whether
2xis a number or a name.Can contain only letters, digits, and underscore Special symbols have other meanings in Python.
Cannot be a keyword Keywords already belong to Python.
Examples
Valid:
totalMarks = 450
_studentName = "Riya"
avg_score = 82
Invalid (with reasons):
2marks = 90 # starts with digit
total-marks = 90 # hyphen not allowed
for = 5 # keyword
Identifiers should always be meaningful, because programs are read more often than they are written.
5.4 Variables
A variable is a name that refers to a value stored in memory.
In Python:
- Variables are created automatically
- No need to declare data types explicitly
- The type depends on the value assigned
This behaviour is called dynamic typing.
Example:
name = "Anita"
age = 16
percentage = 89.5
Python decides internally:
name→ stringage→ integerpercentage→ float
We can verify this:
print(type(name))
print(type(age))
print(type(percentage))
Variables must always be assigned a value before use, otherwise Python raises an error.
5.5 Comments
When humans read code, they need explanations. When Python reads code, it needs only instructions.
Comments exist purely for humans.
Why comments are necessary
- Explain what the code does
- Make programs easier to understand
- Help during debugging
- Essential in teamwork
Types of Comments
Single-line comment:
# This program calculates average marks
Multi-line comment (docstring):
"""
This program demonstrates
the use of comments in Python
"""
Python ignores comments completely during execution.
5.6 Everything is an Object
Python follows an object-oriented approach.
This means:
- Numbers are objects
- Strings are objects
- Lists are objects
- Functions are objects
Each object has:
- Type → what kind of data it is
- Value → actual data stored
- Identity → memory location
Example:
x = 10
print(type(x))
y = "Python"
print(type(y))
Understanding this idea helps later when learning data structures and functions.
5.7 Data Types (Conceptually Explained)
A data type tells Python:
- what kind of value is being stored
- how much memory is required
- what operations are allowed
Without data types, Python would not know how to process data correctly.
Numeric Data Types
Integer (int)
Stores whole numbers without decimal part.
count = 25
temperature = -5
Integers are used where exact values are required.
Float (float)
Stores numbers with decimal part.
average = 76.5
pi = 3.14
Floats are used where precision is needed.
Complex (complex)
Stores numbers of the form a + bj.
z = 2 + 3j
Used mainly in advanced mathematics and engineering.
Boolean Data Type
Boolean values represent truth conditions.
isPassed = True
isAbsent = False
Booleans are the foundation of decision making in programs.
String Data Type
A string is a sequence of characters.
subject = "Computer Science"
Strings are indexed, meaning each character has a position.
print(subject[0]) # C
print(subject[-1]) # e
Strings are immutable — once created, they cannot be changed.
List Data Type
A list stores multiple values in a single variable.
marks = [85, 90, 78, 92]
Key properties:
- Ordered
- Mutable (can be changed)
Can store mixed data types
marks[0] = 88
Tuple Data Type
A tuple is similar to a list but immutable.
dimensions = (10, 20)
Tuples are used when data must not change.
Set Data Type
A set stores unique values only.
numbers = {1, 2, 3, 2, 1}
Output:
{1, 2, 3}
Sets are useful when duplicates must be eliminated.
Dictionary Data Type
A dictionary stores data as key–value pairs.
student = {
"name": "Amit",
"class": 11,
"marks": 85
}
Dictionaries are used to represent real-world structured data.
None Data Type
None represents absence of value.
result = None
It is often used as a placeholder.
5.8 Operators
Operators allow us to manipulate data.
Arithmetic:
a = 10
b = 3
print(a + b)
print(a // b)
print(a ** b)
Relational:
print(a > b)
print(a == b)
Logical:
print(True and False)
5.9 Expressions
An expression is anything that produces a value.
result = 15.0 / 4 + (8 + 3)
Python evaluates expressions using operator precedence.
5.10 Statements
A statement is a complete instruction that Python can execute.
x = 4
cube = x ** 3
print(cube)
5.11 Input and Output
Input allows programs to interact with users.
age = input("Enter age: ")
Important:
input()always returns a string
So conversion is necessary:
age = int(input("Enter age: "))
Output is displayed using print().
5.12 Type Conversion
Type conversion changes one data type into another.
Explicit:
x = "10"
y = int(x)
Implicit:
a = 10
b = 2.5
c = a + b
Python converts to a wider type to prevent data loss.
5.13 Debugging (Fully Explained)
Debugging is the process of finding and fixing errors in a program.
Errors exist because programs pass through three stages:
- Reading (syntax)
- Execution (runtime)
- Logical correctness (output)
Syntax Errors
Occur when Python cannot understand the language structure.
print("Hello"
- Detected before execution
- Program does not run at all
Runtime Errors
Occur while the program is running.
x = 10 / 0
- Syntax is correct
- Error depends on data or input
- Program crashes at that point
Logical Errors
Occur when the program runs successfully but produces wrong output.
area = length + breadth # wrong logic
- Most difficult to detect
- No error message
- Found by checking results
How Debugging is Done
- Read error messages
- Print intermediate values
- Check logic carefully
- Test with different inputs
Key Conceptual Takeaways
- Python is an
open-source, high level, interpreterbasedlanguage that can be used for a multitude of scientific and non-scientific computing purposes. Commentsare non-executable statements in a program.- An
identifieris a user defined name given to avariableor aconstantin a program. - The process of identifying and removing errors from a computer program is called
debugging. - Trying to use a variable that has not been assigned a value gives an error.
- There are several data types in Python —
integer, boolean, float, complex, string, list, tuple, sets, Noneanddictionary. - Datatype
conversioncan happen eitherexplicitlyorimplicitly. Operatorsare constructs that manipulate the value of operands. Operators may beunaryorbinary.- An
expressionis a combination of values, variables and operators. - Python has
input()function for taking user input. - Python has
print()function to output data to a standard output device.