-2

I know that the question is quite ambiguous, so I'll expand on my problem. I have written a short thingy over here as practice since I just started learning python and am sort of a newbie.

In my code, I ask the user how many apples they have and if they would like to eat it. If they keep saying "Y" until the amount of apples is 0 (#mention 1 in the screenshot), I want my code to redirect to the #redirect 1 part, instead of writing the entire code from #redirect 1 again. I know that I could just rewrite it, however, I can't for the next part. If there are no apples, I ask the user if they want to buy them and the amount.

Then I would like to redirect the code back to #redirect 2 so that the code plays out again. I have read previous questions and understand that a 'goto' doesn't exist as it is unstructured, however, I have no idea how else I would write my code. Sorry for the dumb question, but as I said I am new to this.

Image of my code

Cohan
  • 4,384
  • 2
  • 22
  • 40
  • 7
    Please post *all code as formatted text in the question itself.* Dont post images of code or links to code / images of code. Always provide a [mcve] for debugging questions. – juanpa.arrivillaga Jan 15 '20 at 19:34
  • 4
    Anyway, no, there is no goto statement in Python, because it was a language made within the last, oh, 50 years. Generally, you should use *functions* to re-use code. Other than that, it is just getting used to thinking in terms of the branching/looping constructs provided by the language. – juanpa.arrivillaga Jan 15 '20 at 19:35
  • 1
    Check `while` structure https://realpython.com/python-while-loop/ – Gocht Jan 15 '20 at 19:37
  • 3
    Maybe not a direct duplicate, but you might find this question helpful, along with functions as previously suggested: [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – G. Anderson Jan 15 '20 at 19:41
  • @juanpa.arrivillaga oh ok I’m sorry it’s my first question on stack Overflow as well so I thought a picture was enough – SoulOfSword Jan 16 '20 at 06:47

1 Answers1

0

Sounds like you need function definition. Something like.

def dostuff():
    print "doing stuff"
    num = 0
num = 0
while true:
    num =+ 1
    if num == 5:
        dostuff()
    else:
        pass

This should print doing stuff once every 5 loops

  • How would I apply it in this case? If the number of apples is 0 and I ask the user if they want to buy more apples, I want the loop to repeat again. Should I use the while loop? – SoulOfSword Jan 16 '20 at 06:46
  • `while true:` will cause anything inside of it to loop forever until you call a `break` You can check the user input, and if the input is no you `break` the loop because they don't want to buy more. In your case you'd use `while true:` choice and it would be inside the `if apples > 0:` – Brandon Campbell Jan 16 '20 at 13:12