Skip to content
Advertisement

Make a for loop that doesn’t add a new line (Class’s List)

I’m pretty new to python and I’m trying to make an inventory for a text RPG game I’m making if you could help me figure this out id super appreciate it!

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()

Current output if I enter Test as name then, giveX3, stats

Enter name here: Test
Enter Command: give
Enter Command: give
Enter Command: give
Enter Command: stats
Name = Test 
 Inventory: 
Me Sword
Me Sword
Me Sword

Desired output if I enter Test as name then, giveX8, stats Also would like to do a new line after every 4 Items have been shown

Enter name here: Test
Enter Command: give
Enter Command: give
Enter Command: give
Enter Command: give
Enter Command: give
Enter Command: give
Enter Command: give
Enter Command: give
Enter Command: stats
Name = Test 
 Inventory: Me Sword, Me Sword, Me Sword, Me Sword #loop after 4 items
            Me Sword, Me Sword, Me Sword, Me Sword

If you have any suggestions I’d really appreciate the help! P.S it does not have to be a for loop but I do not want to have to print every weapon index in order to get them in that output

Advertisement

Answer

You can use slicing and join:

def stats():
    items = [item.item_name for item in Player_1.inventory]

    print(f"Name = {Player_1.name}")
    
    if not items: # if empty list
        print("Inventory is empty.")
        return

    for i in range(0, len(items), 4):
        if i == 0:
            print("Inventory: ", end='')
        else:
            print("           ", end='') # for non-first lines
        print(', '.join(items[i:i+4]))

Output:

Enter name here: foo
Enter Command: give
Enter Command: give
Enter Command: give
Enter Command: give
Enter Command: give
Enter Command: stats
Name = Foo
Inventory: Me Sword, Me Sword, Me Sword, Me Sword
           Me Sword
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement