给随机选择的名字分配一个变量?

2024-10-05 18:57:12 发布

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

我在为项目中随机选择的名字(Marth、Lucina等)分配变量(在本例中为“hero”)时遇到问题。下面是我代码的一小部分。(为了将这个随机文本(名称)打印到画布上,我必须将它赋给一个变量。)

问题:英雄会说没有定义

import random

focus_chance = 3
five_star_chance = 3
four_star_chance = 36
three_star_chance = 58


summon = random.randint(1, 100)

if summon < 4:
    #print('YOU GOT A 5-STAR FOCUS :DD')        
    focus_hero = ['Marth', 'Lucina', 'Robin', 'Tiki']
    hero = random.choice(focus_hero)           

    if summon > 3 and summon < 8:
        #print('YOU GOT A 5-STAR :D')
        five_hero = ['Ogma', 'Cain', 'Corrin', 'Chrom', 'Caeda', 'Ryoma',
                     'Lyn', 'Tiki', 'Tharja', 'Lilina', 'Leo', 'Azura', 'Abel'
                     'Effie'] 
        hero = random.choice(five_hero)

        if summon > 7 and summon < 45:
            #print('You got a 4-star. :)')
            four_hero = ['Hero1','Hero2']
            hero = random.choice(four_hero)

            if summon > 44 and summon < 101:
                #print('You got a 3-star. :(')
                three_hero = ['Hero3', 'Hero4']
                hero = random.choice(three_hero)
print hero

Tags: andifrandomstarfocusthreefourprint
1条回答
网友
1楼 · 发布于 2024-10-05 18:57:12

我相信你的问题是你的if是嵌套的。这意味着一个if只能在上面的if中的条件为真时进行计算。例如

if summon < 4:
    #Only get here if summon is less than 4

    if summon > 3 and summon < 8:
        #Only get here is summon is less than 4 AND summon is greater than 3 and summon is less than 8

解决这个问题的方法是均匀地缩进if,这样python就可以分别查看每一个:

if summon < 4:
    #Only get here if summon is less than 4

if summon > 3 and summon < 8:
    #Only get here when summon is greater than 3 and less than 8

希望这有帮助!你知道吗

相关问题 更多 >