微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用外部DEF语句中的值?

如何解决如何使用外部DEF语句中的值?

我已经有一段时间这个问题了,似乎找不到任何可行的方法。我将如何获得它,以使当前空间增加总滚动量。

def roll():
    import random
    doubles = 0

    x = random.randint(1,6)
    y = random.randint(1,6)

    print(x,y)
    if x == y:
        print('Doubles')
        doubles = 1
        print(f'You have rolled {doubles} doubles!')
        x1 = random.randint(1,6)
        y1 = random.randint(1,6)
        print(x1,y1)
        if x1 == y1:
            print('Doubles')
            doubles = 2
            print(f'You have rolled {doubles} doubles!')
            x2 = random.randint(1,6)
            y2 = random.randint(1,6)
            print(x2,y2)
            if x2 == y2:
                doubles = 3
                print(f'You rolled {doubles} doubles!')
                print('Go to Jail!')
            else:
                total2 = x + y + x1 + y1 + x2 + y2
                print(f'You rolled {total2} in total.')

        else:
            total1 = x + y + x1 + y1
            print(f'You rolled {total1} in total.')

    else:
        total = x + y
        print(f'You rolled {total} in total.')
        


currentspace = 0

print(roll())

解决方法

使用global语句。

def roll():
    global currentspace
    ...do your things...
    currentspace += 1
,

我希望我的问题对了,大声笑

首先,您必须指定该值将随着全局值而变化,然后我在其中写下了该值的剩余位置,您无需执行其他任何操作,即可在滚动后在屏幕上打印该值功能发挥作用。

我确实这样:

def roll():
    import random
    global currentspace

    currentspace +=1
    doubles = 0

    x = random.randint(1,6)
    y = random.randint(1,6)

    print(x,y)
    if x == y:
        currentspace +=1
        print('Doubles')
        doubles = 1
        print('You have rolled %s doubles!'%doubles)
        x1 = random.randint(1,6)
        y1 = random.randint(1,6)
        print(x1,y1)
        if x1 == y1:
            currentspace +=1
            print('Doubles')
            doubles = 2
            print('You have rolled %s doubles!'%doubles)
            x2 = random.randint(1,6)
            y2 = random.randint(1,6)
            print(x2,y2)
            if x2 == y2:
                currentspace +=1
                doubles = 3
                print('You rolled %s doubles!'%doubles)
                print('Go to Jail!')
            else:
                total2 = x + y + x1 + y1 + x2 + y2
                print('You rolled %s in total.'%total2)

        else:
            total1 = x + y + x1 + y1
            print('You rolled %s in total.'%total1)

    else:
        total = x + y
        print('You rolled %s in total.'%total)
    



currentspace = 0
roll()
print("currentspace:",currentspace)

如果我输入的问题有误,请打电话给我删除。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。