I'm learning Python 3 right now and I'm trying to figure out if their is a better way to write the following code:
import random
ability_stats = ["acrobatics", "animal handling", "arcana", "athletics", "deception", "history", "insight",
"intimidation", "investigation", "medicine", "nature", "perception", "performance", "persuasion",
"religion", "sleight of hand", "survival"]
def ability_check():
user_ability = input("""What Ability Check would you want to look at:
Acrobatics, Animal Handling, Arcana, Athletics, Deception, History, Insight,
Intimidation, Investigation, Medicine, Nature, Perception, Performance,
Persuasion, Religion, Sleight of Hand, Survival? """).lower()
while user_ability not in ability_stats:
user_ability = input("""Please choose one of the following:
Acrobatics, Animal Handling, Arcana, Athletics,
Deception, History, Insight, Intimidation, Investigation, Medicine, Nature, Perception,
Performance, Persuasion, Religion, Sleight of Hand, Survival: """).lower()
if user_ability == "Acrobatics".lower():
roll = random.randint(1, 20)
acrobatics_check = roll 2
print("Your Acrobatics check rolled: ", acrobatics_check)
elif user_ability == "Animal Handling".lower():
roll = random.randint(1, 20)
animal_handling_check = roll 2
print("Your Animal Handling check rolled: ", animal_handling_check)
elif user_ability == "Arcana".lower():
roll = random.randint(1, 20)
arcana_check = roll 8
print("You Arcana check rolled: ", arcana_check)
ability_check()
Currently this code works as intended for the three options above. I stopped creating the rest of the list, because it seems repetitive. Is there a better way to write this or make it so it's not repetitive? Or is this the best option?
The 2 and 8 are static for now, but I have a link setup to another Python sheet that has this information calculated so it would be:
DnD_Attributes.Acrobatics
instead of the 2 / 8 variables in the code above. Please let me know if there are other ways to improve this code or better ways to write this as I'm learning Python and want to become better at writing Python.
Thank you in advance!
CodePudding user response:
I don't know if I understand your problem correctly but I wrote this
ability_dict = {"acrobatics": 2, "animal handling": 2, "arcana": 8}
# connection of ability and the " " value can be made as a dict
def ability_check():
while True:
user_ability = input("""Please choose one of the following:
Acrobatics, Animal Handling, Arcana, Athletics,
Deception, History, Insight, Intimidation, Investigation, Medicine, Nature, Perception,
Performance, Persuasion, Religion, Sleight of Hand, Survival: """).lower()
if user_ability in ability_dict.keys():
roll = random.randint(1, 20)
check = roll ability_dict[user_ability.lower()]
print(f"Your {user_ability} check rolled: ", check)
break
First make a dict with all the terms and the reference to its value. And instead of repeating each name reference this dict :)