Home > Software design >  How can i make a function out of this so i don't have to copy paste the same piece of code?
How can i make a function out of this so i don't have to copy paste the same piece of code?

Time:12-16

Currently in my code i am just copy and pasting blocks of code like these 20 times, i need some help on how to make this into a function to save space

if chosenrace == "Var Human":
    randclass = random.choice(varhumanclasses)

if chosenrace == "Aasimar":
    randclass = random.choice(aasimarclasses)

if chosenrace == "Aarakocra":
    randclass = random.choice(aarakocraclasses)

if chosenrace == "Warforged":
    randclass = random.choice(warforgedclasses)

CodePudding user response:

A possible solution would be to have create a dictionary linking the strings, to the variables. For example,

class_dict = {
"Var Human": varhumanclasses,
"Aasimar": aasimarclasses
}

Then, you could create a function that takes the chosen race string and returns a random choice using the correct class variable from the dictionary.

def random_class(race):
    return random.choice(class_dict[race])

CodePudding user response:

like this

def pick(chosenrace): return random.choice({
    "Var Human" : varhumanclasses,
    "Aasimar"   : aasimarclasses,
    "Aarakocra" : aarakocraclasses,
    "Warforged" : warforgedclasses,
}.get(chosenrace, notfoundclasses))

CodePudding user response:

I liked and up-voted the solution by @tintins7a6164. If you don't want to maintain a dictionary, you can consider the snippet below. It assumes that varhumanclasses etc are declared on the global scope.

import random

varhumanclasses = [1, 2, 3]
aasimarclasses = [5, 6, 7]


def get_classes_from_race(race: str):
    classes_s = race.lower().replace(" ", "")   "classes"
    if classes_s in globals():
        f = globals()[classes_s]
    else:
        raise ValueError(f"{classes_s} not found")
    if not isinstance(f, list):
        raise ValueError(f"{classes_s} is not declared as a function")
    return f


print(random.choice(get_classes_from_race("Var Human")))
print(random.choice(get_classes_from_race("Aasimar")))

  • Related