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)
because phonebook
is not the integral number of times that you need to iterate. number
is. Also the variable name
is not referenced to in the iteration; it was assigned a new value. So it can be changed into another variable, like i
, 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, like phone
, can be used there.So the completed code should look like:
def randomcall(phonebook, number):
import random
for name in range(number):
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)
Output:
Let's call anna with 65478
Let's call klaus with 5468764
Let's call hans with 748463
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 the phonebook
parameter, and if 1
is passed to the number
parameter, it generates 1 random call.