Part B (Weekly Assignment Question)
Question I. Write a function that accepts two positive integers, viz. a and b where a is smaller
than b. It returns a list that contains all the odd numbers between a and b (including a and
including b if applicable) in descending order. Example: Odd Numbers between 10 and 20
should create the list and print the list in descending order as follows. [19, 17, 15, 13, 11]
Solution
def odd_numbers_descending(a, b):
if a > b:
return "Invalid input: a should be smaller than b"
# Odd numbers between a and b
odd_numbers = [num for num in range(a, b + 1) if num % 2 != 0]
return odd_numbers[::-1]
a = int(input("Enter (a) : Smaller interger : "))
b = int(input("Enter (b) : Larger than a : "))
# Ensure a is smaller than b
if a < b:
result = odd_numbers_descending(a, b)
print("Odd numbers between", a, "and", b, "in descending order are:",
result)
else:
print("Invalid input: a should be smaller than b")
Output
Validate a is smaller han B
Return the Odd numbers
Question 2. Write a Python program to print and store squares of numbers in a dictionary.
Solution
def store_squares(n):
# Created a dictionary to store squares
squares_dict = {i: i**2 for i in range(1, n + 1)}
# Printing the dictionary here
print("Squares of numbers from 1 to", n, "are:", squares_dict)
return squares_dict
n = int(input("Enter a positive integer (n): "))
# Ensuring that the input is positive
if n > 0:
squares = store_squares(n)
else:
print("Invalid input: n should be a positive integer")
Output: