相关疑难解决方法(0)

在函数中使用全局变量

如何在函数中创建或使用全局变量?

如果我在一个函数中创建一个全局变量,我如何在另一个函数中使用该全局变量?我是否需要将全局变量存储在需要访问的函数的局部变量中?

python scope global-variables

2939
推荐指数
22
解决办法
307万
查看次数

退货声明的目的是什么?

什么是return语句的简单基本解释,如何在Python中使用它?

它和print声明有什么区别?

python printing return

79
推荐指数
8
解决办法
56万
查看次数

Python - 函数输出?

我有一个非常基本的问题.

假设我调用一个函数,例如,

def foo():
    x = 'hello world'
Run Code Online (Sandbox Code Playgroud)

如何让函数以这样的方式返回x,我可以将它用作另一个函数的输入或者在程序体内使用变量?

当我使用return并在另一个函数中调用该变量时,我得到一个NameError.

python function

10
推荐指数
2
解决办法
7万
查看次数

在Python中调用一个函数的变量到另一个函数

我正在编写一个程序来通过python发送电子邮件.我有不同的def,它包含包含电子邮件用户名和电子邮件密码等的变量.然后我有另一个def实际发送电子邮件,但它需要包含电子邮件用户名和密码等的变量.我怎么能调用来自不同def的变量?抱歉这个怪异的措辞.我不知道怎么说:P谢谢!

def get_email_address():
    #the code to open up a window that gets the email address
    Email = input
def get_email_username():
    #the code to open up a window that gets email username
    Email_Username = input

    #same for the email recipient and email password

def send_email():
    #here I need to pull all the variables from the other def's
    #code to send email
Run Code Online (Sandbox Code Playgroud)

python

9
推荐指数
1
解决办法
4万
查看次数

如何在另一个函数中访问一个python函数中的变量

我编写了几个函数来计算样本响应的 NPS 和误差幅度。

我不想从第一个函数返回结果,然后将它传递给另一个函数以便能够使用它们。

所以我希望创建全局变量,这些变量可以在它创建的函数之外使用,以便它可以在其他函数中使用而无需传递它们。

但它似乎抛出错误。知道如何实现这一目标吗?我不想使用类并将这些变量作为类变量。

def nps_score(responses): 
    """Function to get the NPS score from the 
     Survey responses 

    """
    global sample_size = len(responses)
    global promoters_proportion = sum([1 for x in responses if x >=9])/sample_size
    global detractors_proprotion= sum([1 for x in responses if x<=6])/sample_size

    global sample_NPS= promoters_proportion - detractors_proportion

    print("Sample Net Promoter Score(NPS) is {} or {}%".format(sample_NPS,sample_NPS*100))



def moe():
    """ Calculate the margin of error
    of the sample NPS 

    """

    # variance/standard deviation of the sample NPS using 
    # Discrete random …
Run Code Online (Sandbox Code Playgroud)

python

3
推荐指数
1
解决办法
1万
查看次数

使用 Python 中其他函数的变量

我正在学习 python,目前正在编写一个必须分为函数的简单程序。我的问题是我有一个函数应该返回四个不同变量的字符串,然后应该在另一个函数中使用它们。

例如

def function1():
   var1 = input("Write something: ")
   var2 = input("Write something: ")
   var3 = input("Write something: ")

def function2():
   print(var1)
   print(var2)
   print(var3)

function1()
function2()
Run Code Online (Sandbox Code Playgroud)

由于 var1 未在 function2 的框架中定义,因此会给出错误消息。这应该如何解决呢?为了清楚起见,插图非常简化,但如果需要,我可以发布更具体的内容。

python

2
推荐指数
1
解决办法
3万
查看次数

如何使用其他函数的变量?

这是我的代码:

def Area():
    area = pi * radius * radius
    pi = 3.14
    radius = diameter * 2

def cost():
    diameter = eval(input("diamater: "))
    print ("Area is", area)
cost()
Run Code Online (Sandbox Code Playgroud)

它说区域没有定义,但我有一个名为area的变量!

python

1
推荐指数
1
解决办法
1万
查看次数

标签 统计

python ×7

function ×1

global-variables ×1

printing ×1

return ×1

scope ×1