'Call function at end of for loop is not working as intended
The following code is not working as intended when I call the next() function at end of for loop. For some reason only one item from the list is printed and it is always the same food (banana). When I remove the next() call at the end of the for loop, everything seems to run fine. Excuse the code, as I am sure there is a more efficient way to implement this, but could anyone explain why the function fails to work as intended?
I wanted this code to constantly loop back to the beginning of the function, add a random no of foods to shop list, and print them out after user presses enter button.
import random
food=["orange","banana","bread loaf","watermelon","cake","pudding"]
shop=[]
def next():
day=input("press enter to start the next day:")
if day==(""):
rand=random.randrange(1,10)
while rand > 0:
shop.append(random.choice(food))
rand-=1
if rand <=0:
shop.sort()
for items in shop:
print(items)
next()
next()
Solution 1:[1]
Managed to sort it out (mostly). Created two separate functions, but more importantly (i think) , changed the order of while loop and modified the if statement.
Also added a clear function for the list being appended. Everything except the list sorting function is working.
import random
food=["orange","banana","bread loaf","watermelon","cake","pudding"]
shop=[]
def nextday():
rand=random.randrange(1,12)
while rand > 0 :
shop.append(random.choice(food))
for i in shop:
shop.sort()
print(i)
rand-=1
if rand==0:
day()
def day():
print("")
so=input("press enter to start the day: ")
print("")
if so==(""):
shop.clear()
nextday()
day()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | d_code |
