Unit 3: Python Programming
Q1. What are the advantages of Python programming?
Ans:
Simple and easy to learn
Open source and free
Portable and extensible
Interpreted language
Object-oriented programming support
Rich libraries and community support
Q2. What are the data types available in Python?
Ans:
Numeric (int, float, complex)
Sequence (list, tuple, range)
Text (string)
Set (set, frozenset)
Mapping (dictionary)
Boolean (True/False)
None type
Q3. What is the difference between mutable and immutable objects in Python?
Ans:
Mutable objects: Can be changed after creation (e.g., list, dictionary, set).
Immutable objects: Cannot be changed after creation (e.g., string, tuple, frozenset).
Q4. What is the difference between list and tuple in Python?
Ans:
List: Mutable, slower, defined using square brackets [ ].
Tuple: Immutable, faster, defined using parentheses ( ).
Q5. Explain dictionary in Python with an example.
Ans:
A dictionary stores data in key-value pairs.
Example:
student = {"name": "Rahul", "age": 20, "marks": 85}
print(student["name"]) # Output: Rahul
Q6. What are Python functions? Explain with an example.
Ans:
A function is a reusable block of code that performs a specific task.
Example:
def add(a, b):
return a + b
print(add(5, 3)) # Output: 8
Q7. What is the difference between local and global variables?
Ans:
Local variable: Declared inside a function, accessible only within it.
Global variable: Declared outside all functions, accessible throughout the program.
Q8. What are Python control structures?
Ans:
Conditional statements: if, if-else, if-elif-else
Loops: for loop, while loop
Control keywords: break, continue, pass
🐍 Unit 3 – Python Programming (Summary Notes)
🔹 Introduction
Python created by Guido van Rossum (1991).
Named after “Monty Python’s Flying Circus” (a comedy show).
Features: Simple, high-level, interpreted, cross-platform, open-source, huge libraries.
🔹 Tokens in Python
Keywords – reserved words (e.g., if, else, for).
Identifiers – names for variables/functions (can’t start with digit).
Literals – constant values (numbers, strings, True/False, None).
Operators – Arithmetic (+, -, *, /), Relational (==, >), Logical (and, or, not), etc.
Punctuators – symbols like : , ( ) [ ] { }.
🔹 Data Types
Numeric – int, float, complex
Text – string "Hello"
Sequence – list [ ], tuple ( ), range()
Set – set { }, frozenset
Mapping – dictionary {key: value}
Boolean – True / False
None – represents null value
🔹 Variables
Dynamic typing → type decided at runtime.
Example:
x = 10 # int
x = "Hello" # string
🔹 Control Structures
Conditional statements: if, if-else, if-elif-else
Loops: for loop, while loop
Control keywords: break, continue, pass
🔹 Functions
Block of reusable code, defined using def.
Example:
def square(n):
return n*n
🔹 Collections
List – ordered, mutable
Tuple – ordered, immutable
Set – unordered, unique elements
Dictionary – key-value pairs
🔹 File Handling (CSV)
import csv to work with CSV files.
csv.reader() → read data
csv.writer() → write data
🔹 Libraries for AI
NumPy – numerical computing (arrays, maths ops)
Pandas – data manipulation (DataFrames)
Scikit-learn – machine learning algorithms (classification, regression, clustering)
ANSWER THE FOLLOWING :-
1. input() function accepts the value as string only. How can you convert string to int?
You can use the int() function to convert a string to an integer.
num = int(input("Enter a number: "))
2. What are variables? What are the rules of declaring variables in Python?
A variable is a name given to a memory location where data is stored.
Rules for declaring variables in Python:
1. Variable names must start with a letter or underscore (_), not with digits.
2. Variable names can contain letters, digits, and underscores, but no special characters
or spaces.
3. Variable names are case-sensitive (age and Age are different).
4. Reserved words (keywords) cannot be used as variable names.
Example:
name = "Alice"
_age = 25
score1 = 90
3. What do you mean by type casting?
Type casting is the process of converting one data type into another, explicitly or implicitly.
Examples:
x = int("10") # string to int
y = float(5) # int to float
z = str(25) # int to string
4. “Python supports dynamic typing”, True or False. Justify your answer.
✅ True
In Python, variables are not bound to a specific data type. A variable can hold different types of
values during program execution.
Example:
x = 10 # x is int
x = "Hello" # now x is str
5. Name any four features of Python language.
1. Simple and easy to learn.
2. Interpreted language (no need for compilation).
3. Dynamically typed.
4. Large standard library and support for third-party modules.
6. Give examples for keywords.
Keywords are reserved words in Python that have special meaning. Examples:
if, else, while, for, True, False, None, import, class, def
7. Expand CSV.
CSV → Comma Separated Values
8. How do you read data from a CSV file into a Pandas DataFrame?
You can use pandas.read_csv() function.
Example:
import pandas as pd
df = pd.read_csv("data.csv")
print(df.head()) # displays first 5 rows
1. Describe the data types supported by Python, providing relevant examples.
In Python, data types specify the type of value a variable can store. They are broadly categorized into
the following:
(a) Numeric Types
int → Whole numbers, positive or negative, without decimal.
x = 10
y = -25
float → Numbers with decimal point.
pi = 3.14
salary = 25000.75
complex → Numbers with a real and imaginary part.
z = 3 + 4j # real=3, imaginary=4
(b) Sequence Types
str (String) → Sequence of characters enclosed in single, double, or triple quotes.
name = "Python"
list → Ordered, mutable (changeable), and allows duplicates.
fruits = ["apple", "banana", "mango"]
tuple → Ordered, immutable (cannot be changed), and allows duplicates.
point = (10, 20, 30)
(c) Set Types
set → Unordered collection of unique items.
nums = {1, 2, 3, 3, 2} # output: {1, 2, 3}
frozenset → Immutable version of a set.
fs = frozenset([1, 2, 3])
(d) Mapping Type
dict (Dictionary) → Collection of key-value pairs.
student = {"name": "Alice", "age": 20, "grade": "A"}
(e) Boolean Type
bool → Represents True or False.
flag = True
result = False
(f) None Type
Represents the absence of a value.
x = None
Python supports int, float, complex, str, list, tuple, set, frozenset, dict, bool, and NoneType as its
fundamental data types.
2. Define an operator and provide examples of different operators along with their functions.
An operator is a symbol that performs a specific operation on one or more operands (variables or
values).
Python supports several types of operators:
(a) Arithmetic Operators (used for mathematical operations)
x, y = 10, 3
print(x + y) # 13 (Addition)
print(x - y) # 7 (Subtraction)
print(x * y) # 30 (Multiplication)
print(x / y) # 3.33 (Division)
print(x % y) # 1 (Modulus → remainder)
print(x ** y) # 1000 (Exponentiation → 10^3)
print(x // y) # 3 (Floor division)
(b) Relational / Comparison Operators (compare values, return True/False)
a, b = 5, 10
print(a == b) # False
print(a != b) # True
print(a > b) # False
print(a < b) # True
print(a >= b) # False
print(a <= b) # True
(c) Logical Operators (combine conditional statements)
x, y = True, False
print(x and y) # False
print(x or y) # True
print(not x) # False
(d) Assignment Operators (assign values to variables)
n = 10
n += 5 # n = n + 5 → 15
n -= 3 # n = n - 3 → 12
n *= 2 # n = n * 2 → 24
n /= 4 # n = n / 4 → 6.0
(e) Bitwise Operators (operate on binary representation of numbers)
a, b = 5, 3 # 5 → 101, 3 → 011
print(a & b) # 1 (AND)
print(a | b) # 7 (OR)
print(a ^ b) # 6 (XOR)
print(~a) # -6 (NOT)
print(a << 1) # 10 (Left shift)
print(a >> 1) # 2 (Right shift)
(f) Membership Operators
lst = [1, 2, 3, 4]
print(2 in lst) # True
print(5 not in lst) # True
(g) Identity Operators
x = [1, 2]
y = [1, 2]
print(x is y) # False (different objects in memory)
print(x == y) # True (same values)
print(x is not y) # True .