Exercise 106

Write a program in Python that asks the user to enter ten integers of their choice and return them a dictionary whose keys are the entered integers and whose values are 'prime' or 'not prime' depending on the entered integer.

Solution

# creating a function to test if given integer is prime or not
def isPrim(n):
# initializing the numer of divisors of n
numberDivisors = 0
# browsing through all integers 1 2 3 ... n
for i in range(1 , n + 1):
if ( n%i == 0 ):
numberDivisors = numberDivisors + 1
if (numberDivisors == 2 ):
return True
else:
return False

# creating an empty dictionary which will be contains entered key and their values
d = dict({})
for i in range(0 , 10):
n = int(input("Type an integer : " ))
if (isPrim(n)):
d[n] = "prime"
else:
d[n] = "not prime"
print(d)
# Testing algorithm:
# for the entered values Type an integer : 3, 5, 4, 11, 18, 13, 9, 22, 45, 16 the output is :
# {3: 'prime', 5: 'prime', 4: 'not prime', 11: 'prime', 18: 'not prime', 13: 'prime', 9: 'not prime', 22: 'not prime', 45: 'not prime', 16: 'not prime'}

Younes Derfoufi
my-courses.net
One thought on “Solution Exercise 106: python code to generate a dictionary from some entered numbers”

Leave a Reply