【问题标题】:why this code run correctly? (python global keyword) [duplicate]为什么这段代码运行正确? (python全局关键字)[重复]
【发布时间】:2021-06-11 04:03:35
【问题描述】:

我是新手...正在研究global 关键字。 此代码创建一个随机字符串。

我认为 第 8 行string.append(word[x]) 在此代码上出错 因为string是一个全局变量,所以必须要global关键字。 (全局字符串)

但是这段代码运行正确... 为什么可以正常运行...?

import random
word = 'a b c d e f g h i j k l m n o p q r s t u v w x y z'.split(" ")
string = []
n = int(input())

def get(leng) :
    for i in range (0, leng) :
        x = random.randint(0, len(word)-1)
        string.append(word[x])
    sen = ''.join(string)
    return sen

print(get(n))

【问题讨论】:

    标签: python python-3.x global-variables global


    【解决方案1】:

    你的代码乍一看似乎没有任何问题,虽然不是很清楚你想要发生什么或者错误,但是在get(),你的列表string不需要赋值作为全局变量,除非您想重新定义该变量。如果出于某种原因,您决定在函数中声明 string 或任何与此相关的变量,则需要更改其范围。

    【讨论】:

    • 感谢您的回答。 :) 我知道我不需要被分配为全局变量,但我想知道为什么我不需要在此代码上使用 global 关键字
    • 这是因为你调用的是list的方法,而不是重新定义变量。
    • 哦,你的意思是方法不是重新定义列表的方法......对吗? ?
    • 完全正确。 .append 所做的只是在最后添加一个值,而不是创建一个新值
    猜你喜欢
    • 2023-03-24
    • 2018-04-26
    • 1970-01-01
    • 1970-01-01
    • 2022-07-08
    • 2023-03-18
    • 1970-01-01
    • 2014-08-31
    相关资源
    最近更新 更多