Use enumerate() like so:
def draw_menu(options, selected_index):
for counter, option in enumerate(options):
if counter == selected_index:
print " [*] %s" % option
else:
print " [ ] %s" % option
options = ['Option 0', 'Option 1', 'Option 2', 'Option 3']
draw_menu(options, 2)
Note: You can optionally put parenthesis around counter, option, like (counter, option), if you want, but they're extraneous and not normally included.
Use enumerate() like so:
def draw_menu(options, selected_index):
for counter, option in enumerate(options):
if counter == selected_index:
print " [*] %s" % option
else:
print " [ ] %s" % option
options = ['Option 0', 'Option 1', 'Option 2', 'Option 3']
draw_menu(options, 2)
Note: You can optionally put parenthesis around counter, option, like (counter, option), if you want, but they're extraneous and not normally included.
I'll sometimes do this:
def draw_menu(options, selected_index):
for i in range(len(options)):
if i == selected_index:
print " [*] %s" % options[i]
else:
print " [ ] %s" % options[i]
Though I tend to avoid this if it means I'll be saying options[i] more than a couple of times.
Can you count the number of times a loop occurs?
python - Get loop count inside a for-loop - Stack Overflow
Creating a counter inside a Python for loop - Stack Overflow
Can not understand for loops
How does a for loop work in Python?
What is the purpose of the enumerate() function in Python?
How can I create a custom function similar to enumerate()?
I'm new to python, sorry if my wording is terrible.
I'm building a very basic number guessing game. I don't want to copy and paste the whole code into here unless someone wants it in the comments.
I have it so that you guess a number between 1-100. After each guess it will tell you if it's too low or too high. Once you guess it correct it will say "Correct!". I want it to also tell you how many attempts it took you to find the correct answer and print that out with the "Correct!". How do you do that?
The pythonic way is to use enumerate:
for idx, item in enumerate(my_list):
Agree with Nick. Here is more elaborated code.
#count=0
for idx, item in enumerate(list):
print item
#count +=1
#if count % 10 == 0:
if (idx+1) % 10 == 0:
print 'did ten'
I have commented out the count variable in your code.