(1) Odd or Even: Write a function called is_odd_or_even(num) that takes an integer as
input and prints whether the number is "Odd" or "Even".
def check(num):
# This function takes an integer input and determines if it is odd
or even.
# Check if the number is divisible by 2
if (num % 2 == 0):
# If the remainder is 0, the number is even
print("Even")
else:
# If the remaind)er is not 0, the number is odd
print("Odd")
# Example
check(5) # Output: Odd
check(8) # Output: Even
Odd
Even
Comment
• The function check takes an integer num as an argument.
• It uses the modulus operator % to check if num is divisible by 2.
• If num % 2 equals 0, num is even, so it prints "Even".
• Otherwise, num is odd, so it prints"Odd".
(2) Grade Calculator: Write a program that takes a student's score (0-100) as input
and prints their grade based on the following scale:
90-100: A
80-89: B
70-79: C
60-69: D
Below 60: F
def grade_calculator(score):
# This function takes a student's score (0-100) and prints their
grade based on the specified scale.
# Check the score and determine the grade
if 90 <= score <= 100:
grade = "A"
elif 80 <= score <= 89:
grade = "B"
elif 70 <= score <= 79:
grade = "C"
elif 60 <= score <= 69:
grade = "D"
elif 0 <= score < 60:
grade = "F"
else:
# If the score is out of bounds (not between 0 and 100)
grade = "Invalid score"
# Print the grade
print(f"The grade for a score of {score} is: {grade}")
# Example
grade_calculator(95) # Output: A
grade_calculator(85) # Output: B
grade_calculator(75) # Output: C
grade_calculator(65) # Output: D
grade_calculator(55) # Output: F
grade_calculator(105) # Output: Invalid score
The grade for a score of 95 is: A
The grade for a score of 85 is: B
The grade for a score of 75 is: C
The grade for a score of 65 is: D
The grade for a score of 55 is: F
The grade for a score of 105 is: Invalid score
Comment
• The grade_calculator function takes a single parameter, score, which represents the
student's score.
• The if and elif statements check where the score falls within the specified ranges and
assign the appropriate grade.
• If the score is not within the range of 0-100, it prints "Invalid score" to handle any
erroneous inputs.
• Finally, the grade is printed using formatted strings to clearly indicate the result.
(3) Fizz Buzz: Write a program that prints numbers from 1 to 100. For multiples of 3.
print "Fizz" instead of the number, for multiples of 5. print "Buzz". For numbers that
are multiples of both 3 and 5, print "Fizz Buzz".
def fizz_buzz():
# This function prints numbers from 1 to 100.
# For multiples of 3, it prints "Fizz" instead of the number.
# For multiples of 5, it prints "Buzz" instead of the number.
# For multiples of both 3 and 5, it prints "Fizz Buzz".
for num in range(1, 101):
# Check if the number is a multiple of both 3 and 5
if num % 3 == 0 and num % 5 == 0:
print("Fizz Buzz")
# Check if the number is a multiple of 3
elif num % 3 == 0:
print("Fizz")
# Check if the number is a multiple of 5
elif num % 5 == 0:
print("Buzz")
else:
# If the number is not a multiple of 3 or 5, print the
number
print(num)
# Enter the function to see the output
fizz_buzz()
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
Fizz Buzz
16
17
Fizz
19
Buzz
Fizz
22
23
Fizz
Buzz
26
Fizz
28
29
Fizz Buzz
31
32
Fizz
34
Buzz
Fizz
37
38
Fizz
Buzz
41
Fizz
43
44
Fizz Buzz
46
47
Fizz
49
Buzz
Fizz
52
53
Fizz
Buzz
56
Fizz
58
59
Fizz Buzz
61
62
Fizz
64
Buzz
Fizz
67
68
Fizz
Buzz
71
Fizz
73
74
Fizz Buzz
76
77
Fizz
79
Buzz
Fizz
82
83
Fizz
Buzz
86
Fizz
88
89
Fizz Buzz
91
92
Fizz
94
Buzz
Fizz
97
98
Fizz
Buzz
Comment
• The fizz_buzz function prints numbers from 1 to 100.
• It uses a for loop to iterate through each number in this range.
• For each number, it first checks if it's a multiple of both 3 and 5 (num % 3 == 0 and num
% 5 == 0). If so, it prints "Fizz Buzz".
• If the number is only a multiple of 3 (num % 3 == 0), it prints "Fizz".
• If the number is only a multiple of 5 (num % 5 == 0), it prints "Buzz".
• If none of the above conditions are met, it simply prints the number itself.
(4) Factorial Calculation: Write a function called factorial(n) that takes a non-
negative integer and returns its factorial. Use a loop to calculate the factorial.
def factorial(n):
# This function takes a non-negative integer n and returns its
factorial.
# The factorial of a non-negative integer n is the product of all
positive integers less than or equal to n.
# Initialize the result to 1 (the factorial of 0 is 1)
result = 1
# Loop from 1 to n (inclusive)
for i in range(1, n + 1):
# Multiply the current result by the current number i
result *= i
# Return the final factorial value
return result
# Example
print(factorial(5)) # Output: 120
print(factorial(0)) # Output: 1
120
1
Comment
• The factorial function takes one parameter, n, which is the non-negative integer for
which we want to calculate the factorial.
• We initialize a variable result to 1, as the factorial of 0 is 1, and it serves as the identity for
multiplication.
• We use a for loop to iterate over the range from 1 to n (inclusive). For each iteration, we
multiply the current result by the loop variable i.
• Finally, we return the value of result, which now contains the factorial of n.
(5) Sum of Natural Numbers: Write a program that asks the user for a positive
integer n and calculates the sum of all natural numbers up to n using a loop.
# Function to calculate the sum of natural numbers up to n
def sum_of_natural_numbers():
# This function asks the user for a positive integer n and
calculates the sum of all natural numbers up to n.
# enter a positive integer
n = int(input("Enter a positive integer: "))
# Initialize the sum to 0
total_sum = 0
# Loop from 1 to n
for i in range(1, n + 1):
# Add the current number i to the total sum
total_sum =total_sum+ i
# Print the final sum
print(f"The sum of all natural numbers up to {n} is: {total_sum}")
# Enter the function to see the output
sum_of_natural_numbers()
Enter a positive integer: 5
The sum of all natural numbers up to 5 is: 15
Comment
• Function Definition: The function sum_of_natural_numbers() is defined to encapsulate
the entire process.
• User Input: The program asks the user to enter a positive integer n using the input()
function and converts it to an integer with int().
• Initialization: A variable total_sum is initialized to 0. This variable will accumulate the
sum of natural numbers.
• Loop: A for loop is used to iterate from 1 to n (inclusive). During each iteration, the loop
variable i is added to total_sum.
• Output: Finally, the program prints the result using an f-string to format the message.
(6) Prime Number Checker: Write a function called is_prime(num) that takes an
integer and returns True if the number is prime and False otherwise.
def is_prime(num):
# This function takes an integer 'num' and returns True if the
number is prime, and False otherwise.
# A prime number is a number greater than 1 that has no positive
divisors other than 1 and itself.
# Check if the number is less than or equal to 1 (not prime)
if num <= 1:
return False
# Check if the number is 2 or 3 (both are prime)
if num <= 3:
return True
# Eliminate even numbers and multiples of 3
if num % 2 == 0 or num % 3 == 0:
return False
# Check for factors from 5 to the square root of the number (step
by 6)
i = 5
while i * i <= num:
if num % i == 0 or num % (i + 2) == 0:
return False
i += 6
# If no factors found, the number is prime
return True
# Example
print(is_prime(5)) # Output: True
print(is_prime(10)) # Output: False
print(is_prime(17)) # Output: True
True
False
True
Comment
• Initial Check: If the number is less than or equal to 1, it is not prime.
• Basic Primes: If the number is 2 or 3, it is prime.
• Even Numbers and Multiples of 3: If the number is even or divisible by 3, it is not prime.
• Optimized Factor Check: We check for factors from 5 up to the square root of the
number, with a step of 6, to cover potential prime candidates more efficiently.
(7) Multiplication Table: Write a program that generates a multiplication table for a
number provided by the user (1 to 10).
def generate_multiplication_table():
# This function asks the user for a number and generates the
multiplication table for that number from 1 to 10.
# enter a number
number = int(input("Enter a number to generate its multiplication
table: "))
# Print the multiplication table
print(f"Multiplication table for {number}:")
# Loop from 1 to 10
for i in range(1, 11):
# Calculate the product of the number and the loop variable i
product = number * i
# Print the result in the format "number * i = product"
print(f"{number} * {i} = {product}")
# Enter the function to see the output
generate_multiplication_table()
Enter a number to generate its multiplication table: 5
Multiplication table for 5:
5 * 1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50
Comment
• Function Definition: The function generate_multiplication_table() is defined to
encapsulate the entire process.
• User Input: The program prompts the user to enter a number using the input() function
and converts it to an integer with int().
• Print Header: It prints a header for the multiplication table indicating the number.
• Loop: A for loop iterates from 1 to 10. During each iteration, the loop variable i is
multiplied by the user-provided number.
• Output: The product of the multiplication is printed in a formatted string showing the
operation (number * i = product).
(8) Reverse a String: Write a function called reverse_string(s) that takes a string as
input and returns the string reversed. Use a loop to achieve this.
def reverse_string(s):
# This function takes a string 's' and returns the string reversed
using a loop.
# Initialize an empty string to store the reversed string
reversed_s = ""
# Loop through the original string in reverse order
for char in range(len(s) - 1, -1, -1):
# Append each character to the reversed string
reversed_s += s[char]
# Return the reversed string
return reversed_s
# Example
print(reverse_string("hello")) # Output: "olleh"
print(reverse_string("Python")) # Output: "nohtyP"
print(reverse_string("12345")) # Output: "54321"
olleh
nohtyP
54321
Comment :
• Function Definition: The function reverse_string(s) is defined to take a single parameter
s, which is the input string.
• Initialize: An empty string reversed_s is initialized to store the reversed string.
• Loop: A for loop is used to iterate through the original string in reverse order. This is
achieved by starting from the last character (len(s) - 1) and moving to the first character
(0), with a step of -1.
• Appending Characters: In each iteration of the loop, the current character is appended to
reversed_s.
• Return: The function returns the reversed string.
(9) Count Down: Write a program that takes a positive integer n from the user and
counts down from n to 0, printing each number. When it reaches 0, print "Liftoff!"
def countdown():
# This function takes a positive integer 'n' from the user and
counts down from 'n' to 0.
# It prints each number and, when it reaches 0, it prints
'Liftoff!'.
# enter a positive integer
n = int(input("Enter a positive integer to start the countdown:
"))
# Loop from n to 0 (inclusive)
for i in range(n, -1, -1):
# Print the current number
print(i)
# Print 'Liftoff!' when the countdown reaches 0
print("Liftoff!")
# Enter the function to see the output
countdown()
Enter a positive integer to start the countdown: 15
15
14
13
12
11
10
9
8
7
6
5
4
3
2
1
0
Liftoff!
Comment
• Function Definition: The function countdown() is defined to encapsulate the entire
process.
• User Input: The program prompts the user to enter a positive integer n using the input()
function and converts it to an integer with int().
• Loop: A for loop is used to iterate from n down to 0 (inclusive). The range function
range(n, -1, -1) is used to achieve this countdown.
• Output: During each iteration, the current number i is printed.
• Liftoff: After the loop completes, the program prints "Liftoff!".
(10) Password Validation: Write a program that prompts the user to enter a
password. The password must be at least 8 characters long. contain at least one
uppercase letter, one lowercase letter, and one digit. If the password is valid, print
"Password is valid". If not, print "Password is invalid" and prompt the user to try
again until they enter a valid password.
def is_valid_password(password):
# This function checks if the given password is valid.
# A valid password must be at least 8 characters long,contain at
least one uppercase letter, one lowercase letter, and one digit.
if len(password) < 8:
return False
has_upper = False
has_lower = False
has_digit = False
for char in password:
if char.isupper():
has_upper = True
elif char.islower():
has_lower = True
elif char.isdigit():
has_digit = True
return has_upper and has_lower and has_digit
def prompt_password():
# This function prompts the user to enter a password and validates
it.
# It continues to prompt the user until a valid password is
entered.
while True:
password = input("Enter a password: ")
if is_valid_password(password):
print("Password is valid")
break
else:
print("Password is invalid. Please try again.")
# Enter the function to start the password validation
prompt_password()
Enter a password: kritika
Password is invalid. Please try again.
Enter a password: Kritika@123
Password is valid
Comment
• Function Definition: The function is_valid_password(password) checks if the given
password meets the criteria.
– Length Check: The password must be at least 8 characters long.
– Character Checks: It uses three boolean flags (has_upper, has_lower, has_digit)
to check for the presence of at least one uppercase letter, one lowercase letter,
and one digit.
– Loop: A for loop iterates through each character in the password to update the
flags accordingly.
– Return: The function returns True if all criteria are met, otherwise False.
• Prompting for Password: The prompt_password() function continuously prompts the
user to enter a password and validates it using the is_valid_password() function.
– Loop Until Valid: It uses a while True loop to keep prompting until a valid
password is entered.
– Feedback: Prints "Password is valid" if the password meets the criteria, otherwise
prints "Password is invalid. Please try again."