BUDDHA SERIES
(Unit Wise Solved Questions and Answers)
[Link].(CS)
College-Buddha Institute of Technology (AKTU Code-525)
Department of Computer Science
Subject-Python Programming (BCC402)
Faculty Name-Mr. Shashank Kumar Srivastav
Unit-2
1. What is the purpose of the if statement in programming?(AKTU2022-23)
Ans
The if statement in programming serves the fundamental purpose of controlling the flow of
execution based on certain conditions. It allows the program to make decisions, choosing
different paths of execution depending on whether a condition evaluates to true or false.
1. Conditional Execution: The if statement allows a program to execute a block of code only if a
specified condition is true. This enables the program to perform different actions depending on
varying conditions.
2. Branching: It provides branching capability, enabling the program to follow different paths based
on the evaluation of conditions. This is crucial for implementing logic such as branching based
on user input, processing different cases in algorithms, or handling error conditions.
3. Decision Making: By evaluating conditions using if statements, programs can make decisions
dynamically during runtime. This enables flexibility in program behavior, making it adaptable to
different scenarios.
4. Error Handling: If statements are often used for error handling purposes. Programs can check for
error conditions and take appropriate actions, such as displaying error messages, logging errors,
or executing fallback mechanisms.
Overall, the if statement is a fundamental construct in programming languages that empowers
developers to write logic that responds dynamically to different situations and conditions,
thereby enhancing the flexibility and functionality of their programs.
2. [Link] the difference between the if, else, and else if statements. How do you use
conditional logic to control program flow? ?(AKTU2020-21)
Ans
if Statement:
The if statement is used to execute a block of code only if a specified condition is true.
It evaluates the condition inside the parentheses following the if keyword. If the condition
evaluates to true, the code block associated with the if statement is executed. If the condition is
false, the code block is skipped.
It's often used as the starting point for conditional logic, allowing the program to make decisions
based on whether certain conditions are met.
Example:
python
Copy code
x = 10
if x > 5:
print("x is greater than 5")
2. else Statement:
The else statement is used in conjunction with an if statement to execute a block of code when
the if condition is false.
It doesn't have its own condition to evaluate; instead, it provides an alternative block of code to
execute when the preceding if condition is not met.
It's typically used for providing an alternative course of action when the primary condition fails.
Example:
python
Copy code
x=3
if x > 5:
print("x is greater than 5")
else:
print("x is not greater than 5")
3. else if Statement (elif in Python):
The else if statement, often written as elif in Python, allows for the evaluation of multiple
conditions sequentially.
It follows an initial if statement or another else if statement and provides an alternative condition
to check if the preceding condition(s) are false.
It's useful for implementing branching logic where there are multiple possible outcomes based on
different conditions.
Example:
python
Copy code
x = 10
if x > 10:
print("x is greater than 10")
elif x == 10:
print("x is equal to 10")
else:
print("x is less than 10")
Conditional Logic and Program Flow: Conditional logic allows programmers to control the flow
of a program based on various conditions. By using if, else, and else if statements, programmers
can create decision-making structures within their code. Program flow is directed along different
paths depending on the evaluation of these conditions. This enables programs to react
dynamically to different inputs, states, or situations, making them more versatile and capable of
handling diverse scenarios.
3. [Link] do you nest if statements within each other? ?
Ans. Nesting if statements within each other involves placing one if statement (or multiple if-else
statements) inside the code block of another if statement. This allows for more complex
conditional logic where certain conditions need to be checked only if the outer condition is true.
Here's a general syntax for
Here's a breakdown of the process:
1. Start with the outer if statement, followed by a colon : and an indented block of code.
2. Inside the code block of the outer if statement, write another if statement (or multiple if-else
statements) with its own condition and code block.
3. Ensure that the inner if statement is properly indented within the outer if statement's code block.
4. Optionally, include else or elif statements within the inner if statement's code block for handling
alternative conditions.
5. Continue nesting if statements as needed.
Here's a concrete example to illustrate nesting if statements:
python
Copy code
x = 10
y=5
if x > 5:
print("x is greater than 5")
if y > 3:
print("y is greater than 3")
else:
print("y is not greater than 3")
else:
print("x is not greater than 5")
In this example, the inner if statement checks whether the variable y is greater than 3, but it only
does so if the outer if statement's condition (x > 5) is true. The program will execute the
appropriate code blocks based on the evaluation of these nested conditions.
4. What is the purpose of using loops in Python?
Ans- Loops in Python serve several important purposes, making them fundamental constructs in
programming. Here are some key purposes of using loops in Python:
1. Repetition: Loops allow you to execute a block of code repeatedly. Instead of writing the same
code multiple times, you can use loops to iterate over a sequence of elements or perform a task a
specified number of times.
2. Automation: Loops enable automation of repetitive tasks, such as processing items in a list,
iterating over elements in a collection, or performing calculations on a series of values. This can
significantly reduce code redundancy and increase efficiency.
3. Iterating Over Data Structures: Python's loops allow you to iterate over various data
structures, including lists, tuples, sets, dictionaries, and strings. This facilitates data processing
and manipulation, enabling you to access and work with each element in the data structure
sequentially.
4. Dynamic Behavior: Loops provide a way to create dynamic behavior in programs. By
combining loops with conditional statements, you can create algorithms that adapt their behavior
based on changing conditions or input data.
5. Complex Operations: Loops are essential for performing complex operations that involve
iterating, processing, or analyzing large datasets. They allow you to break down complex tasks
into smaller, manageable steps that can be executed iteratively.
6. Control Flow: Loops help control the flow of program execution. They allow you to define the
sequence in which statements are executed, including repeating specific sections of code,
skipping iterations, or exiting the loop prematurely based on certain conditions.
Overall, loops in Python provide a powerful mechanism for automating tasks, iterating over data,
and controlling program flow, making them indispensable for writing efficient and scalable code.
Whether you need to process large datasets, perform repetitive operations, or create dynamic
algorithms, loops offer a flexible and efficient solution.
4. Describe the use of the continue and break statements within loops. ?(AKTU2023-24)
Ans. [Link] Statement:
The continue statement is used to skip the rest of the code inside a loop for the current iteration
and proceed to the next iteration.
It is typically used when certain conditions are met, and you want to skip the remaining code
block for that specific iteration.
3. for i in range(5):
4. if i == 2:
5. continue # Skip iteration when i equals 2
6. print(i
7. [Link] Statement:
The break statement is used to exit the loop prematurely, regardless of the loop's condition.
It is commonly used to terminate the loop when a specific condition is met, preventing further
iterations.
python
Copy code
for i in range(5):
if i == 3:
break # Exit the loop when i equals 3 print(i)
4. else Statement (with loops):
The else statement in loops is executed when the loop completes all iterations without
encountering a break statement.
It is useful for executing code that should only run if the loop completes successfully, without
early termination.
python
Copy code
for i in range(5):
print(i) else:
print("Loop completed successfully")
These statements provide additional control and flexibility within loops, allowing you to handle
various scenarios such as placeholder actions, skipping iterations, early termination, and
executing code after the loop completes. Understanding their usage can greatly enhance your
ability to write efficient and expressive Python code.
5. Write a Python program that prints the squares of numbers from 1 to 10 using a for
loop.
for i in range(1, 11):
print(i*i)
[Link] to get even number in range between 1-20 element.
Ans. for i in range(1, 21):
if i % 2 == 0:
print(i)
[Link] to use indentation and comment line in python with example.
Ans.# This is a comment
for i in range(5):
print(i) # This is also a comment
[Link] to display multiplication table from (1 to 5).
# Define the range of the multiplication table
start = 1
end = 5
# Iterate over each number in the range
for i in range(1, 11): # Multiplication table goes from 1 to 10
# Iterate over each number in the specified range
for j in range(start, end + 1):
# Print the product of i and j with appropriate formatting
print(f"{j} x {i} = {i * j}", end="\t")
print() # Move to the next line after printing all numbers for each value of i
o/p- 1 x 1 = 1 2 x 1 = 2 3x1=3 4x1=4 5x1=5
1x2=2 2x2=4 3x2=6 4x2=8 5 x 2 = 10
1x3=3 2x3=6 3x3=9 4 x 3 = 12 5 x 3 = 15
1x4=4 2x4=8 3 x 4 = 12 4 x 4 = 16 5 x 4 = 20
1x5=5 2 x 5 = 10 3 x 5 = 15 4 x 5 = 20 5 x 5 = 25
1x6=6 2 x 6 = 12 3 x 6 = 18 4 x 6 = 24 5 x 6 = 30
1x7=7 2 x 7 = 14 3 x 7 = 21 4 x 7 = 28 5 x 7 = 35
1x8=8 2 x 8 = 16 3 x 8 = 24 4 x 8 = 32 5 x 8 = 40
1x9=9 2 x 9 = 18 3 x 9 = 27 4 x 9 = 36 5 x 9 = 45
1 x 10 = 10 2 x 10 = 20 3 x 10 = 30 4 x 10 = 40 5 x 10 = 50
8. Display capital letters from A to Z using loop.
Ans.
for char in range(ord('A'), ord('Z') + 1):
print(chr(char))
[Link] to print even number from 0 to 20 and find their Sum.
Ans.
Sum=0
for i in range(1, 21):
if i % 2 == 0:
sum=sum+i
print(i)
print(sum)
10. Explain the operator, operands and expression with example
Ans. Operator: An operator is a symbol that performs an operation on one or more operands.
Operands: Operands are the values or variables that an operator operates on.
Expression: An expression is a combination of operands and operators that can be evaluated to
produce a value.
# Examples
x = 5 # Operand
y = 3 # Operand
z = x + y # Expression (addition operator)
[Link] to prompt a user to enter a day of the week. if the entered day of the week is
between 1 to then display the respective name of the day
# Prompt the user to enter a day of the week
day_number = int(input("Enter a number between 1 and 7: "))
# Check if the entered number is between 1 and 7
if 1 <= day_number <= 7:
# Map the number to the respective day of the week
if day_number == 1:
day_name = "Monday"
elif day_number == 2:
day_name = "Tuesday"
elif day_number == 3:
day_name = "Wednesday"
elif day_number == 4:
day_name = "Thursday"
elif day_number == 5:
day_name = "Friday"
elif day_number == 6:
day_name = "Saturday"
else:
day_name = "Sunday"
# Display the respective day of the week
print("The day of the week is:", day_name)
else:
print("Invalid input! Please enter a number between 1 and 7.")
[Link] to calculate the sum of number from 1 to 20 which are not divisible 2,3 or 5.
Ans.
# Initialize sum to store the total sum of numbers
total_sum = 0
# Iterate through numbers from 1 to 20
for num in range(1, 21):
# Check if the number is not divisible by 2, 3, or 5
if num % 2 != 0 and num % 3 != 0 and num % 5 != 0:
# Add the number to the total sum
total_sum += num
# Display the total sum
print("The sum of numbers from 1 to 20 not divisible by 2, 3, or 5 is:", total_sum)
[Link] to display the pattern of stars given bellow using python programming.
*
**
***
****
*****
Ans.
# Define the number of rows for the pattern
num_rows = 5
# Iterate over each row
for i in range(1, num_rows + 1):
# Print stars for each row
for j in range(i):
print("*", end=" ")
print() # Move to the next line after printing stars for each row