I have troubles in using for loops in Python. I wrote this code:
JavaScript
x
10
10
1
x=5
2
people=['Mary','Joe']
3
genders=['she','he']
4
5
for person in people:
6
print(person)
7
for gender in genders:
8
if x > 0:
9
print("{} is happy".format(gender))
10
and the output is:
JavaScript
1
7
1
Mary
2
she is happy
3
he is happy
4
Joe
5
she is happy
6
he is happy
7
But I would like the output to be:
JavaScript
1
5
1
Mary
2
she is happy
3
Joe
4
he is happy
5
Is there a way to make the for loop iterate over first “Mary” and “she” and then “Joe” and “he” ?
I thank you in advance.
Advertisement
Answer
Why, you can go with zip()
. Here is a cleaner solution.
JavaScript
1
6
1
people=['Mary','Joe']
2
genders=['she','he']
3
for person,gender in zip(people,genders):
4
print(person)
5
print("{} is happy".format(gender))
6
Output:
JavaScript
1
5
1
Mary
2
she is happy
3
Joe
4
he is happy
5