Wednesday, December 21, 2022

[FIXED] How to print a variable within an array using its index

Issue

I am practicing with for in loops and having trouble with this.

places = ["phuket", "athens", "doha"]

for places in range(5):
    if places == 0:
        print("thailand," + places 0 + "is a cool place")
    else:
        print("not thailand")

When I try this, I get a syntax error with 'places 0'. I want it to print thailand, phuket, is a cool place. But no matter how I seem to format places 0 (with the 0 in [], with it in ()) I just keep getting syntax errors.


Solution

If you use enumerate you can get the index of the for loop. i will be 0, 1, 2 and place will be phuket, athens, doha. And you can use different logic depends on what you want.

places = ["phuket", "athens", "doha"]

for i,place in enumerate(places):
    if i == 0:
        print("thailand," + place + "is a cool place")
    else:
        print("not thailand")

You can understand more here - https://realpython.com/python-enumerate/



Answered By - Andrej Korjakin
Answer Checked By - Marilyn (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.