从字典中随机选择变量

2024-05-04 08:31:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图让python从我的字典中选择一个随机变量在代码中运行,但似乎无法获得正确的语法。如果有人能帮忙那就太好了

def battle():
    moveset_dict = {
    "1": 25, 
    "2": 50,
    "3": 75,
    "4": 100,
    }
    hp = 100

    while hp > 0 :
        attack_chosen =  random.range(len(moveset_dict))
        hp = hp - attack_chosen
        print("Alar used", attack_chosen, "Valor has", hp, "hp")

    else:
        print("Valor has fainted")

battle()

Tags: 代码字典def语法randomdictvalorhp
1条回答
网友
1楼 · 发布于 2024-05-04 08:31:14

你应该试试

import random
def battle():
    moveset_dict = {
    "1": 25, 
    "2": 50,
    "3": 75,
    "4": 100,
    }
    hp = 100

    while hp > 0 :
        attack_chosen =  random.choice(range(len(moveset_dict)))
        hp = hp - attack_chosen
        print("Alar used", attack_chosen, "Valor has", hp, "hp")

    else:
        print("Valor has fainted")

battle()

相关问题 更多 >