My Idea is as following
I dug a bit deeper and tried to make it more flexible as requested.
Concept: Use dictionary to create a person with an attached list of friends.
Advantage: Can contain/store multiple persons with regarding friends. :)
How it works:
- The "for" loop iterates through the number of keys stored inside the dictionary.
- The key (here the entered person) is then put in the first string of the loop with the argument end="" which tells the print function to operate in the same line.
- After that a second variable is implemented which is given the length of the key-value by requesting the stored variable of the dictionary behind the key. We need that value later to determine the last entry of the list. ;) (Note: with every for loop it gets a new value)
- In the next for loop we will iterate through all friends on the list by pointing to the key-value (here the list) through the key from the outer for loop iteration.
- Inside this for loop are three mechanism intertwined:
5.a) The value n_friend decrements by one with each cycle.
5.b) As long as n_friend does not reach zero every friend will be printed with the argument end="" as explained in point 2.
5.c) After n_friend reaches zero the if/else conditional statment will
switch to else and will print the last iteration of the for loop with the requested "and...[enter friend here].". This is without a end="" so the next print will switch into a new line.
- Continue the cycle by 1 again.
.break for code.
friends_list={
"person_1":['Jack', 'John','Jane'],
"person_2":['Luke', 'Darth','Han','Wednesday']
}
for person in friends_list:
print(f"{person} likes following persons: ",end="")
n_friend = len(friends_list[person])
for friend in friends_list[person]:
n_friend -= 1
if n_friend > 0:
print(friend, end=" ")
else:
print(f"and {friend}.")