Home > Software engineering >  How to print a variable within an array using its index
How to print a variable within an array using its index

Time:02-04

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.

CodePudding user response:

Use places[0] and name your for loop variable something other than places so that you don't have conflicting names, eg: for i in range(5) is a more standard naming convention – - Nick Parsons. This was the correct answer:

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

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

CodePudding user response:

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 - enter image description here

IInd method

enter image description here

  •  Tags:  
  • Related