Please forgive me… new to python and first question on stack.
I’m trying to accomplish two things with while loop:
- increment round number (i’m doing this successfully)
- 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:
JavaScript
x
7
1
while round_number < 5:
2
round_number += 1
3
print("Round Number: ", round_number)
4
5
for item in fruit:
6
print(item)
7
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…
Advertisement
Answer
If you must use the while-loop then you can write your code as this:
JavaScript
1
7
1
fruit = ['apple', 'orange', 'banana']
2
round_number = 0
3
4
while round_number < len(fruit):
5
round_number += 1
6
print("Round Number: ", round_number, fruit[round_number-1])
7
and for the for-loop then your code will be:
JavaScript
1
6
1
fruit = ['apple', 'orange', 'banana']
2
round_number = 0
3
4
for item in fruit:
5
print("Round Number: ", fruit.index(item)+1, item)
6
hope this help