簡體   English   中英

如何在python中的函數內創建模塊級全局變量

[英]How to create a module level global variable inside a function in python

我有一個名為functions的文件。 在這個文件中,我有以下代碼的功能

def converter(a):
    index = a.find(',')
    b = a[0:index]
    d = a[index + 1:]
    c1_1 = b.strip()
    c1_2 = d.strip()

現在我想將該函數導入另一個文件,然后我想對 c1_1 和 c1_2 變量應用一些條件,例如

from functions import converter
h = input("Type a command: ")
converter(h)
if c1_1 == 'a'
    print('something')

我已經嘗試過這種方法,但它不起作用

這不會直接回答您的問題,但您應該只返回值而不是依賴全局變量:

def converter(a):
    index = a.find(',')
    b = a[0:index]
    d = a[index + 1:]
    c1_1 = b.strip()
    c1_2 = d.strip()

    return c1_1, c1_2  # Return the values from the function 

. . . 

h = input("Type a command: ")
c1_1, c1_2 = converter(h)  # Then assign them here
if c1_1 == 'a' print('something'):

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM