Create an old sample dictionary {0:10, 1:20} as follows to store numbers. Write a Python script to ask how many runs from user input to add items to the old dictionary. Use a loop to append these key/value pairs to the dictionary. Print out the resulting dictionary for each run (NOT just the last run). Please find the number patterns to append key/value pairs. You cannot add the numbers manually.

Respuesta :

Answer:

Here is the Python code:

runs=int(input("how many runs do you want to add items to dictionary? "))  #store input number of runs

d = dict()  #creates a dictionary

d = {0:10,1:20}  #old dictionary

count=0  #counts number of runs

for x in range(2,runs+2):  #loop to append key/value pairs to dictionary

   d[x]=(x*10)+10  #multiples and adds 10 to the each value

   count+=1  #adds 1 to the count at each iteration

   print("After the #",count, "run the new dictionary is: ",d) #prints the new dictionary

Explanation:

I will explain the program with an example:

The old dictionary is :

d = {0:10,1:20}  

runs = 3

count = 0

At first iteration:

x = 2

d[x]=(x*10)+10

This becomes:

d[2]=(2*10)+10

d[2]= 20 + 10

d[2]= 30

count+=1

count = 1

   print("After the #",count, "run the new dictionary is: ",d)

This statement displays the first iteration result :

After the # 1 run the new dictionary is:  {0: 10, 1: 20, 2: 30}  

At  second iteration:                                                              

x = 3

d[3]=(3*10)+10

This becomes:

d[3]=(3*10)+10

d[3]= 30 + 10

d[3]= 40

count+=1

count = 2

   print("After the #",count, "run the new dictionary is: ",d)

This statement displays the first iteration result :

After the # 2 run the new dictionary is:  {0: 10, 1: 20, 2: 30, 3: 40}      

At  third iteration:                                                              

x = 4

d[4]=(4*10)+10

This becomes:

d[4]=(4*10)+10

d[4]= 40 + 10

d[4]= 40

count+=1

count = 3

   print("After the #",count, "run the new dictionary is: ",d)

This statement displays the first iteration result :

After the # 3 run the new dictionary is:  {0: 10, 1: 20, 2: 30, 3: 40, 4: 50}    

Now the loop breaks as x = 5 necause n+2 = 3+2 = 5 limit is reached

The screenshot of program along with its output is attached.

Ver imagen mahamnasir