Exercise Solutions Available
Step-by-step answers for all textbook questions in this chapter
CBSE Class 11 Computer Science Chapter 5: Getting Started with Python
Python is one of the most popular programming languages in the world and is the language prescribed by CBSE for Class 11 Computer Science. This chapter introduces you to the fundamentals of Python — from installing it on your computer to writing your first programs. Mastering these basics is essential before moving on to control flow, functions, and data structures in later chapters.
Key Definitions
| Term | Definition |
|---|---|
| Python | A high-level, interpreted, open-source programming language known for its simple syntax |
| IDLE | Integrated Development and Learning Environment — Python's default editor and shell |
| Token | The smallest individual unit in a Python program (keyword, identifier, literal, operator, punctuator) |
| Keyword | A reserved word that has a special meaning in Python and cannot be used as an identifier |
| Identifier | A name given to variables, functions, classes, or other objects in a program |
| Literal | A constant value that appears directly in the program code |
| Variable | A named storage location in memory whose value can change during program execution |
| Data Type | A classification of data that tells the compiler how the data is to be used |
| Operator | A symbol that performs an operation on one or more operands |
| Expression | A combination of variables, literals, and operators that evaluates to a value |
| Dynamic Typing | Python's feature where the data type of a variable is determined at runtime |
Detailed Concepts
1. Introduction to Python
Python was created by Guido van Rossum and first released in 1991. It is widely used in education, web development, data science, artificial intelligence, and automation. Key characteristics of Python:
- High-level language: You write code in human-readable English-like syntax. Python handles memory and hardware details automatically.
- Interpreted language: Python code is executed line by line by the interpreter. There is no separate compilation step.
- Open-source: Python is free to use, modify, and distribute. Its source code is publicly available.
- Cross-platform: Python runs on Windows, macOS, Linux, and many other operating systems without modification.
- Case-sensitive:
Name,name, andNAMEare three different identifiers in Python. - Large standard library: Python comes with many built-in modules for file handling, math, networking, and more.
# Your very first Python program
print("Hello, World!")
2. Installing Python and IDLE
Follow these steps to install Python on your computer:
Step 1 — Download: Go to python.org/downloads and download the latest stable version for your operating system.
Step 2 — Install: Run the downloaded installer. Important: Check the box that says "Add Python to PATH" before clicking Install Now.
Step 3 — Verify: Open a terminal (Command Prompt on Windows, Terminal on macOS/Linux) and type:
python --version
# Output: Python 3.12.x (or your installed version)
Using IDLE
IDLE is Python's built-in development environment. It has two modes:
- Interactive Shell (REPL): Type a statement and press Enter to see the result immediately. Great for testing small code snippets.
>>> 2 + 3
5
>>> print("Hello")
Hello
>>> type(42)
<class 'int'>
- Script Mode: Open a new file (File > New File), write multiple lines of code, save with a
.pyextension, and run (Run > Run Module or press F5). This mode is used for writing complete programs.
3. Python Character Set and Tokens
Character Set
Python uses the following characters:
- Letters: a-z, A-Z
- Digits: 0-9
- Special symbols:
+ - * / = < > ( ) { } [ ] ; : ' " # @ & % ! ^ ~ \ | , . _ - Whitespace: space, tab, newline
Tokens
A token is the smallest meaningful unit in a Python program. Python has five types of tokens:
1. Keywords — Reserved words with special meaning. Python 3 has 35 keywords:
2. Identifiers — Names used for variables, functions, classes, etc. Rules:
- Can contain letters (a-z, A-Z), digits (0-9), and underscores (_)
- Must start with a letter or underscore (never a digit)
- Cannot be a keyword
- Case-sensitive (
ageandAgeare different) - No length limit, but keep names meaningful
# Valid identifiers
student_name = "Rahul"
_age = 17
score1 = 95
# Invalid identifiers
# 1name = "Rahul" # starts with digit
# my-name = "Rahul" # contains hyphen
# class = 11 # keyword used as identifier
3. Literals — Constant values in the code:
# Integer literals
42
0b1010 # binary
0o52 # octal
0x2A # hexadecimal
# Float literals
3.14
2.5e3 # scientific notation = 2500.0
# String literals
'Hello'
"World"
'''Multi-line
string'''
# Boolean literals
True
False
# Special literal
None
4. Operators — Symbols that perform operations (covered in detail below).
5. Punctuators — Symbols used to organize program structure: ( ) { } [ ] ; : , . @
4. Data Types
Every value in Python has a data type. Use the type() function to check a value's type.
| Data Type | Keyword | Description | Example |
|---|---|---|---|
| Integer | int | Whole numbers (no decimal point) | 42, -7, 0 |
| Float | float | Numbers with decimal point | 3.14, -0.5, 2.0 |
| Complex | complex | Real + imaginary part | 3+4j, 2-1j |
| String | str | Sequence of characters in quotes | "Hello", 'Python' |
| Boolean | bool | True or False | True, False |
| NoneType | None | Represents absence of value | None |
# Checking data types
print(type(42)) # <class 'int'>
print(type(3.14)) # <class 'float'>
print(type(3 + 4j)) # <class 'complex'>
print(type("Hello")) # <class 'str'>
print(type(True)) # <class 'bool'>
print(type(None)) # <class 'NoneType'>
# int can be arbitrarily large
big = 10 ** 100
print(big) # googol — a 1 followed by 100 zeros
5. Variables and Assignment
A variable is a name that refers to a value stored in memory. Python uses dynamic typing — you do not declare the type; Python figures it out from the value assigned.
Variable Naming Rules
1. Must start with a letter or underscore 2. Can contain letters, digits, and underscores 3. Cannot contain spaces or special characters 4. Cannot be a keyword 5. Case-sensitive
# Assigning values
name = "Anita"
age = 16
height = 5.4
is_student = True
# Multiple assignment
x = y = z = 10 # all three get 10
a, b, c = 1, 2, 3 # a=1, b=2, c=3
# Dynamic typing — type changes at runtime
x = 10 # x is int
x = "hello" # now x is str (allowed in Python)
Type Conversion
Convert between data types using built-in functions:
# int() — converts to integer
print(int(3.9)) # 3 (truncates, does not round)
print(int("42")) # 42
# float() — converts to float
print(float(7)) # 7.0
print(float("3.14")) # 3.14
# str() — converts to string
print(str(42)) # '42'
print(str(3.14)) # '3.14'
# bool() — converts to boolean
print(bool(1)) # True
print(bool(0)) # False
print(bool("")) # False (empty string is falsy)
print(bool("Hello")) # True (non-empty string is truthy)
6. Operators
Arithmetic Operators
| Operator | Name | Example | Result |
|---|---|---|---|
+ | Addition | 5 + 3 | 8 |
- | Subtraction | 5 - 3 | 2 |
* | Multiplication | 5 * 3 | 15 |
/ | Division (float) | 7 / 2 | 3.5 |
// | Floor Division | 7 // 2 | 3 |
% | Modulus (remainder) | 7 % 2 | 1 |
** | Exponentiation | 2 ** 3 | 8 |
print(10 / 3) # 3.3333333333333335 (true division)
print(10 // 3) # 3 (floor division — quotient without decimal)
print(10 % 3) # 1 (remainder)
print(2 ** 10) # 1024 (2 raised to power 10)
Relational (Comparison) Operators
| Operator | Meaning | Example | Result |
|---|---|---|---|
== | Equal to | 5 == 5 | True |
!= | Not equal to | 5 != 3 | True |
< | Less than | 3 < 5 | True |
> | Greater than | 5 > 3 | True |
<= | Less than or equal to | 5 <= 5 | True |
>= | Greater than or equal to | 5 >= 3 | True |
Logical Operators
| Operator | Meaning | Example | Result |
|---|---|---|---|
and | True if both are True | True and False | False |
or | True if at least one is True | True or False | True |
not | Reverses the boolean value | not True | False |
x = 10
print(x > 5 and x < 20) # True
print(x > 15 or x < 5) # False
print(not(x > 5)) # False
Assignment Operators
| Operator | Example | Equivalent To |
|---|---|---|
= | x = 5 | x = 5 |
+= | x += 3 | x = x + 3 |
-= | x -= 3 | x = x - 3 |
*= | x *= 3 | x = x * 3 |
/= | x /= 3 | x = x / 3 |
//= | x //= 3 | x = x // 3 |
%= | x %= 3 | x = x % 3 |
**= | x **= 3 | x = x ** 3 |
Identity Operators
| Operator | Meaning | Example | Result |
|---|---|---|---|
is | Same object in memory | x is y | True/False |
is not | Different object in memory | x is not y | True/False |
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(a is b) # False (different objects, same value)
print(a is c) # True (same object in memory)
print(a == b) # True (same value)
Membership Operators
| Operator | Meaning | Example | Result |
|---|---|---|---|
in | Present in sequence | 'a' in 'apple' | True |
not in | Not present in sequence | 'z' not in 'apple' | True |
print(3 in [1, 2, 3, 4]) # True
print('x' not in 'hello') # True
Bitwise Operators
| Operator | Name | Example | Result | ||
|---|---|---|---|---|---|
& | Bitwise AND | 5 & 3 | 1 | ||
| `\ | ` | Bitwise OR | `5 \ | 3` | 7 |
^ | Bitwise XOR | 5 ^ 3 | 6 | ||
~ | Bitwise NOT | ~5 | -6 | ||
<< | Left Shift | 2 << 2 | 8 | ||
>> | Right Shift | 8 >> 2 | 2 |
7. Operator Precedence
Python evaluates expressions using the following precedence (highest to lowest):
| Priority | Operators | Description | |
|---|---|---|---|
| 1 (highest) | ** | Exponentiation | |
| 2 | ~, +x, -x | Bitwise NOT, unary plus, unary minus | |
| 3 | *, /, //, % | Multiplication, division, floor division, modulus | |
| 4 | +, - | Addition, subtraction | |
| 5 | <<, >> | Bitwise left shift, right shift | |
| 6 | & | Bitwise AND | |
| 7 | ^ | Bitwise XOR | |
| 8 | `\ | ` | Bitwise OR |
| 9 | ==, !=, <, >, <=, >= | Comparison operators | |
| 10 | is, is not | Identity operators | |
| 11 | in, not in | Membership operators | |
| 12 | not | Logical NOT | |
| 13 | and | Logical AND | |
| 14 (lowest) | or | Logical OR |
# Precedence in action
print(2 + 3 * 4) # 14 (multiplication before addition)
print((2 + 3) * 4) # 20 (parentheses override precedence)
print(2 ** 3 ** 2) # 512 (right-associative: 2**(3**2) = 2**9)
Tip: When in doubt, use parentheses to make the order of evaluation explicit.
8. Input and Output
input() — Taking Input from User
The input() function reads a line from the keyboard and always returns a string.
name = input("Enter your name: ")
print("Hello,", name)
# input() always returns a string — convert for numbers
age = int(input("Enter your age: "))
height = float(input("Enter your height in feet: "))
print() — Displaying Output
The print() function outputs data to the screen.
# Basic printing
print("Hello, World!")
# Multiple values separated by commas
print("Name:", name, "Age:", age)
# Custom separator
print(1, 2, 3, sep="-") # 1-2-3
# Custom end character (default is newline)
print("Hello", end=" ")
print("World") # Hello World (same line)
# Printing special characters
print("Line1\nLine2") # \n = newline
print("Tab\there") # \t = tab
print("He said \"Hi\"") # \" = escaped quote
Formatted Output
Using format() method:
name = "Rahul"
marks = 95.678
print("Name: {}, Marks: {}".format(name, marks))
# Name: Rahul, Marks: 95.678
print("Marks: {:.2f}".format(marks))
# Marks: 95.68 (rounded to 2 decimal places)
print("{0} scored {1:.1f}%".format(name, marks))
# Rahul scored 95.7%
Using f-strings (Python 3.6+, preferred for CBSE):
name = "Rahul"
marks = 95.678
print(f"Name: {name}, Marks: {marks:.2f}")
# Name: Rahul, Marks: 95.68
print(f"{name} scored {marks:.1f}%")
# Rahul scored 95.7%
9. Comments
Comments are non-executable lines that explain the code. Python ignores them during execution.
# This is a single-line comment
x = 10 # inline comment after code
'''
This is a multi-line comment.
Actually, this is a multi-line string literal
that Python ignores when not assigned to a variable.
It is commonly used as a multi-line comment.
'''
"""
Another way to write
a multi-line comment using double quotes.
"""
10. First Python Programs
Program 1: Hello World
# Program to display Hello World
print("Hello, World!")
Program 2: Simple Calculator
# Program to add, subtract, multiply and divide two numbers
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
print(f"Addition: {num1 + num2}")
print(f"Subtraction: {num1 - num2}")
print(f"Multiplication: {num1 * num2}")
print(f"Division: {num1 / num2}")
Program 3: Area of a Circle
# Program to calculate area of a circle
radius = float(input("Enter the radius of the circle: "))
pi = 3.14159
area = pi * radius ** 2
print(f"Area of the circle = {area:.2f}")
Program 4: Swapping Two Variables
# Program to swap two variables
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print(f"Before swapping: a = {a}, b = {b}")
# Using a temporary variable
temp = a
a = b
b = temp
print(f"After swapping: a = {a}, b = {b}")
Program 5: Average of Three Numbers
# Program to find average of three numbers
n1 = float(input("Enter first number: "))
n2 = float(input("Enter second number: "))
n3 = float(input("Enter third number: "))
average = (n1 + n2 + n3) / 3
print(f"Average = {average:.2f}")
11. Common Errors in Python
| Error Type | Cause | Example |
|---|---|---|
| SyntaxError | Code violates Python's grammar rules | print("Hello (missing closing quote) |
| NameError | Using a variable that is not defined | print(x) when x was never assigned |
| TypeError | Operation on incompatible types | "2" + 3 (string + int without conversion) |
| IndentationError | Wrong or inconsistent indentation | Mixed tabs and spaces, or missing indent after colon |
| ValueError | Correct type but inappropriate value | int("abc") (cannot convert string to int) |
# SyntaxError — missing closing parenthesis
# print("Hello"
# NameError — variable not defined
# print(score) # NameError if score was never assigned
# TypeError — adding string and number
# age = "16"
# result = age + 2 # TypeError: can only concatenate str to str
# IndentationError — wrong indentation
# if True:
# print("Hello") # IndentationError: expected an indented block
# ValueError — invalid conversion
# x = int("hello") # ValueError: invalid literal for int()
Common Mistakes
1. Forgetting to convert input(): input() always returns a string. For arithmetic, convert with int() or float(). Writing age = input() and then age + 1 causes a TypeError.
2. Using = instead of == for comparison: if x = 5: is a SyntaxError. Use if x == 5: for comparison.
3. Confusing / and //: 7 / 2 gives 3.5 (float division), while 7 // 2 gives 3 (floor division). Know which one you need.
4. Inconsistent indentation: Python uses indentation to define blocks. Mixing tabs and spaces, or using different amounts of spaces, causes IndentationError.
5. Using keywords as variable names: class = 11 is invalid because class is a reserved keyword. Use class_num = 11 instead.
6. Case-sensitivity errors: True is a boolean value, but true is an undefined name (NameError). Similarly, Print() is not the same as print().
7. String concatenation without conversion: "Age: " + 16 causes TypeError. Use "Age: " + str(16) or an f-string: f"Age: {16}".
Exam Tips
1. Memorise the operator precedence table: Questions often test whether you know that * has higher precedence than , which has higher precedence than +. Trace expressions step by step.
2. Practice type conversion with input(): Every exam has at least one question where you read numbers using input() and convert them. Always wrap input() in int() or float() for numerical programs.
3. Know the difference between /, //, and %: These three division operators are frequently tested. / gives a float result, // gives the integer quotient, % gives the remainder.
4. Write clean, indented code: In practical exams, improper indentation costs marks. Use exactly 4 spaces per indent level and be consistent.
5. Use comments in your programs: Add # Program to... at the top and brief inline comments. Examiners appreciate well-documented code.
6. Trace before you write: For output prediction questions, trace each line manually on paper. Write down the current value of each variable after every statement.
7. Remember that Python is case-sensitive: True, False, and None are capitalised. Keywords like if, for, while must be lowercase. Variable names like Name and name are different.
Quick Revision Notes
- Python is a high-level, interpreted, open-source, cross-platform language created by Guido van Rossum.
- IDLE has two modes: Interactive Shell (REPL) for testing and Script Mode for full programs.
- Tokens: keywords, identifiers, literals, operators, punctuators.
- Python has 35 keywords that cannot be used as identifiers.
- Data types:
int,float,complex,str,bool,NoneType. - Python uses dynamic typing — variable types are determined at runtime.
- Arithmetic operators:
+ - / // % *. Remember/vs//vs%. - Relational operators:
== != < > <= >=. Result is alwaysTrueorFalse. - Logical operators:
and or not.andneeds both True;orneeds at least one True. - Assignment operators:
+= -= = /= //= %= *=. - Identity operators:
isandis notcheck memory identity, not just value equality. - Membership operators:
inandnot incheck presence in a sequence. - Precedence order (highest to lowest):
*> unary >/ // %>+ -> shift >&>^>|> comparison > identity > membership >not>and>or. input()always returns a string. Convert withint()orfloat()for numbers.print()withsepandendparameters for custom formatting.- Use f-strings
f"...{expr}..."for clean formatted output. - Comments:
#for single-line, triple quotes for multi-line. - Common errors: SyntaxError, NameError, TypeError, IndentationError, ValueError.
