0% found this document useful (0 votes)
1 views

Fundamental algorithm

The document provides a comprehensive overview of various Python programming concepts, including algorithms for list operations, eligibility checks, password validation, and Fibonacci series generation. It discusses control flow statements like if-else, loops, and transfer statements (break, continue, return) with example programs. Additionally, it covers variable swapping techniques and the use of iteration statements in Python.

Uploaded by

mishthijaiswal37
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)
1 views

Fundamental algorithm

The document provides a comprehensive overview of various Python programming concepts, including algorithms for list operations, eligibility checks, password validation, and Fibonacci series generation. It discusses control flow statements like if-else, loops, and transfer statements (break, continue, return) with example programs. Additionally, it covers variable swapping techniques and the use of iteration statements in Python.

Uploaded by

mishthijaiswal37
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
You are on page 1/ 26

MODULE 3- FUNDAMENTAL ALGORITHM

1. Design a Python program to handle append and search operations in a list.


The search operation should be performed sequentially, checking each element
until a match is found or the end of the list is reached.
l = []
def add_in_list():
n = int(input("Enter the value to put in list: "))
l.append(n)
print("The list with the added value: ", l)
def search():
a = int(input("Enter the element you want to search:"))
found = False
for i in range(0, len(l)):
if l[i] == a:
print("The element is found in the list at index", i)
found = True
break
if not found:
print("The element is not found!")
start = input("Do you want to start (y/n): ")
while start.lower() == 'y':
choice = int(input("What do you wish to do? 1. add element 2.
search element: "))
if choice == 1:
add_in_list()
elif choice == 2:
search()
else:
print("Incorrect choice")
2. Write a Python program that determines the eligibility of a person to in an
entrance exam with marks.
print("ELIGIBILITY CRITERIA")
mark = int(input("Enter your marks: "))
if mark<40:
print("You are not eligible as your marks is below 40.")
else:
print("You are Eligible. Congratulations!")
3. Write a Program to find a count of Odd and Even numbers in List with integer
values
odd = 0
even = 0
l = []
num = int(input("How many elements you want in the list: "))
for i in range(0,num):
a = int(input("Enter the number: "))
l.append(a)
print("The list formed is: ",l)
for i in range(0,len(l)):
if l[i]%2==0:
even +=1
else:
odd +=1
print("Total number of even elements: ", even)
print("Total number of odd elements: ", odd)
4. Analyze the given password validation process and explain how the
conditions ensure the security of a password. Write a Python program that
checks following conditions:
1. Contain at least 1 letter between a and z 2. Contain at least 1 number
between 0 and 9 3. Contain at least 1 letter between A and Z 4. Contain at least
1 character from $, #, @ 5. Minimum length of password: 6 6. Maximum length
of password: 12
If all of these conditions satisfied, return “Valid password” or else “Invalid
password

The password validation conditions ensure a strong password by addressing the


following aspects:

1.​ Inclusion of lowercase letters (a-z): Ensures the password isn't entirely
numeric or uppercase.
2.​ Inclusion of digits (0-9): Adds complexity, making it harder for attackers to
guess using simple dictionary attacks.
3.​ Inclusion of uppercase letters (A-Z): Enhances complexity and resists
brute-force attacks more effectively.
4.​ Inclusion of special characters ($, #, @): Makes the password resistant to
common password cracking techniques by adding non-alphanumeric
characters.
5.​ Length restrictions (6-12 characters): Ensures the password isn't too short
(prone to brute force) or excessively long (unnecessary complexity).

print("PASSWORD VALIDATION")
passwd = input("Enter your password: ")
#Conditions
if len(passwd) < 12 and len(passwd) > 6:
print("VALID PASSWORD IN TERMS OF LENGTH")
else:
print("INVALID PASSWORD IN TERMS OF LENGTH")
special = "$#@"
has_lower = False
has_upper = False
has_digits = False
has_special = False
for char in passwd:
if char.islower():
has_lower = True
elif char.isupper():
has_upper = True
elif char.isdigit():
has_digit = True
elif char in special:
has_special = True
if has_lower and has_upper and has_digit and has_special:
print("VALID PASSWORD IN TERMS OF CHARACTERS")
else:
print("INVALID PASSWORD IN TERMS OF CHARACTERS")
5. Examine the role of continue and break statements in controlling program
flow. Discuss how these statements can alter the behaviour of loops in different
scenarios. Then, write a Python program that checks whether a number is
prime, prompting the user for input.

●​ continue Statement
○​ The continue statement is used to skip the current iteration of the
loop and proceed directly to the next iteration.
○​ Effect on Loop Behavior:
■​ When continue is encountered, the remaining code in the
current iteration is not executed.
■​ The loop jumps back to evaluate its condition and, if true,
proceeds to the next iteration.
○​ Common Use Cases:
■​ Skipping unwanted iterations based on a condition.
■​ Filtering out specific values or scenarios in a loop
●​ break Statement
○​ The break statement is used to terminate the loop entirely,
regardless of the loop condition.
○​ Effect on Loop Behavior:
■​ When a break is encountered, the loop stops execution
immediately.
■​ The program flow continues with the first statement following
the loop.
○​ Common Use Cases:
■​ Exiting a loop early when a condition is met.
■​ Preventing unnecessary iterations when the desired result is
already achieved.

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

for i in range(2,num-1):

if num%i == 0:

print("The number is not prime")

break

else:

print("The number is prime")

break

6. Write a function to generate the Fibonacci series using iteration and


recursion. Compare the recursive approach with the iterative approach
def fibonacci_iterative(n):
fib_series = []
a, b = 0, 1
for _ in range(n):
fib_series.append(a)
a, b = b, a + b
return fib_series
def fibonacci_recursive(n):
if n <= 0:
return []
elif n == 1:
return [0]
elif n == 2:
return [0, 1]
else:
fib_series = fibonacci_recursive(n - 1)
fib_series.append(fib_series[-1] + fib_series[-2])
return fib_series
n = 10
print("Fibonacci Series (Iterative):", fibonacci_iterative(n))
print("Fibonacci Series (Recursive):", fibonacci_recursive(n))

7. Write a detailed note on Python conditional statements with example


programs

●​ if Statement
1.​ The if statement allows you to test a condition and execute a block
of code if the condition is true.
2.​ Example:

age = 18

if age >= 18:

print("You are eligible to vote.")

●​ if-else Statement
1.​ The if-else statement is used when you have two possible
outcomes. If the condition is true, one block of code is executed;
otherwise, another block is executed.
2.​ Example:

age = 16

if age >= 18:

print("You are eligible to vote.")

else:

print("You are not eligible to vote.")


●​ if-elif-else Statement
1.​ The if-elif-else statement allows you to test multiple conditions.
It checks conditions sequentially, executing the code block of the
first true condition. If no conditions are true, the else block is
executed.
2.​ Example:

marks = 75

if marks >= 90:

print("Grade: A")

elif marks >= 75:

print("Grade: B")

elif marks >= 60:

print("Grade: C")

else:

print("Grade: D")

●​ Nested if Statements
1.​ A nested if statement occurs when one if statement is placed inside
another. This is useful when you need to check multiple conditions
that depend on the outcome of a previous condition.
2.​ Example:

age = 25

income = 30000

if age >= 18:

if income >= 20000:

print("Eligible for loan")

else:

print("Income too low for loan")

else:
print("Not eligible for loan")

●​ Short-circuit Evaluation in Conditional Statements


1.​ In Python, logical operators (and, or) exhibit short-circuit
evaluation, meaning they stop evaluating further once the result is
determined.
2.​ and: If the first condition is False, Python won't evaluate the second
condition because the result is already False.
3.​ or: If the first condition is True, Python won't evaluate the second
condition because the result is already True.
4.​ Example:

x = 5

y = 10

if x > 3 and y < 15:

print("Both conditions are true.")

a = 5

b = 2

if a > 10 or b > 1:

print("At least one condition is true.")

8. Write a Python program to exchange the values of two variables: i) With a


temporary variable ii) Without a temporary variable Explain the code along
with its output
Using temporary variable
a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))
temp = 0
temp = a
a = b
b = temp
print("New first number after swapping:", a)
print("New second number after swapping:", b)
Without using temporary variable
a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))
a = a + b
b = a - b
a = a - b
print("New first number after swapping:", a)
print("New second number after swapping:", b)
9. Discuss iteration statements (loops) in Python with example program

●​ for Loop
1.​ The for loop is used to iterate over a sequence (e.g., a list, tuple,
string, or range) or any iterable object. It executes the loop body for
each element in the sequence.
2.​ Example:

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:

print(fruit)

●​ while Loop
1.​ The while loop executes a block of code repeatedly as long as the
specified condition is True.
2.​ Example:

count = 5

while count > 0:

print(count)

count -= 1

●​ Loop Control Statements

1. break:

❖​ The break statement is used to terminate the loop prematurely.


❖​ Example:

for i in range(1, 10):

if i == 5:

break

print(i)
2. continue:

❖​ The continue statement is used to skip the rest of the current


iteration and proceed to the next iteration
❖​ Example:

for i in range(1, 10):

if i % 2 == 0:

continue

print(i)

3. pass:

❖​ The pass statement does nothing. It’s a placeholder for code that is yet to be
written.
❖​ Example:

for i in range(5):

if i == 3:

pass # Placeholder

else:

print(i)

●​ Nested Loops
1.​ A loop inside another loop is called a nested loop. Both for and while loops
can be nested.
2.​ Example:

for i in range(1, 4): # Outer loop

for j in range(1, 4): # Inner loop

print(f"i = {i}, j = {j}")

●​ Infinite Loops
1.​ An infinite loop runs indefinitely if the condition never becomes False. Use it
with caution.
2.​ Example:

while True:
user_input = input("Enter 'exit' to quit: ")

if user_input.lower() == "exit":

break

10. Identify a Python program that asks the user to input a number n. The
program should generate and display the Fibonacci sequence up to the n-th
term. Ensure the program can handle edge cases, such as when the user enters
a number less than or equal to 0
def fibonacci(n):
# Handle edge cases
if n <= 0:
return "Please enter a number greater than 0."
elif n == 1:
return [0]
elif n == 2:
return [0, 1]
# Generate Fibonacci sequence for n > 2
fib_sequence = [0, 1]
for i in range(2, n):
next_term = fib_sequence[i - 1] + fib_sequence[i - 2]
fib_sequence.append(next_term)
return fib_sequence
n = int(input("Enter a number n: "))
result = fibonacci(n)
if isinstance(result, list):
print("Fibonacci sequence up to the", n, "th term:", result)
else:
print(result)
11. Analyse a Python program that iterates through a list of integers and
performs the following actions using iteration statements: Use a for loop to
print each number. Use a while loop to print numbers until a specific condition
is met Use break to exit the loop when a specific number (e.g., 5) is
encountered. Use continue to skip printing even numbers. Use pass to handle a
specific case where you don't want to perform any action.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# 1. Use a for loop to print each number
print("Using for loop:")
for num in numbers:
print(num)
# 2. Use a while loop to print numbers until a specific condition is
met (e.g., until number 6 is encountered)
print("\nUsing while loop (printing until 6):")
i = 0
while i < len(numbers):
print(numbers[i])
if numbers[i] == 6:
break
i += 1
# 3. Use break to exit the loop when a specific number (5) is
encountered
print("\nUsing break (exit at number 5):")
for num in numbers:
if num == 5:
break
print(num)
# 4. Use continue to skip printing even numbers
print("\nUsing continue (skip even numbers):")
for num in numbers:
if num % 2 == 0:
continue
print(num)
# 5. Use pass to handle a case where no action is performed
print("\nUsing pass (skip number 3 but don't print anything):")
for num in numbers:
if num == 3:
pass
else:
print(num)
12. Develop a Python program to swap the values of two variables using
arithmetic operations instead of a temporary third variable
a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))
a = a + b
b = a - b
a = a - b
print("New first number after swapping:", a)
print("New second number after swapping:", b)
13. What are transfer statements in Python? Explain their purpose, types, and
how they are used in control flow with appropriate examples for each type.

Transfer statements in Python are used to control the flow of execution in a


program. They allow the program to skip parts of code, jump to different parts, or
exit from loops or functions. These statements are essential for implementing
conditional logic, looping, and handling exceptional situations.
Types of Transfer Statements:

1.​ break Statement


a.​ The break statement is used to terminate the current loop
prematurely. It exits the loop regardless of the loop's condition and
moves the control to the next statement after the loop.
b.​ Example:

for i in range(1, 10):

if i == 5:

break # Exit the loop when i equals 5

print(i)

2.​ continue Statement


a.​ The continue statement is used to skip the current iteration of a loop
and move to the next iteration. It doesn't terminate the loop but skips
the remaining code for the current iteration.
b.​ Example:

for i in range(1, 10):

if i % 2 == 0:

continue # Skip even numbers

print(i)

3.​ return Statement


a.​ The return statement is used inside a function to return a value and
exit the function. Once a return statement is executed, the function is
terminated, and the control is returned to the point where the function
was called.
b.​ Example:

def add_numbers(a, b):

return a + b

result = add_numbers(5, 3)

print(result)

4.​ pass Statement


a.​ The pass statement is a placeholder that does nothing. It is often used
in places where code is syntactically required but you don't want to
implement any action. It allows the program to continue without any
error.
b.​ Example:

for i in range(1, 5):

if i == 3:

pass # Do nothing when i equals 3

else:

print(i)

Purpose of Transfer Statements in Control Flow:

●​ break allows for early termination of loops, which is helpful when a condition
is met and further iteration is unnecessary.
●​ continue allows skipping over specific iterations in a loop based on
conditions, which can optimize performance or avoid unwanted
computations.
●​ return is used to exit a function immediately, returning a value to the calling
point.
●​ pass is useful as a placeholder in situations where code structure requires a
statement, but no action is needed.

14. Write a program to convert a decimal number to binary, octal, or


hexadecimal without using inbuilt function?
# Function to convert decimal to binary
def decimal_to_binary(decimal):
binary = ''
while decimal > 0:
remainder = decimal % 2
binary = str(remainder) + binary
decimal = decimal // 2
return binary if binary else '0'
# Function to convert decimal to octal
def decimal_to_octal(decimal):
octal = ''
while decimal > 0:
remainder = decimal % 8
octal = str(remainder) + octal
decimal = decimal // 8
return octal if octal else '0'
# Function to convert decimal to hexadecimal
def decimal_to_hexadecimal(decimal):
hex_digits = '0123456789ABCDEF' # Hexadecimal digits
hexadecimal = ''
while decimal > 0:
remainder = decimal % 16
hexadecimal = hex_digits[remainder] + hexadecimal
decimal = decimal // 16
return hexadecimal if hexadecimal else '0'
decimal_number = int(input("Enter a decimal number: "))
binary = decimal_to_binary(decimal_number)
octal = decimal_to_octal(decimal_number)
hexadecimal = decimal_to_hexadecimal(decimal_number)
print(f"Binary: {binary}")
print(f"Octal: {octal}")
print(f"Hexadecimal: {hexadecimal}")
15. Write a python program to reverse the given input. Sample Input: VIT
Bhopal 2024 Sample Output: 4202 lapohB TIV
SAME AS ANSWER 30
16. Write a program that accepts a sentence and calculates the number of
letters and digits. Suppose the following input is supplied to the program: "Hello
world! 123" Then, the output should be: "LETTERS 10 DIGITS 3"
a = input("Enter the string: ")
digit = 0
letter = 0
l = []
for i in range(0,len(a)):
l.append(a[i])
for i in l:
if i.isdigit():
digit += 1
elif i.isalpha():
letter +=1
print("Total number of digits: ", digit)
print("Total number of letters: ", letter)
17. Illustrate the different types of control flow statements in Python with an
example.
Conditional statements (if , elif, else), Looping Statements (for, while), Transfer
Statements (break, continue, pass), Function Return Statement (return
18. Write an algorithm to calculate the factorial of a number and implement it
in Python using both iterative and recursive approaches.
Algorithm:

1.​ Input: A non-negative integer n.


2.​ Step 1 (Iterative Approach):
○​ Initialize a variable result to 1.
○​ Loop through numbers from 1 to n and multiply the result by each
number.
○​ Return result as the factorial of n.
3.​ Step 2 (Recursive Approach):
○​ If n is 0 or 1, return 1 (base case).
○​ Otherwise, recursively call the factorial function for n-1 and multiply
it by n.
4.​ Output: The factorial of n.

# Iterative approach to calculate factorial


def factorial_iterative(n):
result = 1
for i in range(1, n + 1):
result *= i
return result
# Recursive approach to calculate factorial
def factorial_recursive(n):
# Base case: factorial of 0 or 1 is 1
if n == 0 or n == 1:
return 1
# Recursive case: n * factorial of (n-1)
else:
return n * factorial_recursive(n - 1)
19. Write a Python program that demonstrates the use of if-else, nested if-else,
and elif statements. Write the Syntax and draw the flowcharts of if-else, nested
if-else, elif statements Use if-else to check whether the number is positive or
negative. Use elif to check if the number is divisible by 3, 5, or both Use nested
if-else to check if the number is odd or even, and if it is greater than 100.
num = int(input("Enter a number: "))
# 1. Using if-else to check if the number is positive or negative
if num > 0:
print(f"{num} is positive.")
else:
print(f"{num} is negative.")
# 2. Using elif to check if the number is divisible by 3, 5, or both
if num % 3 == 0 and num % 5 == 0:
print(f"{num} is divisible by both 3 and 5.")
elif num % 3 == 0:
print(f"{num} is divisible by 3.")
elif num % 5 == 0:
print(f"{num} is divisible by 5.")
else:
print(f"{num} is not divisible by 3 or 5.")
# 3. Using nested if-else to check if the number is odd/even and
greater than 100
if num > 100:
if num % 2 == 0:
print(f"{num} is even and greater than 100.")
else:
print(f"{num} is odd and greater than 100.")
else:
if num % 2 == 0:
print(f"{num} is even and not greater than 100.")
else:
print(f"{num} is odd and not greater than 100.")
20. (a) Write a Python program that uses a while loop. The program should
print all the even numbers from 1 to n and print the total count of even
numbers from 1 to n. Note: The program should stop asking for input when the
user enters the number 0.
while True:
n = int(input("Enter a number (enter 0 to stop): "))
if n == 0:
print("Exiting the program.")
break
count = 0
print(f"Even numbers from 1 to {n}:")
for i in range(2, n + 1, 2):
print(i, end=" ")
count += 1
print(f"\nTotal count of even numbers from 1 to {n}: {count}")
(b) Write a Python program using a while loop that prints all the numbers from
1 to n (inclusive) and calculates their sum.
n = int(input("Enter a positive integer (n): "))
current_number = 1
total_sum = 0
while current_number <= n:
print(current_number)
total_sum += current_number
current_number += 1
print("Sum of numbers from 1 to", n, "is:", total_sum)
(c) Write a Python program using a for loop that prints all the numbers from 1
to n (inclusive) and calculates their sum.
n = int(input("Enter a positive integer (n): "))
total_sum = 0
for i in range(1, n + 1):
print(i)
total_sum += i
print("Sum of numbers from 1 to", n, "is:", total_sum)
(d) Compare the above two implementations. Explain the advantages of using
the for loop in this case

The for loop is typically a better option in this scenario because:

1.​ Simplicity: The for loop is more concise and readable, especially when the
number of iterations is known in advance (from 1 to n). You don’t need to
manually increment the counter or check the condition.
2.​ Automatic Iteration: The range() function automatically generates the
sequence of numbers, removing the need for manual control over the
iteration (like updating the counter in a while loop).
3.​ Less Error-Prone: Since the for loop handles the iteration automatically,
there’s less chance of errors like forgetting to increment the counter or
forgetting to break the loop when the condition is met.
4.​ Efficiency: The for loop, especially with range(), is optimized for cases
where the number of iterations is predetermined.

21. Debug the code


def check_number(num):
if num > 0
print("The number is positive")
elif num < 0:
print("The number is negative")
else:
print("The number is zero")
number = input("Enter a number: ")
check_number(number)
Identify and correct the errors in the code. Ensure that the program works
correctly for all possible inputs Explain what each error is and why it occurs.
CORRECTED CODE-
def check_number(num):
if num > 0 :
print("The number is positive")
elif num < 0:
print("The number is negative")
else:
print("The number is zero")
number =float( input("Enter a number: "))
check_number(number) # No indentation here

Error 1: Expected colon after the if statement which signifies the start of a new
code block.
Error 2: The number variable was initially storing a string input because of input()
function, but a decimal value was intended to be stored. Thus, we needed to add
the float() function before it.
Error 3: There is supposed to be no indentation before calling the function as it
has to be outside the function block to be able to call it.
22. Write the output of the given code and explain the purpose of continue
statement in both the example. (4M)
# First Example
for letter in 'Welcome’:
if letter == 'c’:
continue
print ('Current Letter :', letter)
# Second Example
var = 10
While var> 0:
print('Current variable value :', var)
var = var -1
if var == 5:
continue print ("End!”)
Output of first example:
Current Letter : W
Current Letter : e
Current Letter : l
Current Letter : o
Current Letter : m
Current Letter : e

Output of second example:


Current variable value : 10
Current variable value : 9
Current variable value : 8
Current variable value : 7
Current variable value : 6
Current variable value : 5
Current variable value : 4
Current variable value : 3
Current variable value : 2
Current variable value : 1
End!
Purpose of the continue Statement
1.​ Definition:
○​ The continue statement skips the remaining code in the current
iteration of a loop and moves to the next iteration.
2.​ Purpose in the Examples:
○​ First Example: Skips printing the letter 'c' when encountered.
○​ Second Example: Skips the remaining code when var == 5.
However, in this case, it doesn't visibly affect the output since no
additional code (apart from the decrementation) follows in that
iteration.

23. Create a Python program for an open-air theatre that calculates ticket
prices based on age, vehicle and time of day. Tickets for children (age < 10) are
€6 for two-wheeler and €8 for four wheeler, adults (age >= 10) are €10 for
two-wheeler and €12 for four-wheeler, senior citizens (age >= 60) are €9 for any
vehicle. For evening shows (after 5 PM), there’s an additional €2 surcharge.
print("OPEN AIR THEATRE TICKET PRICING")
print("Kindly give the following data: ")
age = int(input("Enter your age: "))
time = float(input("Enter the time in 24-hour format: "))
vehicle = int(input("Enter the vehicle preference (2/4): "))
surcharge = 2 if time >= 17 else 0
if age < 10:
if vehicle == 2:
price = 6
elif vehicle == 4:
price = 8
else:
print("Invalid Vehicle Preference!")
exit()
elif age >= 10 and age < 60:
if vehicle == 2:
price = 10
elif vehicle == 4:
price = 12
else:
print("Invalid Vehicle Preference!")
exit()
else:
price = 9

# Apply surcharge for evening shows


price += surcharge
print(f"Price of ticket: €{price}")
24. i)Write a python program to read the numbers until -1 is encountered using
while loop and if-else statement. Also count the negatives, positives and zeroes
entered by the user. Calculate the average of positive and negative numbers
entered by the user.
positive_count = 0
negative_count = 0
zero_count = 0
positive_sum = 0
negative_sum = 0
print("Enter numbers. To stop, enter -1.")
while True:
number = int(input("Enter a number: "))
if number == -1:
break
elif number > 0:
positive_count += 1
positive_sum += number
elif number < 0:
negative_count += 1
negative_sum += number
else:
zero_count += 1
positive_avg = positive_sum / positive_count if positive_count > 0 else
0
negative_avg = negative_sum / negative_count if negative_count > 0 else
0
print(f"Positive numbers entered: {positive_count}")
print(f"Negative numbers entered: {negative_count}")
print(f"Zeroes entered: {zero_count}")
print(f"Average of positive numbers: {positive_avg}")
print(f"Average of negative numbers: {negative_avg}")
(ii) Compare the flow of execution of ‘for loop’ and ‘while loop’ statements with
an example.

●​ For Loop:
1.​ A for loop is generally used when the number of iterations is known
or defined. It automatically handles the iteration and termination
based on the given range or iterable.
2.​ Flow of Execution:
a.​ The for loop begins by evaluating the range or iterable
(range(1, 6) in this case).
b.​ It initializes i to 1, executes the body of the loop, then
increments i.
c.​ The loop continues until the value of i exceeds 5.
d.​ No explicit condition checking or updating of i is needed by
the programmer.
●​ While Loop:
1.​ A while loop is used when the number of iterations is not known, and
the loop should continue based on a condition that is checked before
each iteration.
2.​ Flow of Execution:
a.​ The while loop starts by checking the condition (i <= 5).
b.​ If the condition is true, the body of the loop is executed
(printing the value of i).
c.​ The value of i is manually updated after each iteration (i +=
1).
d.​ The loop continues until the condition becomes false.

25. Explain the syntax of the range function. The following for-loop is written to
print the numbers using the range function. Are these loops correct? Justify
your answer

The range() function in Python generates a sequence of numbers, which is often


used in loops.
LOOP 1:
●​ Explanation: range(10) generates numbers from 0 to 9 (10 is excluded).
●​ Output: This loop prints: 0 1 2 3 4 5 6 7 8 9
●​ Correctness: This loop is correct. The syntax and logic align with Python
conventions.
LOOP 2:
●​ Explanation: range(2, 10) generates numbers from 2 to 9. For each i, num
= i + 1 is calculated and printed.
●​ Output: This loop prints: 3 4 5 6 7 8 9 10
●​ Correctness:This loop is correct. The logic properly utilizes range().
LOOP 3:
●​ Explanation: range(1, 3, 15) attempts to generate numbers starting from
1, ending before 3, with a step of 15. Since 15 is larger than the range, only
the start value (1) is included in the sequence.
●​ Output: This loop prints: 1
●​ Correctness: The loop is syntactically correct but contains a logical issue:
○​ The i = i + 1 line inside the loop does not affect the loop variable
i, as the for loop overwrites it in each iteration.
○​ The loop effectively executes only once due to the large step value.
26. Convert the decimal number (90) into binary, octal and hexadecimal format.
decimal_number = 90
binary_representation = bin(decimal_number)[2:]
octal_representation = oct(decimal_number)[2:]
hexadecimal_representation = hex(decimal_number)[2:].upper()
print("Binary representation:", binary_representation)
print("Octal representation:", octal_representation)
print("Hexadecimal representation:", hexadecimal_representation)
27. Write a Python Program to Generate the First n Terms of the Fibonacci
Sequence. Print the sequence in a single line..
first = 0
second = 1
n = int(input("Enter how many digits you want in the series: "))
for i in range (0,n):
print(first, end = " ")
third = first + second
first = second
second = third
28. Write a Python program that takes a two-digit number as input, reverses the
number, and compares it with the original number. If the reversed number is
greater than the input number, find the difference; otherwise, add the two
numbers and print the result.
a = input("Enter the number: ")
l = []
for i in a:
l.append(i)
k = len(l)
b = ''
for j in range(k-1,-1,-1):
b +=l[j]
print("Reversed Number: ", b)
a_num = int(a)
b_num = int(b)
if b_num > a_num:
diff = b_num - a_num
print("The difference of the two numbers: ", diff)
else:
sum = b_num + a_num
print("The sum of the two numbers: ", sum)
29. Discuss the concept of base conversion in programming. Write the steps to
convert a number from decimal to binary manually. How can this be
implemented in Python using built-in functions like bin()?

Base conversion in programming refers to the process of converting a number


from one numeral system (base) to another. The most commonly used bases are:

●​ Base-10 (Decimal): The standard numeral system used in daily life.


●​ Base-2 (Binary): Used in computer systems and digital electronics.
●​ Base-8 (Octal): Less common, but used in specific applications like Unix
permissions.
●​ Base-16 (Hexadecimal): Frequently used in computer programming and
networking (e.g., color codes, memory addresses).

Steps to Convert a Decimal Number to Binary Manually

To convert a decimal number to binary:

1.​ Divide the Decimal Number by 2: Write down the quotient and remainder.
2.​ Record the Remainders: The remainder is either 0 or 1.
3.​ Repeat Division: Continue dividing the quotient by 2 until it becomes 0.
4.​ Write the Binary Representation: The binary representation is the
remainders read from bottom to top.

Implementation in Python Using bin()

Python provides a built-in function, bin(), to convert decimal numbers to binary.

decimal_number = int(input("Enter the decimal number: "))

binary_representation = bin(decimal_number)

binary_representation = binary_representation[2:]

print(f"Binary representation of {decimal_number}:


{binary_representation}")
30. Write a Python program to reverse a string without using built-in functions.
Use a for loop to iterate over the string in reverse and construct the result
manually. Display the original and reversed strings
a = input("Enter the string: ")
print("Original String: ", a)
l = []
for i in a:
l.append(i)
k = len(l)
print("Reversed String: ")
for j in range(k-1,-1,-1):
print(l[j],end='')
31. Explain the different iteration statements in Python (for, while, break,
continue, pass).
SAME AS ANSWER 9
32. Write a Python program to print the following picture.
*
***
*****
*******
*********
*******
*****
***
*
a = int(input("Enter the number of rows you want in your design: "))
for i in range (1,a+1):
print(" " * (a - i), end="")
print("* " *i)
for i in range(a-1, 0, -1):
print(" " * (a - i), end="")
print("* " *i)
33. Create a program that accepts an integer input from the user and:
Exchanges it with a default value.
user_input = int(input("Enter an integer: "))
default_value = 10
user_input, default_value = default_value, user_input
print(f"Exchanged value: {user_input} (default value now is
{default_value})")
Counts up to the number.
user_input = int(input("Enter an integer: "))
print(f"Counting up to {user_input}:")
for i in range(1, user_input + 1):
print(i, end=" ")
print()
Computes the sum and factorial of all numbers up to the input
SUM OF N NUMBER SOMEWHERE IN THE DOCUMENT (KHUD DHUNDH LO :’))
user_input = int(input("Enter an integer: "))
fact = 1
for i in range (1,user_input+1):
fact = fact*i
print("The factorial of the number is ", fact)
34. Explain about various Iterative and control statements with example in
python.
Write for loop, while loop, control statements (if, elif,else, if-else), break,
continue, pass, infinite loop,
35. Write both the Python function to generate the Fibonacci series using
iteration and recursion
SAME AS ANSWER 6
36. Convert the decimal number (989) into binary, octal and hexadecimal
format
decimal_number = 989
binary_representation = bin(decimal_number)[2:]
octal_representation = oct(decimal_number)[2:]
hexadecimal_representation = hex(decimal_number)[2:].upper()
print("Binary representation:", binary_representation)
print("Octal representation:", octal_representation)
print("Hexadecimal representation:", hexadecimal_representation)
37. Write down the algorithm to calculate sum and average of first N natural
numbers and implement the code for the same.
Algorithm:
1.​ START
2.​ Prompt the user to input the number and store it in variable ‘n’.
3.​ Write a function Sum().
a.​ Initialize ‘sum’ as 0
b.​ Run a for loop from 0 to n+1 and add each number one by one in
‘sum’.
c.​ Print ‘sum’
4.​ Write another function Avg().
a.​ Repeat the same steps to find the total of all numbers till n
b.​ Write the formulate ‘avg = sum/n’
c.​ Print ‘avg’
5.​ Print the final output for both sum and average.
6.​ STOP
n = int(input("Enter the number: "))
def Sum():
sum = 0
for i in range(0,n+1):
sum +=i
return sum
def Avg():
sum = 0
for i in range(0,n+1):
sum +=i
avg = sum/n
return avg
print("The sum of", n, "th number: ", Sum())
print("The average of", n, "th number: ", Avg())
38. Explain below given Iteration statements with suitable code:
1. while
2. for
3. break
4. continue
5. pass
SAME AS ANSWER 9
39. Implement the python script to print the below given pattern.
0
10
101
0101
rows = int(input("Enter the number of rows in pattern: "))
for i in range(1, rows + 1):
pattern = ""
for j in range(i):
# Use (i + j) % 2 to alternate between 0 and 1
pattern += str((i + j) % 2)
print(pattern)
40. Write a Python program for a movie theatre that calculates ticket prices
based on age and time of day. Tickets for children (age < 12) are $5, adults (age
>= 12) are $10, and seniors (age >= 60) are $7. For evening shows (after 5 PM),
there’s an additional $2 surcharge
print("MOVIE THEATRE TICKET PRICING")
print("KINDLY FILL THE NECESSARY DATA:")
age = int(input("Enter you age: "))
time= float(input("Enter the time of show in 24 hour format: "))
if time<17.00:
if age<12:
print("Total price: $5")
elif age>=12 or age< 60:
print("Total price: $10")
else:
print("Total price: $7")
else:
if age<12:
print("Total price: $", 5+2)
elif age>=12 or age< 60:
print("Total price: $", 10+2)
else:
print("Total price: $", 7+2)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy