so i am stuck on a certain problem I have to solve and was wondering if you guys could help me in my situation (i am really new to python and programming by itself). So the task i got is, to define a own new function to pick out of a Dictionary called "phonebook" random people and print out to pretend calling them. Something like "randomcall(phonebook,10) and then it prints: Calling Peter at 1800650, and 9 others.
def randomcall(phonebook, number):
import random
for name in range(phonebook):
name = random.choice(list(phonebook))
phonebook = phonebook[name]
print(f"Let's call {name} with {phonebook}")
phonebook = {"martin": 12345, "anna": 65478, "klaus": 5468764, "hans": 748463, "peter": 84698416, "ulrich": 3416846546, "frank": 4789749, "lukas": 798469, "ferdinand": 68465131}
randomcall(phonebook, 3)
randomcall("", 5)
Your code is correct, except for several small mistakes:
for name in range(phonebook)
becausephonebook
is not the integral number of times that you need to iterate.number
is. Also the variablename
is not referenced to in the iteration; it was assigned a new value. So it can be changed into another variable, likei
, which is used more commonly in iteration.phonebook
, which is the variable of the phonebook dictionary. It makes it impossible to access the actual phonebook again. Another variable, likephone
, can be used there.So the completed code should look like:
Output:
Also, as stated in this comment, the line
randomcall("", 5)
is used to call a random person. Actually, the phonebook must be passed to the function as thephonebook
parameter, and if1
is passed to thenumber
parameter, it generates 1 random call.