Python conditional statements and loops
1. Write a Python program to find those numbers which are divisible by 7
and multiples of 5
Ans:
# Define the range of numbers
start = 1
end = 100
# List to store the results
result = []
# Loop through the range
for num in range(start, end + 1):
if num % 7 == 0 and num % 5 == 0:
result.append(num)
# Print the result
print("Numbers divisible by 7 and multiples of 5:", result)
2. Write a Python program to convert temperatures to and from Celsius
and Fahrenheit.
[ Formula : c/5 = f-32/9 [ where c = temperature in celsius and f =
temperature in fahrenheit ]
Ans:
def celsius_to_fahrenheit(celsius):
fahrenheit = (celsius * 9/5) + 32
return fahrenheit
def fahrenheit_to_celsius(fahrenheit):
celsius = (fahrenheit - 32) * 5/9
return celsius
# Main program
print("Temperature Converter")
choice = input("Choose conversion type:\n1. Celsius to Fahrenheit\n2. Fahrenheit
to Celsius\nEnter 1 or 2: ")
if choice == '1':
celsius = float(input("Enter temperature in Celsius: "))
fahrenheit = celsius_to_fahrenheit(celsius)
print(f"{celsius}°C is equal to {fahrenheit:.2f}°F")
elif choice == '2':
fahrenheit = float(input("Enter temperature in Fahrenheit: "))
celsius = fahrenheit_to_celsius(fahrenheit)
print(f"{fahrenheit}°F is equal to {celsius:.2f}°C")
else:
print("Invalid choice!")
3. Write a Python program to construct the following pattern, using a
nested for loop.
*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*
Ans:
# Number of rows for the upper half of the pattern
n = 5
# Upper part of the pattern
for i in range(1, n + 1):
print("* " * i)
# Lower part of the pattern
for i in range(n - 1, 0, -1):
print("* " * i)
4. Write a Python program to get the Fibonacci series between 0 and 50.
Note : The Fibonacci Sequence is the series of numbers :
0, 1, 1, 2, 3, 5, 8, 13, 21, ....
Ans:
# Initializing the first two Fibonacci numbers
a, b = 0, 1
# Printing the Fibonacci series between 0 and 50
print("Fibonacci series between 0 and 50:")
while a <= 50:
print(a, end=" ")
# Update the values of a and b for the next iteration
a, b = b, a + b
5. Write a Python program to sum all the items in a list.
Ans:
# Sample list of numbers
numbers = [1, 2, 3, 4, 5]
# Calculate the sum of all items in the list
total_sum = sum(numbers)
# Print the result
print("The sum of all items in the list is:", total_sum)
6. Write a Python program to count the number of strings from a given list
of strings. The string length is 2 or more and the first and last characters
are the same.
Sample List : ['abc', 'xyz', 'aba', '1221']
Expected Result : 2
Ans:
def count_strings(strings):
count = 0
for string in strings:
if len(string) >= 2 and string[0] == string[-1]:
count += 1
return count
# Sample list
sample_list = ['abc', 'xyz', 'aba', '1221']
# Call the function and display the result
result = count_strings(sample_list)
print("Number of strings with length 2 or more and same first and last characters:",
result)
7. Write a Python program to remove duplicates from a list.
Ans:
def remove_duplicates(lst):
return list(set(lst))
# Sample list with duplicates
my_list = [1, 2, 2, 3, 4, 4, 5, 6, 6]
# Removing duplicates
unique_list = remove_duplicates(my_list)
# Display the result
print("List after removing duplicates:", unique_list)
8. Write a Python script to sort (ascending and descending) a dictionary by
value.
Ans:
# Sample dictionary
my_dict = {'apple': 50, 'banana': 20, 'cherry': 30, 'date': 10}
# Sorting in ascending order by value
sorted_dict_asc = dict(sorted(my_dict.items(), key=lambda item: item[1]))
# Sorting in descending order by value
sorted_dict_desc = dict(sorted(my_dict.items(), key=lambda item: item[1],
reverse=True))
# Display the results
print("Dictionary sorted by value in ascending order:", sorted_dict_asc)
print("Dictionary sorted by value in descending order:", sorted_dict_desc)
9. Write a Python script to merge two Python dictionaries.
Ans:
# Two sample dictionaries
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
# Merging dict2 into dict1
dict1.update(dict2)
# Display the merged dictionary
print("Merged dictionary:", dict1)
10. Write a Python program to remove a key from a dictionary.
Ans:
# Sample dictionary
my_dict = {'apple': 50, 'banana': 20, 'cherry': 30}
# Key to be removed
key_to_remove = 'banana'
# Remove the key using pop() method
removed_value = my_dict.pop(key_to_remove, None)
# Check if the key was found and removed
if removed_value is not None:
print(f"Key '{key_to_remove}' removed, value was: {removed_value}")
else:
print(f"Key '{key_to_remove}' not found.")
# Display the updated dictionary
print("Updated dictionary:", my_dict)
11. Write a Python program to get the maximum and minimum values of a
dictionary.
Ans:
# Sample dictionary
my_dict = {'apple': 50, 'banana': 20, 'cherry': 30, 'date': 40}
# Get maximum value
max_value = max(my_dict.values())
# Get minimum value
min_value = min(my_dict.values())
# Display the results
print("Maximum value in the dictionary:", max_value)
print("Minimum value in the dictionary:", min_value)