Home > database >  University Question including for loops and lists
University Question including for loops and lists

Time:10-25

the question is asking me to do this In a small highland village, everyone has the surname McIntosh, McGregor, McDonald or McKenzie. Everyone is called Angus, Hamish, Morag or Mhairi No two people have the same name. Create a program to compile a list of the inhabitants of the village.

It makes use of lists and loops but I don't know how to do it, this is what i have so far

surnames = ["Mcintosh", "McGregor", "McDonald", "Mckenzie"]
forenames = ["Angus", "Hamish", "Morag", "Mhairi"]

for forenames in forenames:
    for surnames in surnames:
        print forenames

CodePudding user response:

You have the right idea with doing a nested loop, but you need to use a different variable name for the for var in iterable part, and you need to print the variables from both loops.

>>> surnames = ["Mcintosh", "McGregor", "McDonald", "Mckenzie"]
>>> forenames = ["Angus", "Hamish", "Morag", "Mhairi"]
>>> for fore in forenames:
...     for sur in surnames:
...         print(fore, sur)
...
Angus Mcintosh
Angus McGregor
Angus McDonald
Angus Mckenzie
Hamish Mcintosh
Hamish McGregor
Hamish McDonald
Hamish Mckenzie
Morag Mcintosh
Morag McGregor
Morag McDonald
Morag Mckenzie
Mhairi Mcintosh
Mhairi McGregor
Mhairi McDonald
Mhairi Mckenzie

Note that e.g. surnames is the list of all the surnames, and for sur in surnames assigns each individual surname to the variable sur.

CodePudding user response:

You have a great start, but I think you need more an explanation of what is happening. The first loop will be picking the forename. The second loop will be choosing the last name.

To understand this more clearly here is an example

first = [1, 2, 3, 4]
second = [1, 2, 3, 4]

for i in first:
    for k in second:
        print(i, k)

OUTPUT:

1 1
1 2
1 3
1 4
2 1
2 2
2 3
2 4
3 1
3 2
3 3
3 4
4 1
4 2
4 3
4 4

CodePudding user response:

surnames = ["Mcintosh", "McGregor", "McDonald", "Mckenzie"]
forenames = ["Angus", "Hamish", "Morag", "Mhairi"]


print({f"{i} {j}"for j in forenames for i in surnames})

# {'Mhairi Mcintosh', 'Morag Mckenzie', 'Mhairi Mckenzie', 'Mhairi McDonald', 'Angus McGregor', 'Morag McGregor', 'Angus Mckenzie', 'Hamish Mckenzie', 'Angus Mcintosh', 'Morag McDonald', 'Angus McDonald', 'Hamish McGregor', 'Morag Mcintosh', 'Hamish Mcintosh', 'Mhairi McGregor', 'Hamish McDonald'}
  • Related