【问题标题】:Python using "global" in function to return new variablePython 在函数中使用“全局”返回新变量
【发布时间】:2013-08-17 05:10:23
【问题描述】:

我在编程和通过LPTHW 工作方面相对较新。我想构建一个函数来检查 raw_input() 是否为数字,然后返回 float(input) 或如果不是数字则仅返回原始输入。

我已经确定 input.isdigit() 是一个可接受的函数,但现在我正在努力构建在 if 语句编译后实际返回变量的函数。我相信使用 global 功能会对我有所帮助,但是在阅读了一些帖子之后,听起来 global 并不是非常“有效”的工具。

这是我迄今为止所拥有的。

def Number_Check(input):
    global input
    if input.isdigit():
        input = float(input)
    else:
        input = input

在 shell 中运行它会给我错误:

SyntaxError: name 'input' is local and global (ex36.py, line 19)

非常感谢您对此的任何帮助。

【问题讨论】:

  • 将签名从def Number_Check(input)更改为def Number_Check(),或者如果是不同的变量,只需重命名即可。
  • 你绝对不需要全局的

标签: python python-2.7 global


【解决方案1】:

忘记global,这里不需要;仅当您想在不同的函数调用之间共享状态时才需要全局。由于 input 的值对于调用来说总是新的,global 绝对是您应该使用的。请尝试以下方法

def number_check(input):
    """
    if the given input can be converted to a float, return
    the float, otherwise return the input as a string unchanged.
    """
    try:
        return float(input)
    except ValueError:
        return input

# and use like this:

string = raw_input()
number_or_string = number_check(input)

【讨论】:

    【解决方案2】:

    您的代码中有两个输入。一个是参数,另一个是全局变量。编译器不知道您指的是哪一个。也许更改其中之一的名称?

    input = input
    

    这没有任何意义。你是想说输入保持不变吗?然后只需删除 else 部分!而且你不需要全局变量。可以直接返回值!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-11
      • 1970-01-01
      • 2012-05-22
      • 1970-01-01
      • 1970-01-01
      • 2020-04-22
      相关资源
      最近更新 更多