Exercise 103
Write a Python program that creates from a keyboard-typed integer n, a dictionary whose keys are integers from 1 to n and key values are their squares. Example for n = 7 the dictionary will be of the form:
{1: 1, 2: 4, 3: 9, 4:16, 5:25, 6:36, 7:49}
Solution
# we ask the user to enter an integer n
n = int (input ("Enter the value of n"))
# we create an empty dictionary which will contain the numbers n and their squares
d = dict ({})
# browsing through integers from 1 to n and adding key and values to dictionary
for i in range (1, n + 1):
d [i] = i * i
print (d)
#The output for n = 10 is : {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100}
Younes Derfoufi
my-courses.net
my-courses.net