QUESTION BANK FOR
PYTHON PROGRAMMING TECHNIQUES
(TIU-UCA-MJ-T22201)
1. What are the Logical operators available in Python state with example?
--In Python, logical operators are used to combine conditional statements. The three logical operators
available in Python are:
1. and – Returns True if both statements are true.
2. or – Returns True if at least one of the statements is true.
3. not – Reverses the result, returning False if the statement is true and True if the statement is false.
Example:
x = 10
y=5
# Using 'and' operator
print(x > 5 and y < 10) # True, because both conditions are true
# Using 'or' operator
print(x < 5 or y > 2) # True, because one condition (y > 2) is true
# Using 'not' operator
print(not(x > 5)) # False, because x > 5 is True, and 'not' negates it
These operators are commonly used in conditional statements to control program flow. State with an
example, the role of the following operators: i) is ii) in iii)not in iv)<< v)>>
2. Describe if-elif-else structure with an example. (5)
The if-elif-else structure in Python is used for decision-making, allowing a program to execute different
blocks of code based on conditions.
Structure:
if checks the first condition.
elif (short for "else if") checks additional conditions if the previous ones were false.
else executes when none of the conditions are met.
Example:
num = 15
if num > 20:
print("Number is greater than 20")
elif num > 10:
print("Number is between 11 and 20")
else:
print("Number is 10 or less")
Output:
Number is between 11 and 20
This structure is useful for scenarios where multiple conditions need to be evaluated in sequence.
3. Take a age and find he or she is Child or Teenage or adult or Senior Citizen.(5)
You can determine the age category of a person using Python's if-elif-else structure. Here's an example:
age = int(input("Enter age: "))
if age <= 12:
print("Child")
elif age <= 19:
print("Teenager")
elif age <= 59:
print("Adult")
else:
print("Senior Citizen")
Explanation:
Ages 12 and below are classified as Child.
Ages between 13-19 are Teenagers.
Ages between 20-59 are Adults.
Ages 60 and above fall under Senior Citizen.
Sample Output:
Enter age: 25
Adult
4. Take a year and find leap year or not. (5)
You can determine whether a given year is a leap year using Python's conditional statements. Here's an
example:
year = int(input("Enter a year: "))
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print(f"{year} is a Leap Year")
else:
print(f"{year} is not a Leap Year")
Explanation:
A year is a leap year if:
o It is divisible by 4 AND not divisible by 100 (except when divisible by 400).
This ensures that years like 2000 and 2024 are leap years, while 1900 and 2021 are not.
Sample Output:
Enter a year: 2024
2024 is a Leap Year
5. The marks obtained by a student in 3 different subjects are input through the keyboard. The student
gets a division as per the following rules:
Percentage above or equal to 60----- First division
Percentage between 50 and 59 ------ Second division
Percentage between 40 and 49 ------ Third division
Percentage less than 40 --------------- Fail
Write a program to calculate the division obtained by the student.(5)
Here's a Python program that categorizes a student's division based on their marks:
# Taking marks input from the user
subject1 = float(input("Enter marks for subject 1: "))
subject2 = float(input("Enter marks for subject 2: "))
subject3 = float(input("Enter marks for subject 3: "))
# Calculating percentage
total_marks = subject1 + subject2 + subject3
percentage = (total_marks / 300) * 100 # Assuming each subject is out of 100
# Determining division
if percentage >= 60:
print(f"Percentage: {percentage:.2f}% - First Division")
elif percentage >= 50:
print(f"Percentage: {percentage:.2f}% - Second Division")
elif percentage >= 40:
print(f"Percentage: {percentage:.2f}% - Third Division")
else:
print(f"Percentage: {percentage:.2f}% - Fail")
Explanation:
The user inputs marks for three subjects.
The total percentage is calculated, assuming each subject has a maximum score of 100.
Based on the percentage, the program categorizes the student into their respective division.
Sample Output:
Enter marks for subject 1: 75
Enter marks for subject 2: 68
Enter marks for subject 3: 80
Percentage: 74.33% - First Division
6. Describe range() function with an example.(3)
The range() function in Python is used to generate a sequence of numbers. It is commonly used in loops to
iterate over a range of values.
Syntax:
range(start, stop, step)
start (optional) – The starting number (default is 0).
stop (required) – The number where the sequence ends (not included).
step (optional) – The interval between numbers (default is 1).
Example:
for i in range(1, 10, 2):
print(i)
Output:
1
3
5
7
9
Here, range(1, 10, 2) generates numbers from 1 to 9, increasing by 2 in each step.
7. Write a program to print all odd non prime numbers between 1 to 50.(5)
Here's a Python program that prints all odd non-prime numbers between 1 and 50:
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
# Printing odd non-prime numbers between 1 and 50
print("Odd non-prime numbers between 1 and 50:")
for num in range(1, 51, 2): # Iterating through odd numbers only
if not is_prime(num): # Checking if the number is non-prime
print(num, end=" ")
Explanation:
1. The function is_prime(n) checks whether a number is prime.
2. The loop runs through odd numbers from 1 to 50 using range(1, 51, 2).
3. If a number is not prime, it is printed.
Output:
Odd non-prime numbers between 1 and 50:
1 9 15 21 25 27 33 35 39 45 49
8. Print the following pattern: (5)
1
22
333
4444 for n=4
You can print this pattern using a simple loop in Python. Here's the code:
n = 4 # Number of rows
for i in range(1, n + 1): # Looping from 1 to n
print(str(i) * i) # Printing the number i, repeated i times
Output:
1
22
333
4444
Explanation:
The loop iterates from 1 to n (here, n=4).
str(i) * i repeats the number i, i times to form the pattern.
9. Write a program to calculate the sum of the following series: (5) S= 1/2+2/3+3/4+....+n/(n+1)
[n should be user input]
Here's a Python program to calculate the sum of the given series:
# Taking user input for n
n = int(input("Enter the value of n: "))
# Initializing sum variable
sum_series = 0.0
# Calculating the sum of the series
for i in range(1, n + 1):
sum_series += i / (i + 1)
# Displaying the result
print(f"Sum of the series for n={n} is: {sum_series:.4f}")
Explanation:
The user inputs n, which determines the number of terms in the series.
The program initializes sum_series to store the cumulative sum.
A loop runs from 1 to n, adding i / (i + 1) to the sum.
The final result is displayed with four decimal precision.
Sample Output:
Enter the value of n: 5
Sum of the series for n=5 is: 2.2833
Would you like me to modify this for larger values of n, or optimize the calculations further?
10. Difference between break and continue with example. (5)
In Python, break and continue are control statements used inside loops to alter their execution.
Difference:
break terminates the loop entirely when a specified condition is met.
continue skips the current iteration and moves to the next loop cycle without exiting the loop.
Example:
# Using 'break' - loop terminates when num == 5
for num in range(1, 10):
if num == 5:
break
print(num, end=" ")
print("\nLoop terminated with break.")
# Using 'continue' - loop skips when num == 5
for num in range(1, 10):
if num == 5:
continue
print(num, end=" ")
print("\nLoop continued without printing 5.")
Output:
1234
Loop terminated with break.
12346789
Loop continued without printing 5.
Explanation:
break stops the loop once num == 5, preventing further execution.
continue skips printing 5 but continues looping.
11. Define a function which will take principal amount, time in years and rate of interest in percentage as
input and calculate the simple interest. All the three arguments have default values – 1000 (principal
amount), 5 (time in years) and 10 (rate of interest in percentage). Call the function from main module
with all possible ways and calculate the simple interest each time. (5)
Python Code:
# Function to calculate simple interest
def simple_interest(principal=1000, time=5, rate=10):
return (principal * time * rate) / 100
# Calling the function in all possible ways
if _ _name_ _ == "_ _main_ _":
# 1. Using default values
print("Simple Interest (default values):", simple_interest())
# 2. Providing all arguments explicitly
print("Simple Interest (custom values):", simple_interest(2000, 3, 8))
# 3. Using only principal amount, default time and rate
print("Simple Interest (custom principal):", simple_interest(5000))
# 4. Providing principal and time, default rate
print("Simple Interest (custom principal & time):", simple_interest(3000, 4))
# 5. Providing principal and rate, default time
print("Simple Interest (custom principal & rate):", simple_interest(1500, rate=12))
Explanation:
The function simple_interest() has default values for principal (1000), time (5 years), and rate (10%).
When calling the function, different variations are used:
1. Without arguments, using all default values.
2. Explicitly passing all arguments.
3. Overriding only the principal.
4. Overriding principal and time.
5. Overriding principal and rate.
This ensures that the function is tested with multiple scenarios while taking advantage of default
parameters.
12. Define a function which will calculate factorial of a number and call the function from main module
with a value taken from user.(5)
Python Code:
# Function to calculate factorial
def factorial(n):
if n < 0:
return "Factorial is not defined for negative numbers."
elif n == 0 or n == 1:
return 1
else:
result = 1
for i in range(2, n + 1):
result *= i
return result
# Main module to take input from user and call the function
if __name__ == "__main__":
num = int(input("Enter a number to calculate its factorial: "))
print(f"Factorial of {num} is: {factorial(num)}")
Explanation:
The factorial() function calculates the factorial of a number using a loop.
Handles special cases:
o If n < 0, returns an error message.
o If n == 0 or n == 1, returns 1 since 0! = 1! = 1.
o Otherwise, it iterates from 2 to n, multiplying the values to get the factorial.
The user inputs a number, and the function is called to compute the factorial.
13. Define a function which will accept name of a student and a set of sports that he/she likes and this
function will display the student name and his/her favorite sports. Use variable length argument in the
function parameter so that different student can have different number of favorite sports. (5)
Here’s a Python function that takes a student's name and a variable-length list of sports they like:
Python Code:
# Function to display student name and their favorite sports
def favorite_sports(name, *sports):
print(f"Student Name: {name}")
if sports:
print("Favorite Sports:", ", ".join(sports))
else:
print("No favorite sports specified.")
# Calling the function with different numbers of sports
if __name__ == "__main__":
favorite_sports("Alice", "Basketball", "Tennis")
favorite_sports("Bob", "Cricket")
favorite_sports("Charlie")
favorite_sports("Diana", "Football", "Badminton", "Swimming")
Explanation:
The function favorite_sports() accepts a student's name (name) and a variable-length argument (*sports).
The *sports parameter allows passing any number of sports.
If sports are provided, they are printed; otherwise, a message indicates that no favorite sports were
specified.
The function is tested with different students having varying numbers of sports preferences.
Let me know if you'd like any modifications! 🚀
14. What is function? What is the advantage and disadvantage of using function? (2+2+2)
Function in Python
A function is a reusable block of code that performs a specific task. It helps in organizing code into
smaller, manageable sections. In Python, functions are defined using the def keyword.
Advantages of Using Functions
1. Code Reusability – Functions allow you to write code once and use it multiple times, reducing
duplication.
2. Modularity – They break complex problems into smaller parts, making the code more organized and
easier to understand.
Disadvantages of Using Functions
1. Memory Overhead – Defining too many functions may increase memory usage, especially in recursive
function calls.
2. Debugging Complexity – If functions depend on multiple variables or other functions, debugging can
become tricky.
15. Using lambda function to check whether a number is Positive, negative or zero.(3)
You can use a lambda function in Python to check whether a number is positive, negative, or zero like
this:
Python Code:
# Lambda function to check number status
check_number = lambda x: "Positive" if x > 0 else ("Negative" if x < 0 else "Zero")
# Testing the lambda function
num = int(input("Enter a number: "))
print(f"The number {num} is:", check_number(num))
Explanation:
A lambda function is used to check the number.
It returns:
o "Positive" if the number is greater than 0.
o "Negative" if the number is less than 0.
o "Zero" if the number is equal to 0.
The user inputs a number, and the lambda function evaluates it.
16. Using lambda function to check whether the number is even or odd(3)
Here’s how you can use a lambda function to check whether a number is even or odd:
Python Code:
# Lambda function to check even or odd
even_or_odd = lambda x: "Even" if x % 2 == 0 else "Odd"
# Taking user input
num = int(input("Enter a number: "))
print(f"The number {num} is:", even_or_odd(num))
Explanation:
The lambda function takes a number x as input.
It checks if x % 2 == 0:
o If true, it returns "Even".
o Else, it returns "Odd".
The user inputs a number, and the lambda function evaluates it.
17. What is the role of return and def keyword with respect to function? (2)
Role of def and return in Python Functions
1. def Keyword:
o Used to define a function in Python.
o It allows you to create reusable blocks of code that can be executed when called.
Example:
def greet(name):
print(f"Hello, {name}!")
2. return Keyword:
o Used inside a function to return a value to the caller.
o It allows functions to send computed results back to the program.
Example:
def square(num):
return num * num
result = square(4)
print(result) # Output: 16
18. Define recursion. Differentiate it with iteration. (2+3)
Definition of Recursion:
Recursion is a technique in programming where a function calls itself to solve smaller instances of a
problem until a base condition is met. It helps in breaking down complex problems into simpler sub-
problems.
Difference Between Recursion and Iteration:
Feature Recursion Iteration
Definition Function calls itself Uses loops (for, while)
Termination Stops when base case is met Stops when loop condition becomes false
Memory Usage Higher (due to function call stack) Lower (uses simple loop control)
Performance Can be slower for deep recursion Generally faster
Example Factorial using recursion Factorial using loop
19. Write a python program to print Fibonacci series using recursion(5)
Here's a Python program to print the Fibonacci series using recursion:
Python Code:
# Function to generate Fibonacci sequence using recursion
def fibonacci(n):
if n <= 0:
return "Enter a positive integer."
elif n == 1:
return [0]
elif n == 2:
return [0, 1]
else:
seq = fibonacci(n - 1) # Recursively generate sequence
[Link](seq[-1] + seq[-2]) # Add next Fibonacci number
return seq
# Taking user input
num = int(input("Enter the number of terms for Fibonacci series: "))
print("Fibonacci Series:", fibonacci(num))
Explanation:
Base Cases:
o If n <= 0, an error message is returned.
o If n == 1, the sequence [0] is returned.
o If n == 2, the sequence [0, 1] is returned.
Recursive Case:
o Calls fibonacci(n-1) to generate the sequence for (n-1) terms.
o Appends the sum of the last two numbers (seq[-1] + seq[-2]).
User Input: The number of terms is taken dynamically.
20. Write a python program to print Factorial using recursion(5)
Here’s a Python program to calculate the factorial of a number using recursion:
Python Code:
# Function to calculate factorial using recursion
def factorial(n):
if n < 0:
return "Factorial is not defined for negative numbers."
elif n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1) # Recursive call
# Taking user input
num = int(input("Enter a number to calculate its factorial: "))
print(f"Factorial of {num} is: {factorial(num)}")
Explanation:
Base Case: If n is 0 or 1, the function returns 1.
Recursive Case: The function calls itself (factorial(n-1)) while multiplying by n to compute the
factorial.
User Input: The program takes an integer from the user and calculates its factorial.