## Thursday, September 24, 2020

Solution Exercise 109: python code to create dictionary with 1 , 2 , 3, ... as keys and their sums as values

#### Exercise 109

Write a program in Python that asks the user to enter an integer n and return a dictionary whose keys are the integers 1, 2, 3, ... n and whose values ​​are the sums 1, 1+ 2, 1 + 2 + 3,... 1 + 2 + 3 + ... + n.

#### Solution

``````# create a function which calculates the sum 1 + 2 + 3 + ... + n
def sumInt(n):
s = 0
for i in range(1, n + 1):
s = s + i
return s

# create an empty dictionary which will contains the key 1 , 2 , 3 , ... , n and their values
d= dict({})
n = int(input("Enter value of integer n"))
for i in range(1, n):
d[i] = sumInt(i)

# display obtained  dictionary d
print("The obtained dictionary is d = " , d)
# The output is :
#The obtained dictionary is d =  {1: 1, 2: 3, 3: 6, 4: 10, 5: 15, 6: 21}``````

Younes Derfoufi
my-courses.net

## Python Exercises With Solutions

1. Python Arithmetic Exercises
2. Equations & System Of Equations
3. Polynomials and Functions
4. Python Arithmetic Exercises
5. Numpy, Matplolib, Sympy , Scipy - Exercises
6. Python Arithmetic Exercises

Younes Derfoufi