0% found this document useful (0 votes)
3 views32 pages

Python Practice Full

Python tutorials and imps

Uploaded by

akpatel030778
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views32 pages

Python Practice Full

Python tutorials and imps

Uploaded by

akpatel030778
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Programming

Practice Questions & Complete Solutions


31 Questions — Full Question Text + Explanation + Program + Output

Q1. Variables in Python


Question:
Define variables in Python. Write a program to assign values to variables and display them.
Explanation:
A variable is a named location in memory used to store data. In Python, variables are created the
moment a value is assigned to them using the = operator. Python is dynamically typed, which means
you do not need to declare the type of a variable — the interpreter infers it automatically from the
assigned value.

Rules for naming variables:


- Must begin with a letter (a-z, A-Z) or underscore (_)
- Cannot start with a digit
- Can contain letters, digits, and underscores
- Cannot be a Python keyword (e.g., if, for, while, class, etc.)
- Variable names are case-sensitive (age and Age are different)
Program:
# Assigning values to variables of different types
name = "Alice" # str (string)
age = 20 # int (integer)
height = 5.6 # float (decimal)
is_student = True # bool (boolean)

# Displaying variables using print()


print("Name :", name)
print("Age :", age)
print("Height :", height)
print("Is Student:", is_student)

# Checking the type of each variable


print(type(name)) # <class 'str'>
print(type(age)) # <class 'int'>
print(type(height)) # <class 'float'>
print(type(is_student)) # <class 'bool'>

# Output:
# Name : Alice
# Age : 20
# Height : 5.6
# Is Student: True
Q2. Data Types in Python
Question:
Explain different data types in Python with examples.
Explanation:
Python provides several built-in data types to store and represent different kinds of information. The
main data types are:

1. int - Whole numbers without decimal points (e.g., 10, -5, 0)


2. float - Numbers with decimal points (e.g., 3.14, -0.5)
3. str - Sequence of characters enclosed in quotes (e.g., "Hello")
4. bool - Logical values: True or False
5. list - Ordered, mutable collection of items (e.g., [1, 2, 3])
6. tuple - Ordered, immutable collection (e.g., (10, 20))
7. dict - Key-value pairs (e.g., {"name": "Alice"})
8. set - Unordered collection of unique items (e.g., {1, 2, 3})

The built-in function type() returns the data type of any variable.
Program:
# 1. int
x = 42
print("int :", x, "->", type(x))

# 2. float
pi = 3.14159
print("float:", pi, "->", type(pi))

# 3. str
greeting = "Hello, Python!"
print("str :", greeting, "->", type(greeting))

# 4. bool
flag = True
print("bool:", flag, "->", type(flag))

# 5. list (ordered, mutable)


fruits = ["apple", "banana", "cherry"]
print("list:", fruits, "->", type(fruits))

# 6. tuple (ordered, immutable)


coords = (10, 20, 30)
print("tuple:", coords, "->", type(coords))

# 7. dict (key-value pairs)


student = {"name": "Alice", "age": 20}
print("dict:", student, "->", type(student))

# 8. set (unique elements, unordered)


unique_nums = {1, 2, 3, 3, 2}
print("set :", unique_nums, "->", type(unique_nums))
# Output:
# int : 42 -> <class 'int'>
# float: 3.14159 -> <class 'float'>
# str : Hello, Python! -> <class 'str'>
# bool : True -> <class 'bool'>
# list : ['apple', 'banana', 'cherry'] -> <class 'list'>
# tuple: (10, 20, 30) -> <class 'tuple'>
# dict : {'name': 'Alice', 'age': 20} -> <class 'dict'>
# set : {1, 2, 3} -> <class 'set'>

Q3. Arithmetic Operations


Question:
Write a Python program to perform arithmetic operations (addition, subtraction,
multiplication, division) on two numbers.
Explanation:
Python supports the following arithmetic operators:

+ Addition : adds two numbers


- Subtraction : subtracts right from left
* Multiplication : multiplies two numbers
/ Division : divides and returns a float
// Floor Division : divides and returns integer (floor)
% Modulus : returns remainder of division
** Exponentiation : raises left to the power of right
Program:
# Input two numbers
a = 15
b = 4

# Arithmetic operations
print("a =", a, " b =", b)
print("-" * 30)
print("Addition (a + b) :", a + b) # 19
print("Subtraction (a - b) :", a - b) # 11
print("Multiplication (a * b) :", a * b) # 60
print("Division (a / b) :", a / b) # 3.75
print("Floor Division (a // b) :", a // b) # 3
print("Modulus (a % b) :", a % b) # 3
print("Exponentiation (a ** b) :", a ** b) # 50625

# Output:
# a = 15 b = 4
# ------------------------------
# Addition (a + b) : 19
# Subtraction (a - b) : 11
# Multiplication (a * b) : 60
# Division (a / b) : 3.75
# Floor Division (a // b) : 3
# Modulus (a % b) : 3
# Exponentiation (a ** b) : 50625
Q4. Comparison Operators
Question:
Explain comparison operators in Python with suitable examples.
Explanation:
Comparison operators (also called relational operators) compare two values and return a Boolean
result — either True or False. They are widely used in conditions (if statements, loops, etc.).

Python comparison operators:


== Equal to : True if both values are equal
!= Not equal to : True if values are not equal
> Greater than : True if left is greater than right
< Less than : True if left is less than right
>= Greater than or equal : True if left >= right
<= Less than or equal : True if left <= right
Program:
a = 10
b = 20

print("a =", a, " b =", b)


print("-" * 35)

print("a == b (Equal to) :", a == b) # False


print("a != b (Not equal to) :", a != b) # True
print("a > b (Greater than) :", a > b) # False
print("a < b (Less than) :", a < b) # True
print("a >= 10 (Greater than/equal) :", a >= 10) # True
print("b <= 15 (Less than/equal) :", b <= 15) # False

# Practical use in an if statement


x = 75
if x >= 50:
print("\nResult: Pass")
else:
print("\nResult: Fail")

# Output:
# a = 10 b = 20
# -----------------------------------
# a == b (Equal to) : False
# a != b (Not equal to) : True
# a > b (Greater than) : False
# a < b (Less than) : True
# a >= 10 (Greater than/equal) : True
# b <= 15 (Less than/equal) : False
# Result: Pass
Q5. Logical Operators
Question:
Write a Python program to demonstrate logical operators (and, or, not).
Explanation:
Logical operators are used to combine or negate Boolean expressions. Python has three logical
operators:

and - Returns True only if BOTH operands are True


or - Returns True if AT LEAST ONE operand is True
not - Returns the OPPOSITE Boolean value (negation)

They follow short-circuit evaluation:


- and stops at the first False (no need to check further)
- or stops at the first True (no need to check further)
Program:
x = True
y = False

print("x =", x, " y =", y)


print("-" * 35)

# and operator
print("x and y :", x and y) # False (both must be True)
print("x and x :", x and x) # True

# or operator
print("x or y :", x or y) # True (at least one True)
print("y or y :", y or y) # False

# not operator
print("not x :", not x) # False
print("not y :", not y) # True

# Practical example with numbers


age = 25
income = 50000

if age >= 18 and income > 30000:


print("\nEligible for loan: Yes")
else:
print("\nEligible for loan: No")

# Output:
# x = True y = False
# -----------------------------------
# x and y : False
# x and x : True
# x or y : True
# y or y : False
# not x : False
# not y : True
# Eligible for loan: Yes
Q6. Identity and Membership Operators
Question:
Explain the difference between Identity operators and Membership operators with examples.
Explanation:
IDENTITY OPERATORS — check if two variables refer to the same object in memory (not just equal
values):
is Returns True if both variables point to the same object
is not Returns True if they point to different objects

MEMBERSHIP OPERATORS — check if a value exists within a sequence (list, tuple, string, dict):
in Returns True if the value is found in the sequence
not in Returns True if the value is NOT found in the sequence

Key difference: == checks value equality; is checks object identity.


Program:
# ── Identity Operators ──────────────────────────
a = [1, 2, 3]
b = a # b points to the SAME object as a
c = [1, 2, 3] # c is a NEW object with the same content

print("Identity Operators:")
print("a is b :", a is b) # True (same object)
print("a is c :", a is c) # False (different objects)
print("a is not c :", a is not c) # True
print("a == c :", a == c) # True (same VALUES)

# ── Membership Operators ─────────────────────────


fruits = ["apple", "banana", "cherry"]
print("\nMembership Operators:")
print("'apple' in fruits :", "apple" in fruits) # True
print("'mango' in fruits :", "mango" in fruits) # False
print("'mango' not in fruits :", "mango" not in fruits) # True

# Membership with strings


text = "Hello, Python!"
print("\n'Python' in text :", "Python" in text) # True
print("'Java' in text :", "Java" in text) # False

# Membership with dict checks keys


info = {"name": "Alice", "age": 20}
print("\n'name' in info :", "name" in info) # True
print("'Alice' in info :", "Alice" in info) # False (checks keys)

Q7. Basic List Operations


Question:
Write a Python program to perform basic list operations (add, remove, access elements).
Explanation:
A list is an ordered, mutable (modifiable) collection in Python. Lists are defined using square brackets
[] and can hold elements of different types.

Common list operations:


list[i] Access element at index i (0-based)
list[-1] Access last element
list[a:b] Slice from index a to b-1
[Link](x) Add x at the end
[Link](i,x) Insert x at index i
[Link](x) Remove first occurrence of x
[Link]() Remove and return last element
[Link](i) Remove and return element at index i
len(list) Return number of elements
Program:
# Create a list
fruits = ["apple", "banana", "cherry"]
print("Original list :", fruits)

# ── Accessing elements ───────────────────────────


print("First element :", fruits[0]) # apple
print("Last element :", fruits[-1]) # cherry
print("Slice [0:2] :", fruits[0:2]) # ['apple', 'banana']

# ── Adding elements ──────────────────────────────


[Link]("mango") # Add at end
[Link](1, "orange") # Insert at index 1
print("After adding :", fruits)

# ── Removing elements ────────────────────────────


[Link]("banana") # Remove by value
removed = [Link]() # Remove and return last item
print("Popped item :", removed)
print("After removing :", fruits)

# ── Other operations ─────────────────────────────


print("Length :", len(fruits))
print("Is apple there?:", "apple" in fruits)
[Link]()
print("After sort :", fruits)
[Link]()
print("After reverse :", fruits)

# Output:
# Original list : ['apple', 'banana', 'cherry']
# First element : apple
# Last element : cherry
# Slice [0:2] : ['apple', 'banana']

Q8. Tuples in Python


Question:
Explain tuple characteristics and write a Python program to create and access a tuple.
Explanation:
A tuple is an ordered, immutable (unchangeable) collection of elements, defined using parentheses ().

Characteristics of tuples:
1. Ordered : Elements maintain their insertion order
2. Immutable : Elements cannot be changed after creation
3. Allows duplicates : Multiple identical values are permitted
4. Indexed : Elements are accessed using a 0-based index
5. Faster than lists : Due to immutability, tuples are more efficient
6. Heterogeneous : Can contain elements of different types

Tuples are ideal for fixed data such as coordinates, RGB colors, or database records.
Program:
# Creating tuples
coordinates = (10, 20, 30)
colors = ("red", "green", "blue")
mixed = (1, "Alice", 3.14, True)
single = (42,) # Single-element tuple needs trailing comma

# ── Accessing elements ───────────────────────────


print("coordinates[0] :", coordinates[0]) # 10
print("colors[-1] :", colors[-1]) # blue
print("coordinates[1:] :", coordinates[1:]) # (20, 30)

# ── Looping through a tuple ──────────────────────


print("\nColors:")
for color in colors:
print(" -", color)

# ── Tuple unpacking ──────────────────────────────


x, y, z = coordinates
print("\nUnpacked: x=%d y=%d z=%d" % (x, y, z))

# ── Useful methods ───────────────────────────────


print("Length :", len(colors)) # 3
print("Count of 'red' :", [Link]("red")) # 1
print("Index of 'green':", [Link]("green")) # 1

# ── Immutability demo ────────────────────────────


# colors[0] = "yellow" # TypeError: 'tuple' object does not support item
assignment
print("\nTuples are immutable — values cannot be changed after creation.")

Q9. if Statement
Question:
Explain the syntax of the if statement with an example program.
Explanation:
The if statement is the fundamental decision-making construct in Python. It executes a block of code
only when a specified condition evaluates to True.

Syntax:
if condition:
statement(s) # executed only if condition is True

Key points:
- The condition is any expression that evaluates to True or False
- The colon (:) after the condition is mandatory
- The body must be indented (4 spaces is the convention)
- Python uses indentation instead of braces {} to define blocks
- If the condition is False, the block is skipped entirely
Program:
# Example 1: Simple if statement
age = 18

if age >= 18:


print("You are eligible to vote.")

# Example 2: if with string comparison


username = "admin"
if username == "admin":
print("Welcome, Administrator!")

# Example 3: if with membership check


primes = [2, 3, 5, 7, 11, 13]
num = 7
if num in primes:
print(num, "is a prime number.")

# Example 4: if with multiple statements in block


marks = 85
if marks >= 50:
print("Result : Pass")
print("Marks :", marks)
print("Status : Promoted to next year")

# Output:
# You are eligible to vote.
# Welcome, Administrator!
# 7 is a prime number.
# Result : Pass
# Marks : 85
# Status : Promoted to next year

Q10. if-else: Even or Odd


Question:
Write a Python program using if-else statement to check whether a number is even or odd.
Explanation:
The if-else statement provides TWO alternate paths of execution:
- The if block runs when the condition is True
- The else block runs when the condition is False

Syntax:
if condition:
block_when_true
else:
block_when_false

Logic for even/odd:


A number is even if number % 2 == 0 (remainder is 0 when divided by 2)
A number is odd if number % 2 != 0 (remainder is 1)
Program:
# Program to check Even or Odd

num = int(input("Enter a number: "))

if num % 2 == 0:
print(num, "is an Even number")
else:
print(num, "is an Odd number")

# ── Extended version: check multiple numbers ─────


print("\nChecking numbers 1 to 10:")
for n in range(1, 11):
if n % 2 == 0:
print(f" {n} -> Even")
else:
print(f" {n} -> Odd")

# Sample Output:
# Enter a number: 9
# 9 is an Odd number
#
# Checking numbers 1 to 10:
# 1 -> Odd
# 2 -> Even
# 3 -> Odd ... and so on

Q11. elif Ladder


Question:
Explain the elif ladder with a suitable example.
Explanation:
The elif (else-if) ladder is used to test multiple conditions in sequence. Python evaluates each
condition from top to bottom; when a True condition is found, its block executes and all remaining
conditions are skipped.
Syntax:
if condition1:
block1
elif condition2:
block2
elif condition3:
block3
else:
default_block

Key points:
- Any number of elif clauses can be used
- Only ONE block executes — the first matching condition
- The final else is optional and acts as a catch-all default
Program:
# Grade Classification using elif ladder

marks = int(input("Enter your marks (0 - 100): "))

if marks >= 90:


grade = "A+"
remark = "Outstanding"
elif marks >= 80:
grade = "A"
remark = "Excellent"
elif marks >= 70:
grade = "B"
remark = "Very Good"
elif marks >= 60:
grade = "C"
remark = "Good"
elif marks >= 50:
grade = "D"
remark = "Average"
else:
grade = "F"
remark = "Fail"

print(f"Marks : {marks}")
print(f"Grade : {grade}")
print(f"Remark: {remark}")

# Sample Outputs:
# Enter your marks: 92 -> Grade: A+ Remark: Outstanding
# Enter your marks: 76 -> Grade: B Remark: Very Good
# Enter your marks: 45 -> Grade: F Remark: Fail

Q12. Nested if: Largest of Three Numbers


Question:
Write a Python program using nested if statements to find the largest of three numbers.
Explanation:
A nested if statement is an if statement placed inside the body of another if (or else) block. This
allows multi-level decision making.

Syntax:
if outer_condition:
if inner_condition:
inner_block
else:
inner_else_block
else:
outer_else_block

For finding the largest of three numbers:


- First compare a and b
- Whichever is larger, compare it against c
- The one that survives both comparisons is the largest
Program:
# Find the largest of three numbers using nested if

a = int(input("Enter first number: "))


b = int(input("Enter second number: "))
c = int(input("Enter third number: "))

if a >= b: # a is >= b
if a >= c: # a is also >= c
largest = a
else: # c is > a (and c > b since a >= b)
largest = c
else: # b > a
if b >= c: # b is also >= c
largest = b
else: # c is > b (and c > a)
largest = c

print(f"\nNumbers : {a}, {b}, {c}")


print(f"Largest : {largest}")

# Sample Output:
# Enter first number: 45
# Enter second number: 72
# Enter third number: 60
#
# Numbers : 45, 72, 60
# Largest : 72

Q13. for Loop: Print 1 to 10


Question:
Write a Python program to print numbers from 1 to 10 using a for loop.
Explanation:
The for loop in Python is used to iterate over a sequence (list, tuple, string, range, etc.).

Syntax:
for variable in sequence:
statement(s)

range() function generates a sequence of numbers:


range(stop) : 0 to stop-1
range(start, stop) : start to stop-1
range(start, stop, step) : start to stop-1 with given step

To print 1 to 10: use range(1, 11) — starts at 1, stops before 11.


Program:
# Print numbers 1 to 10 using for loop

print("Numbers from 1 to 10:")


for i in range(1, 11):
print(i, end=" ")

print() # move to new line

# ── Printing with labels ─────────────────────────


print("\nDetailed output:")
for i in range(1, 11):
print(f" Number: {i}")

# ── Print only even numbers 1-10 ─────────────────


print("\nEven numbers from 1 to 10:")
for i in range(2, 11, 2): # step = 2
print(i, end=" ")

# Output:
# Numbers from 1 to 10:
# 1 2 3 4 5 6 7 8 9 10
#
# Even numbers from 1 to 10:
# 2 4 6 8 10

Q14. Multiplication Table Using Loops


Question:
Write a Python program to print the multiplication table of a number using loops.
Explanation:
A multiplication table shows a number multiplied by each integer from 1 to 10 (or any range). A for
loop with range() is the natural choice for this repetitive task.

Algorithm:
1. Accept the number from the user
2. Loop i from 1 to 10
3. Print: number x i = result

We use f-strings (formatted string literals) for clean output formatting.


Program:
# Print multiplication table of a given number

num = int(input("Enter a number: "))

print(f"\n Multiplication Table of {num}")


print(" " + "-" * 25)

for i in range(1, 11):


result = num * i
print(f" {num} x {i:2d} = {result:4d}")

# ── Print tables of 1 to 5 ───────────────────────


print("\nTables from 1 to 5:")
for n in range(1, 6):
print(f"\n Table of {n}:")
for i in range(1, 11):
print(f" {n} x {i} = {n * i}")

# Sample Output (num = 7):


# Multiplication Table of 7
# -------------------------
# 7 x 1 = 7
# 7 x 2 = 14
# 7 x 3 = 21
# ...
# 7 x 10 = 70

Q15. Iterate Through a List Using a Loop


Question:
Write a Python program that iterates through a list and prints all elements using a loop.
Explanation:
Python's for loop can iterate directly over a list without needing index variables. This is called a
'for-each' style loop.

Methods to iterate over a list:


1. Direct iteration : for item in list
2. Index-based iteration : for i in range(len(list))
3. enumerate() : for index, item in enumerate(list)
→ provides both the index and the value simultaneously

enumerate() is the most Pythonic way when both index and value are needed.
Program:
# Iterate through a list and print all elements
fruits = ["apple", "banana", "cherry", "mango", "orange"]

# Method 1: Direct iteration (for-each style)


print("Method 1 — Direct iteration:")
for fruit in fruits:
print(" -", fruit)

# Method 2: Using index with range()


print("\nMethod 2 — Index-based:")
for i in range(len(fruits)):
print(f" fruits[{i}] = {fruits[i]}")

# Method 3: Using enumerate()


print("\nMethod 3 — enumerate():")
for index, fruit in enumerate(fruits):
print(f" {index}: {fruit}")

# ── Iterating a list of numbers ──────────────────


numbers = [10, 25, 37, 42, 56]
total = 0
for n in numbers:
total += n
print(f"\nNumbers : {numbers}")
print(f"Sum : {total}")

# Output:
# Method 1 — Direct iteration:
# - apple
# - banana
# - cherry
# - mango
# - orange

Q16. Function Arguments and Return Values


Question:
Explain function arguments and return values with an example.
Explanation:
A function is a reusable block of code defined using the def keyword.

Arguments (Parameters) — values passed into a function:


Positional arguments : matched by order
Keyword arguments : matched by parameter name
Default arguments : have preset default values used if no argument is passed
Variable-length (*args): accepts any number of positional arguments

Return values — a function sends a result back using return:


- return exits the function immediately
- A function can return multiple values as a tuple
- A function without return implicitly returns None
Program:
# ── Positional arguments ────────────────────────
def add(a, b):
return a + b

print("Sum:", add(10, 20)) # Sum: 30

# ── Default arguments ────────────────────────────


def greet(name, message="Hello"):
return f"{message}, {name}!"

print(greet("Alice")) # Hello, Alice!


print(greet("Bob", "Welcome")) # Welcome, Bob!

# ── Keyword arguments ────────────────────────────


def describe(name, age, city):
return f"{name} is {age} years old from {city}."

print(describe(age=20, city="Delhi", name="Alice"))

# ── Multiple return values ───────────────────────


def stats(numbers):
return min(numbers), max(numbers), sum(numbers)

low, high, total = stats([3, 1, 9, 5, 7])


print(f"Min={low} Max={high} Sum={total}")

# ── Variable-length arguments (*args) ────────────


def multiply_all(*args):
result = 1
for n in args:
result *= n
return result

print("Product:", multiply_all(2, 3, 4, 5)) # 120

# Output:
# Sum: 30
# Hello, Alice!
# Welcome, Bob!
# Alice is 20 years old from Delhi.
# Min=1 Max=9 Sum=25
# Product: 120

Q17. Factorial of a Number (Function)


Question:
Write a Python function to calculate the factorial of a number.
Explanation:
The factorial of a non-negative integer n (written n!) is the product of all positive integers from 1 to n.

Mathematical definition:
0! = 1 (by convention)
1! = 1
n! = n x (n-1) x (n-2) x ... x 2 x 1

Examples:
3! = 3 x 2 x 1 =6
5! = 5 x 4 x 3 x 2 x 1 = 120
7! = 5040

Approach used: iterative (using a for loop).


Factorial is undefined for negative numbers.
Program:
# Function to calculate factorial (iterative)

def factorial(n):
if n < 0:
return "Undefined (negative numbers)"
if n == 0 or n == 1:
return 1
result = 1
for i in range(2, n + 1):
result *= i
return result

# Test the function


print("Factorial calculations:")
print("-" * 25)
for num in [0, 1, 3, 5, 7, 10]:
print(f" {num:2d}! = {factorial(num)}")

# User input
n = int(input("\nEnter a number: "))
print(f"{n}! = {factorial(n)}")

# Output:
# Factorial calculations:
# -------------------------
# 0! = 1
# 1! = 1
# 3! = 6
# 5! = 120
# 7! = 5040
# 10! = 3628800

Q18. Variable Scope (Local and Global)


Question:
Explain variable scope in Python (local and global variables) with examples.
Explanation:
Scope refers to the region of a program where a variable is accessible.

LOCAL variable:
- Declared inside a function
- Accessible ONLY within that function
- Created when the function is called; destroyed when the function ends

GLOBAL variable:
- Declared outside all functions (at module level)
- Accessible from anywhere in the program
- To MODIFY a global variable inside a function, use the global keyword

LEGB Rule — Python searches for variables in this order:


L = Local → E = Enclosing → G = Global → B = Built-in
Program:
# ── Global variable ──────────────────────────────
total = 100 # global variable

def show_values():
local_var = 50 # local variable
print("Inside function:")
print(" local_var (local) :", local_var)
print(" total (global) :", total) # reads global

show_values()

# local_var is not accessible here:


# print(local_var) # NameError!

print("\nOutside function:")
print(" total:", total)

# ── Modifying global variable inside a function ──


counter = 0

def increment():
global counter # declare intent to modify global
counter += 1
print(" Counter inside function:", counter)

print("\nCounter before:", counter)


increment()
increment()
print("Counter after :", counter)

# Output:
# Inside function:
# local_var (local) : 50
# total (global) : 100
# Outside function:
# total: 100
# Counter before: 0
# Counter inside function: 1
# Counter inside function: 2
# Counter after : 2
Q19. Create and Access a Dictionary
Question:
Write a Python program to create and access a dictionary.
Explanation:
A dictionary is an unordered (Python 3.7+ maintains insertion order) collection of key-value pairs. It is
defined using curly braces {}.

Key properties:
- Keys must be unique and immutable (strings, numbers, tuples)
- Values can be of any data type
- Access values using their key: dict[key] or [Link](key)

Common dictionary methods:


[Link]() : returns all keys
[Link]() : returns all values
[Link]() : returns all key-value pairs
[Link](k) : returns value for key k (None if not found)
[Link]({}) : merges another dictionary into this one
del dict[key] : removes a key-value pair
Program:
# Create a dictionary
student = {
"name" : "Alice",
"age" : 20,
"course" : "Computer Science",
"gpa" : 3.8,
"city" : "Delhi"
}

# ── Accessing values ─────────────────────────────


print("Name :", student["name"]) # Alice
print("Age :", [Link]("age")) # 20
print("GPA :", [Link]("gpa", 0.0)) # 3.8

# ── Adding / Updating entries ─────────────────────


student["email"] = "alice@[Link]" # add new key
student["age"] = 21 # update existing key

# ── Deleting an entry ────────────────────────────


del student["city"]

# ── Iterating over the dictionary ────────────────


print("\nStudent Details:")
for key, value in [Link]():
print(f" {key:8} : {value}")

# ── Dictionary methods ───────────────────────────


print("\nKeys :", list([Link]()))
print("Values :", list([Link]()))
print("Exists?:", "name" in student) # True
print("Length :", len(student))
Q20. Sum of Elements in a List (Function)
Question:
Write a Python function to find the sum of elements in a list.
Explanation:
A function can accept a list as a parameter and process each element using a loop. This
demonstrates combining functions and list iteration.

Algorithm:
1. Define function list_sum(numbers)
2. Initialize total = 0
3. Loop through each element in numbers
4. Add each element to total
5. Return total

We also compare our result with Python's built-in sum() function.


Program:
# Function to find sum of all elements in a list

def list_sum(numbers):
total = 0
for num in numbers:
total += num
return total

# Test with various lists


list1 = [1, 2, 3, 4, 5]
list2 = [10, 20, 30, 40, 50]
list3 = [100, 200, 300]
list4 = [1.5, 2.5, 3.5] # floats

print("List:", list1, "-> Sum:", list_sum(list1)) # 15


print("List:", list2, "-> Sum:", list_sum(list2)) # 150
print("List:", list3, "-> Sum:", list_sum(list3)) # 600
print("List:", list4, "-> Sum:", list_sum(list4)) # 7.5

# Verify with built-in sum()


print("\nVerification using built-in sum():")
print(" sum(list1) =", sum(list1))
print(" sum(list2) =", sum(list2))

# User input version


n = int(input("\nHow many elements? "))
nums = [int(input(f" Element {i+1}: ")) for i in range(n)]
print("Sum of entered list:", list_sum(nums))

Q21. Python Modules


Question:
Explain Python modules and write steps to import a module.
Explanation:
A module is a file containing Python code — functions, variables, and classes — that can be imported
and reused in other programs. Modules promote code reusability and organisation.

Types of modules:
1. Built-in modules : come with Python (math, os, sys, datetime, random)
2. Third-party modules: installed via pip (numpy, pandas, requests)
3. User-defined modules: .py files you create yourself

Steps to import a module:


Step 1: Write import module_name
Step 2: Access its contents using module_name.function()

Import styles:
import math → access as [Link]()
from math import sqrt → access as sqrt() directly
import math as m → alias: [Link]()
from math import * → imports everything (not recommended)
Program:
# ── Method 1: Import entire module ───────────────
import math

print("[Link] :", [Link]) # 3.14159...


print("[Link](25) :", [Link](25)) # 5.0
print("[Link](2,8) :", [Link](2, 8)) # 256.0

# ── Method 2: Import specific items ──────────────


from math import factorial, ceil, floor

print("\nfactorial(6) :", factorial(6)) # 720


print("ceil(4.3) :", ceil(4.3)) # 5
print("floor(4.9) :", floor(4.9)) # 4

# ── Method 3: Import with alias ──────────────────


import math as m

print("\nm.log10(1000) :", m.log10(1000)) # 3.0


print("[Link](0) :", [Link](0)) # 0.0
print("[Link](0) :", [Link](0)) # 1.0

# ── Viewing all contents of a module ─────────────


print("\nContents of math module:")
contents = [name for name in dir(math) if not [Link]("_")]
print(contents)

Q22. math Module: Square Root and Power


Question:
Write a Python program using the math module to calculate square root and power.
Explanation:
The math module is a built-in Python module that provides access to mathematical functions. Key
functions include:

[Link](x) : square root of x (returns float)


[Link](x, y) : x raised to the power y (returns float)
[Link] : mathematical constant pi (3.14159...)
math.e : Euler's number (2.71828...)
[Link](x) : natural logarithm of x
math.log10(x) : base-10 logarithm of x
[Link](x) : largest integer <= x
[Link](x) : smallest integer >= x
[Link](x) : absolute value as float
Program:
import math

# ── Square Root ──────────────────────────────────


numbers = [4, 9, 16, 25, 49, 144]
print("Square Roots:")
for n in numbers:
print(f" sqrt({n:3d}) = {[Link](n)}")

# ── Power ────────────────────────────────────────
print("\nPowers:")
print(f" pow(2, 10) = {[Link](2, 10)}") # 1024.0
print(f" pow(3, 4) = {[Link](3, 4)}") # 81.0
print(f" pow(5, 0) = {[Link](5, 0)}") # 1.0

# ── User input example ───────────────────────────


num = float(input("\nEnter a number: "))
exp = float(input("Enter the exponent: "))

print(f"
Square root of {num} = {[Link](num):.4f}")
print(f"{num} raised to {exp} = {[Link](num, exp):.4f}")

# ── Other math functions ──────────────────────────


print("\nOther functions:")
print(f" pi = {[Link]:.6f}")
print(f" e = {math.e:.6f}")
print(f" log10(1000) = {math.log10(1000)}")
print(f" floor(3.7) = {[Link](3.7)}")
print(f" ceil(3.2) = {[Link](3.2)}")

Q23. User-Defined Module


Question:
Explain how to create a user-defined module in Python with example.
Explanation:
A user-defined module is a Python source file (.py) you create that contains reusable functions,
variables, or classes.

Steps to create and use a user-defined module:


Step 1: Create a new file, e.g., [Link]
Step 2: Write functions, constants, or classes inside it
Step 3: Save the file in the same directory as your main program
Step 4: In the main program, import using: import mymodule
Step 5: Call functions as: mymodule.function_name()

The __name__ == '__main__' guard prevents module code from running


when it is imported by another file.
Program:
# ═══════════════════════════════════════════
# File: [Link] (the user-defined module)
# ═══════════════════════════════════════════

PI = 3.14159 # module-level constant

def greet(name):
"""Return a greeting message."""
return f"Hello, {name}! Welcome."

def square(n):
"""Return the square of n."""
return n * n

def cube(n):
"""Return the cube of n."""
return n * n * n

def circle_area(radius):
"""Return area of circle with given radius."""
return PI * radius * radius

if __name__ == "__main__":
print("Running mymodule directly")

# ═══════════════════════════════════════════
# File: [Link] (the program that uses it)
# ═══════════════════════════════════════════

import mymodule

print([Link]("Alice")) # Hello, Alice! Welcome.


print("Square of 6 :", [Link](6)) # 36
print("Cube of 3 :", [Link](3)) # 27
print("Circle area :", mymodule.circle_area(5)) # 78.53975
print("PI constant :", [Link]) # 3.14159

# Import specific items


from mymodule import greet, square
print(greet("Bob")) # Hello, Bob! Welcome.
print(square(9)) # 81
Q24. Current Date and Time
Question:
Write a Python program to display the current date and time using the datetime module.
Explanation:
The datetime module is a built-in Python module for working with dates and times.

Key classes:
[Link] : date AND time combined
[Link] : date only (year, month, day)
[Link] : time only (hour, minute, second)
[Link] : difference between two dates/times

Important methods:
[Link]() : returns current local date and time
[Link]() : returns today's date
strftime(format) : formats date/time as a string

Common format codes for strftime:


%d=day %m=month %Y=4-digit year %H=hour %M=minute %S=second
%A=weekday name %B=month name
Program:
from datetime import datetime, date, time

# ── Current date and time ────────────────────────


now = [Link]()
print("Full datetime :", now)

# ── Formatted output ─────────────────────────────


print("Date (DD/MM/YYYY):", [Link]("%d/%m/%Y"))
print("Time (HH:MM:SS) :", [Link]("%H:%M:%S"))
print("Weekday :", [Link]("%A"))
print("Month name :", [Link]("%B"))
print("12-hour clock :", [Link]("%I:%M %p"))

# ── Accessing individual components ──────────────


print("\nComponents:")
print(" Year :", [Link])
print(" Month :", [Link])
print(" Day :", [Link])
print(" Hour :", [Link])
print(" Minute :", [Link])
print(" Second :", [Link])

# ── Today's date only ────────────────────────────


today = [Link]()
print("\nToday's Date :", today)

# Sample Output:
# Full datetime : 2024-10-15 14:30:22.145678
# Date (DD/MM/YYYY): 15/10/2024
# Time (HH:MM:SS) : 14:30:22
# Weekday : Tuesday

Q25. Swap Two Numbers Without Third Variable


Question:
Write a Python program to swap two numbers without using a third variable.
Explanation:
Swapping means exchanging the values of two variables. Normally a temporary variable is used, but
Python offers cleaner alternatives.

Three methods without a third variable:

Method 1 — Python tuple unpacking (most Pythonic):


a, b = b, a
Python evaluates the right side first, then assigns.

Method 2 — Arithmetic (addition & subtraction):


a=a+b
b = a - b (original a)
a = a - b (original b)

Method 3 — XOR bitwise operator:


a=a^b
b=a^b
a=a^b
Works only for integers.
Program:
# ── Method 1: Tuple unpacking (Pythonic) ─────────
a, b = 10, 20
print("Before swap: a =", a, ", b =", b)
a, b = b, a
print("After swap: a =", a, ", b =", b)

# ── Method 2: Arithmetic (no temp variable) ───────


x, y = 100, 200
print("\nBefore swap: x =", x, ", y =", y)
x = x + y # x = 300
y = x - y # y = 300 - 200 = 100 (original x)
x = x - y # x = 300 - 100 = 200 (original y)
print("After swap: x =", x, ", y =", y)

# ── Method 3: XOR bitwise ────────────────────────


p, q = 5, 9
print("\nBefore swap: p =", p, ", q =", q)
p = p ^ q
q = p ^ q
p = p ^ q
print("After swap: p =", p, ", q =", q)

# Output:
# Before swap: a = 10 , b = 20
# After swap: a = 20 , b = 10
#
# Before swap: x = 100 , y = 200
# After swap: x = 200 , y = 100
#
# Before swap: p = 5 , q = 9
# After swap: p = 9 , q = 5

Q26. Check Positive, Negative, or Zero


Question:
Write a Python program to check whether a number is positive, negative, or zero.
Explanation:
Numbers can be classified into three categories:
Positive : greater than zero (n > 0)
Negative : less than zero (n < 0)
Zero : equal to zero (n == 0)

We use an if-elif-else ladder to handle all three cases. The program accepts both integer and float
inputs using float().

Algorithm:
1. Read number from user
2. If n > 0 → Positive
3. Elif n < 0 → Negative
4. Else → Zero
Program:
# Check if a number is positive, negative, or zero

num = float(input("Enter a number: "))

if num > 0:
print(f"{num} is a Positive number")
elif num < 0:
print(f"{num} is a Negative number")
else:
print("The number is Zero")

# ── Testing multiple values automatically ─────────


print("\nClassifying a set of numbers:")
test_values = [15, -8, 0, 3.5, -0.001, 100, -50]

for n in test_values:
if n > 0:
category = "Positive"
elif n < 0:
category = "Negative"
else:
category = "Zero"
print(f" {n:8} → {category}")

# Sample Output:
# Enter a number: -7.5
# -7.5 is a Negative number
#
# Classifying a set of numbers:
# 15 → Positive
# -8 → Negative
# 0 → Zero
# 3.5 → Positive

Q27. Largest of Three Numbers (Comparison Operators)


Question:
Write a Python program to find the largest of three numbers using comparison operators.
Explanation:
To find the largest of three numbers using comparison operators, we test each number against the
other two using and to combine conditions.

Logic:
- If a >= b AND a >= c → a is the largest
- Elif b >= a AND b >= c → b is the largest
- Else → c is the largest

This differs from Q12 (nested if) in that it uses compound conditions
with logical and operator rather than nested if-else blocks.
Program:
# Find the largest of three numbers using comparison operators

a = int(input("Enter first number: "))


b = int(input("Enter second number: "))
c = int(input("Enter third number: "))

# Using comparison operators with and


if a >= b and a >= c:
largest = a
elif b >= a and b >= c:
largest = b
else:
largest = c

print(f"\nNumbers entered : {a}, {b}, {c}")


print(f"Largest number : {largest}")

# ── Verification using Python built-in max() ─────


print(f"Verified (max()): {max(a, b, c)}")

# ── Test with equal values ────────────────────────


x, y, z = 10, 10, 5
if x >= y and x >= z:
print(f"\nLargest of {x},{y},{z} is: {x} (tie handled)")

# Sample Output:
# Enter first number: 48
# Enter second number: 72
# Enter third number: 55
#
# Numbers entered : 48, 72, 55
# Largest number : 72
# Verified (max()): 72

Q28. Even or Odd Check (if-else)


Question:
Write a Python program to check whether a number is even or odd using if-else statement.
Explanation:
This program uses the modulus operator (%) to determine divisibility by 2.

Rule:
Even : number % 2 == 0 (no remainder when divided by 2)
Odd : number % 2 != 0 (remainder of 1)

Examples:
8 % 2 = 0 → Even
7 % 2 = 1 → Odd

Note: This is similar to Q10 but extended with additional demonstrations.


Zero (0) is considered even because 0 % 2 = 0.
Program:
# Check even or odd using if-else

number = int(input("Enter an integer: "))

if number % 2 == 0:
print(f"{number} is an Even number")
else:
print(f"{number} is an Odd number")

# ── Extended: classify a range of numbers ─────────


print("\n Number | Category")
print(" ---------|----------")
for n in range(1, 16):
if n % 2 == 0:
category = "Even"
else:
category = "Odd"
print(f" {n:4d} | {category}")

# ── Separate even and odd from a list ────────────


numbers = [3, 8, 12, 7, 22, 5, 14, 9]
evens = [n for n in numbers if n % 2 == 0]
odds = [n for n in numbers if n % 2 != 0]
print(f"\nOriginal : {numbers}")
print(f"Even : {evens}")
print(f"Odd : {odds}")

Q29. Function to Find Square of a Number


Question:
Write a Python function to find the square of a number and display the result.
Explanation:
The square of a number n is n multiplied by itself: n x n = n².

We define a function square(n) that:


- Accepts one parameter n
- Computes n * n (or equivalently n ** 2)
- Returns the result

This program demonstrates:


- Defining and calling a simple function
- Using return to send back a computed value
- Testing a function with multiple inputs
- Comparing function result with ** operator
Program:
# Function to calculate the square of a number

def square(n):
"""Return the square of n."""
return n * n

# ── Display squares for a range of numbers ────────


print("Number | Square")
print("--------|--------")
for num in range(1, 11):
print(f" {num:4d} | {square(num):6d}")

# ── User input ────────────────────────────────────


user_num = int(input("\nEnter a number: "))
result = square(user_num)
print(f"Square of {user_num} = {result}")

# ── Verify with ** operator ───────────────────────


print(f"Verification (** operator): {user_num ** 2}")

# ── Square of float ───────────────────────────────


def square_float(n):
return n ** 2

print(f"\nSquare of 3.5 = {square_float(3.5)}") # 12.25


print(f"Square of 1.5 = {square_float(1.5)}") # 2.25
# Output:
# Number | Square
# --------|--------
# 1 | 1
# 2 | 4
# 3 | 9 ... up to 10 | 100

Q30. math Module: Square Root, Power & Factorial


Question:
Write a Python program using the math module to calculate square root, power, and factorial
of a number.
Explanation:
This program combines three math module functions into a single program:

[Link](x) : returns the square root of x as a float


[Link](x, y) : returns x raised to the power y as a float
[Link](n) : returns n! (factorial) as an integer
(only works for non-negative integers)

Note: [Link]() does not accept floats or negative numbers.


Use int() to convert float input before calling factorial().
Program:
import math

# ── User input ────────────────────────────────────


num = int(input("Enter a non-negative integer: "))

print(f"\nResults for n = {num}:")


print("-" * 35)

# Square Root
sq_root = [Link](num)
print(f"Square Root : {sq_root:.4f}")

# Power (n^3 as example)


power3 = [Link](num, 3)
print(f"Power (n^3) : {power3:.0f}")

# Factorial
if num >= 0:
fact = [Link](num)
print(f"Factorial (n!) : {fact}")
else:
print("Factorial : Undefined for negative numbers")

# ── Table of results for 1 to 8 ───────────────────


print("
n | sqrt(n) | n^2 | n!")
print("----|----------|-------|----------")
for n in range(1, 9):
print(f" {n} | {[Link](n):.4f} | {n**2:5} | {[Link](n)}")

# Sample Output (num = 5):


# Results for n = 5:
# Square Root : 2.2361
# Power (n^3) : 125
# Factorial (n!) : 120

Q31. Factorial — Iterative & Recursive


Question:
Write a Python function to calculate the factorial of a number.
Explanation:
This question revisits factorial with TWO implementation approaches:

ITERATIVE approach:
Uses a for loop to multiply numbers from 2 to n.
Straightforward and easy to understand.
Better for large values of n (no risk of stack overflow).

RECURSIVE approach:
The function calls itself with a smaller argument.
Base case: factorial(0) = 1 and factorial(1) = 1
Recursive case: factorial(n) = n * factorial(n-1)
Elegant and closely mirrors the mathematical definition.
Caution: deep recursion can hit Python's recursion limit (~1000).

Both approaches produce identical results.


Program:
# ── Method 1: Iterative factorial ────────────────
def factorial_iterative(n):
if n < 0:
return "Undefined"
result = 1
for i in range(2, n + 1):
result *= i
return result

# ── Method 2: Recursive factorial ────────────────


def factorial_recursive(n):
if n < 0:
return "Undefined"
if n == 0 or n == 1: # base case
return 1
return n * factorial_recursive(n - 1) # recursive call

# ── Compare both methods ──────────────────────────


print(f"{'n':>4} | {'Iterative':>12} | {'Recursive':>12}")
print("-" * 35)
for n in [0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12]:
it = factorial_iterative(n)
re = factorial_recursive(n)
print(f"{n:4} | {it:12} | {re:12}")

# ── How recursion works (trace for n=4) ──────────


print("\nRecursion trace for factorial(4):")
print(" factorial(4)")
print(" = 4 * factorial(3)")
print(" = 4 * 3 * factorial(2)")
print(" = 4 * 3 * 2 * factorial(1)")
print(" = 4 * 3 * 2 * 1")
print(" = 24")

# Output:
# n | Iterative | Recursive
# -----------------------------------
# 0 | 1 | 1
# 5 | 120 | 120
# 10 | 3628800 | 3628800

— End of Python Practice Solutions —

You might also like