0

I have troubles in using for loops in Python. I wrote this code:

x=5
people=['Mary','Joe']
genders=['she','he']

for person in people:
    print(person)
    for gender in genders:
        if x > 0:
            print("{} is happy".format(gender)) 

and the output is:

Mary
she is happy
he is happy
Joe
she is happy
he is happy

But I would like the output to be:

Mary
she is happy
Joe
he is happy

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.

2
  • You can use zip, per below, or enumerate. Also, what you're calling 'gender' is not actually a gender; it's a (personal) pronoun. Commented Jul 26, 2021 at 16:40
  • it's a toy code... thank you! Commented Jul 26, 2021 at 16:42

1 Answer 1

4

Why, you can go with zip(). Here is a cleaner solution.

people=['Mary','Joe']
genders=['she','he']
for person,gender in zip(people,genders):
    print(person)
    print("{} is happy".format(gender)) 

Output:

Mary
she is happy
Joe
he is happy
Sign up to request clarification or add additional context in comments.

4 Comments

@Manuela. Most welcome. Consider upvoting and accepting the answer if it solves the issue
I have upvoted but I can accept the answer only in 7 minutes (it tells me so) @Sujay
@Manuela, no problem
Manuela had meaningful names and you changed it to i and j. Why, oh why? Please change it back to person and gender.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.