PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, December 21, 2022

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

 December 21, 2022     arrays, python, syntax, variables     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing