Home > Software design >  Loop through variable in python
Loop through variable in python

Time:07-15

Please forgive me... new to python and first question on stack.

I'm trying to accomplish two things with while loop:

  1. increment round number (i'm doing this successfully)
  2. have the loop iterate over my variable "fruits" to print the first fruit on round one and second fruit on round two

variables:

round_number = 0 fruit = [apple, orange, banana]

python code:

while round_number < 5:
    round_number  = 1
    print("Round Number: ", round_number) 

 for item in fruit:
      print(item)

the above code is what I currently have. When I run the code it prints all items in my fruit variable at once.

My desired output is for the print output to look like this:

Round Number: 1 apples

Round Number: 2 oranges

ect...

CodePudding user response:

You can do that with enumerate:

fruit = ['apple', 'orange', 'banana']
for n, f in enumerate(fruit, start=1):
    print(f'Round Number: {n} {f}s')

Output:

Round Number: 1 apples
Round Number: 2 oranges
Round Number: 3 bananas

CodePudding user response:

If you must use the while-loop then you can write your code as this:

fruit = ['apple', 'orange', 'banana']
round_number = 0

while round_number < len(fruit):
    round_number  = 1
    print("Round Number: ", round_number, fruit[round_number-1]) 

and for the for-loop then your code will be:

fruit = ['apple', 'orange', 'banana']
round_number = 0

for item in fruit:
    print("Round Number: ", fruit.index(item) 1, item)

hope this help

CodePudding user response:

It would be better to use the index instead of a counter.

Try getting the index of the item in the list, and adding 1. Then joining the string together for the print

for x in fruit:
    print('Round Number: '   str(fruit.index(x) 1), x)

CodePudding user response:

Unless you're using asynchronous stuff, things will happen in the order they're written. The first loop executes entirely, and then the second loop executed entirely.

This is why youll get an output looking like this

Round Number:  1
Round Number:  2
Round Number:  3
Round Number:  4
Round Number:  5
apple
orange
banana

If you want to output the index of a variable in your list, followed by the variable, you'd want to do that in a single loop.

The way to do this you'd learn starting out looks like this

fruit = ['apple', 'orange', 'banana']

for i in range(len(fruit)): 
  print(i 1, fruit[i])

However, the pythonic way to do this would use the enumerate method

for i, fruitName in enumerate(fruit):
  print(i 1, fruitName)

It would also be good to get used to string formatting

for i, fruitName in enumerate(fruit):
  print(f'{i 1}: {fruitName}')

CodePudding user response:

You have to customize the enumerate function to start the number from 1

for i, item in enumerate(fruits, start=1):
   print(i, item)

Alternatively, you can use for loop

for i, item in range(len(fruit)):
   print(i 1, fruit[i])
  • Related