numbers = [1, 2, 3, 4, 5]
number_dict = {}
for num in numbers:
number_dict[num] = num ** 2
print("Dictionary with numbers and their squares:", number_dict)
#source code --> clcoding.com
Code Explanation:
Input List:
numbers = [1, 2, 3, 4, 5]
This list contains the numbers for which we want to calculate the square.
Create an Empty Dictionary:
number_dict = {}
This empty dictionary will be populated with key-value pairs, where:
The key is the number.
The value is the square of the number.
Iterate Through the List:
for num in numbers:
This loop iterates through each number (num) in the numbers list.
Compute the Square of Each Number and Add It to the Dictionary:
number_dict[num] = num ** 2
num ** 2 calculates the square of the current number.
number_dict[num] assigns the square as the value for the current number (num) in the dictionary.
Print the Dictionary:
print("Dictionary with numbers and their squares:", number_dict)
This displays the resulting dictionary, which contains each number and its square.
0 Comments:
Post a Comment