简体   繁体   English

Python函数变量:局部和全局

[英]Python Function variable: local and global

I am struggling with local and global variables. 我正在努力应对局部和全局变量。

I was doing this: 我正在这样做:

def SomeFunc(Input):
    if Input == 1:
        Input = "True"
    elif Input == 0:
        Input = "False"

RawInput=int(raw_input("Input 1 or 0: "))
SomeFunc(RawInput)
print str(RawInput)

and it showed this: 它显示了这一点:

>>> def SomeFunc(Input):
    if Input ==1:
        Input = "True"
    elif Input ==0:
        Input = "False"

>>> RawInput = int(raw_input("Input 1 or 0: "))
Input 1 or 0: 1
>>> SomeFunc(RawInput)
>>> print str(RawInput)
1

What should I do so that the input will convert to str in the function? 我应该怎么做才能使输入在函数中转换为str?

Input is an int which is an immutable object. 输入是一个int ,它是一个不可变的对象。 In other words, you can't change it anywhere. 换句话说,您无法在任何地方进行更改。 However, you can assign it to something else. 但是,您可以将其分配给其他对象。 One of the tricky things about python is learning that everything is just a reference. 关于python的棘手事情之一是学习一切都只是参考。 When you assign to something, you just change the reference. 分配给某物时,只需更改参考。 Think about your variables as strings which go into boxes. 将变量视为放入框中的字符串。 When you assign to a variable, you put that string in a particular box. 当您分配一个变量时,您将该字符串放在特定的框中。 When you assign that variable to something else, you change the box that string goes to. 当您将该变量分配给其他变量时,将更改字符串所在的框。 Of course, when you actually do an addition, you add the contents of the box, not the strings (which is a little confusing). 当然,当您实际进行加法时,您将添加框的内容,而不是字符串(这有点令人困惑)。 If you're accustomed to programming in C, it's kind of like everything is a pointer which gets automatically dereferenced (except when you do an assignment). 如果您习惯于使用C进行编程,则就像一切都是一个指针,该指针会自动取消引用(除非您进行赋值)。

So, what to do? 那么该怎么办? The easiest thing is to return the value from your function. 最简单的方法是从函数中return值。

def some_func(inpt):
    if inpt == 1:
        return "True"
    elif inpt == 0:
        return "False"
    else:
        raise ValueError("WHAT IS THIS GARBAGE? I SAID 0 OR 1!!!!") # ;^)

Now you can call your function as: 现在您可以将函数调用为:

processed_input = some_func(rw_inpt)

as a side note, your function can be condensed to: 作为旁注,您的功能可以浓缩为:

def some_func(inpt):
    return str(bool(inpt))

or 要么

def some_func(inpt):
    return "True" if inpt else "False"

Both of these pass (and return "True" if the user puts in any integer that isn't 0). 这两个都通过(如果用户输入不为0的任何整数,则返回"True" )。 If you really want to force the user to not put in something like "2", you can do: 如果您确实要强制用户不要输入“ 2”之类的内容,则可以执行以下操作:

def some_func(inpt):
    return {1:"True",0:"False"}[inpt]

But I wouldn't recommend that one... 但是我不推荐那个...

Basically you want the argument to be pass-by-reference, but that is not how Python works for basic datatypes. 基本上,您希望参数是按引用传递的,但这不是Python用于基本数据类型的方式。 The pythonic way of doing this is as following: 执行此操作的pythonic方法如下:

def some_func(input):
    if input == 1:
        return "True"
    elif input == 0:
        return "False"

And then 接着

raw_input = some_func(raw_input)

Note: You can just do this: print bool(int(raw_input("Input 1 or 0: "))) 注意:您可以执行以下操作: print bool(int(raw_input("Input 1 or 0: ")))

The more pythonic way of doing it would be as follows: 更加Python化的方式如下:

def some_func(x):
    if x == 1:
        return "True"
    elif x == 0:
        return "False"

x = int(raw_input("Input 1 or 0: "))
x = some_func(x)
print x

However if you did want to use global s you could do it like this but this is really hacky and it isn't one of the good coding practices that python promotes. 但是,如果您确实想使用global ,则可以这样做,但这确实很麻烦,而且它不是python提倡的良好编码实践之一。

def some_func():
    global x
    if x == 1:
        x = "True"
    elif x == 0:
        x = "False"

x = int(raw_input("Input 1 or 0: "))
some_func()
print x

Some other notes: Try not to use names like the bultins eg. 其他一些注意事项:尽量不要使用诸如bultins之类的名称。 Input and RawInput since it makes things unclear and mixes everything up. InputRawInput因为它使事情变得不清楚,并将所有内容混合在一起。

What should I do so that the input will convert to str in the function? 我应该怎么做才能使输入在函数中转换为str?

def SomeFunc(Input):
    as_string = str(Input)
    if Input == '1':
        Input = "True"
    elif Input == '0':
        Input = "False"

Note that python has a native boolean type, including the values True and False already. 请注意,python具有本地布尔类型,已经包含值TrueFalse You can use the integer value of Input as a condition all on its own. 您可以单独使用Input的整数值作为条件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM