首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如果我在python中定义了变量,为什么似乎没有定义它?

如果我在python中定义了变量,为什么似乎没有定义它?
EN

Stack Overflow用户
提问于 2022-01-24 06:38:09
回答 1查看 72关注 0票数 -1

我开始学习Python,我想知道为什么即使我在函数之上定义了我的变量反函数,它也不会在函数中被识别。

代码语言:javascript
复制
counterofplays = 0  # this variable should be defined below

def tiktaktoe():
    while playing:
        isdigit = False
        inRange = False
        while not isdigit or not inRange:
            playable = True 
            print(firstchoice,"turn")
            index = input("Choose the index:\n" +
                        "1 | 2 | 3\n" +
                        "4 | 5 | 6\n" +
                        "7 | 8 | 9\n")

            if index.isdigit():
                isdigit = True
                index = int(index)
                if index in range(1,4) and row1[index-1][0] == ' ':
                    inRange = True
                    row1[index-1] = firstchoice if index == 3 else firstchoice + " | "
                    counterofplays += 1 # and here it marks error
                elif index in range(4,7) and row2[index-4][0] == ' ':
                    inRange = True
                    row2[index-4] = firstchoice if index == 6 else firstchoice + " | "                
                    counterofplays += 1
                elif index in range(7,10) and row3[index-7][0] == ' ':
                    inRange = True
                    row3[index-7] = firstchoice if index == 9 else firstchoice + " | "                
                    counterofplays += 1
                else:
                    inRange = False
                    playable = False
            else:
                isdigit = False
                playable = False
                print("You've to choose a number")
                sleep(1.3)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-01-24 06:48:09

您应该尝试将counterofplays直接在TikTakToe()中定义为global,并且不会造成任何问题。由于似乎没有在上述函数之外使用该变量,所以也不能将其设置为global

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70829863

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档