Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to return to the start of a function while in that function without recursion

class PlayerAttributes:
        inventory = []
        def __init__(self, name, inventory):
            self.name = name
            self.inventory = inventory # LIST
    class Item:
        def __init__(self, item_name, damage):
            self.item_name = item_name
            self.damage = damage

class Weapons(Item):
    weapon_1 = Item("Me Sword", 100)


Player_1 = PlayerAttributes("Bob", [])

def get_name():
    Player_1.name = input("Enter name here: ").capitalize()
    commands()

def stats():
    print("Name = " + str(Player_1.name), "\n",
          "Inventory: ")
    for x in Player_1.inventory:
        print(str(x.item_name))

def commands():
    prompt = None
    prompt_choices = {"stats", "quit", "give"}
    while prompt not in prompt_choices:
        prompt = input("Enter Command: ").lower()
    if prompt == "stats":
        stats()
        commands()
    elif prompt == "quit":
        quit()
    elif prompt == "give":
        Player_1.inventory.append(Weapons.weapon_1)
        commands()

get_name()

PROBLEM

I’m currently getting back to the while loop for "prompt" by calling "commands()" in the if statements but was told that it’s a recursion and that it’s unnecessary as well as it has a side effect of growing the call stack…

QUESTION

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

What should I do differently??

Extra

How would it grow the call stack?

>Solution :

You can use an infinite loop. Instead of letting get_name and commands call commands, try putting the following at the end of the code:

get_name()

while True:
    commands()

and remove all other calls commands() from your code.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading