python - 关于python函数和变量访问的问题

标签 python function

我目前正在学习Python并研究如何定义和使用函数。但我有一个令我困惑的问题。

教程中有这样的内容:

alphabet = ['a','b','c']
text = input("type your message")
shift = int(input("type the number of characters to shift message by"))

def encrypt(txt_msg, shft_msg):
    for letter in txt_msg:
        position = alphabet.index(letter)
        # rest of code...
    print(result)

encrypt(text, shift)

所以我明白,当我调用 encrypt(text,shift) 时,我将这些参数传递给函数 txt_msgshft_msg 中的参数,以便它们在函数中可用。

那么为什么他们没有也通过alphabet呢?在我看来,根据 MA​​TLAB 的经验,如果您希望主工作区中的变量可用于该函数,则必须将它们作为参数传递。为什么 alphabet 可用于函数而不将其作为参数传递?如果是这样的话,传递任何参数有什么意义呢?

最佳答案

代码中的所有变量都是全局的。要回答你的第二个问题,没有实际“需要”通过它们。现在回答你的第一个问题,你也可以传递alphabet,但它看起来像是常量,并且将被重用于加密的不同输入。为了使其更加合理和Python化,请考虑以下事项:

ALPHABET = ['a','b','c']

def encrypt(txt_msg, shft_msg):
    for letter in txt_msg:
        position = ALPHABET.index(letter)
        # rest of code...
    print(result)

def main():
    text = input("type your message")
    shift = int(input("type the number of characters to shift message by"))
    encrypt(text, shift)

def other_function():
    text = 'random_text'
    shift = random.randint(1, 26)
    encrypt(text, shift)

现在 ALPHABET 是全局的,因为它是一个常量。而 textshift 是局部变量(在 mainother_function 中),因此需要将它们传递给 加密

关于python - 关于python函数和变量访问的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76488895/

相关文章:

python - 信号 fft 的错误幅度

python - 带有尾部斜杠的 Flask POST

python unicode在用作字符串时而不是在打印时转换为原始文本字符

function - 将 scala 代码概括为函数

c++ - 在 DLL 中调用非导出函数

python - Excel 分隔文件

Javascript 的使用,这些评论是好的还是矫枉过正?

c - 如何在 C 程序任务中创建 "twirly"?

c - 从同一编译单元覆盖 C 中的函数调用

python - Mac Lion : Issue with opencv and python 2. 7.5