【问题标题】:Values stored in variables dont carry over from one function to another存储在变量中的值不会从一个函数传递到另一个函数
【发布时间】:2021-08-14 08:42:12
【问题描述】:
def q1():
  type = str(input("Does your powers work with heat or cold or both? "))
  key = 0
  if type == "H":
    name1 = "Fire"
    key = 1
    q2a()

  if type == "C":
    name1 = "Ice"
    key = 1
    q2b()

  if type == "B":
    name1 = "Both"
    key = 1
    q3()

  elif key == 0:
    print("Oops, please enter H, C or B")
    q1()

def q2():
  print(name1)

我正在创建一个代码来根据用户输入的值生成一个超级英雄的名字。我的问题是,如果一个变量被分配了一个值,如果在单独的函数中使用相同的变量,为什么该变量不保留该值?

【问题讨论】:

  • 使用参数..简单
  • @chowman01 但是你想做什么?首先调用哪个函数。

标签: python python-3.x list python-2.7


【解决方案1】:

我认为有一些问题需要解决,并不是所有的问题都与代码有关。

如果有人问:“你的能力是在热还是冷或两者的情况下工作?”如何知道预期会出现“F”、“C”或“B”?为什么不接受“热”、“冷”、“两者”作为答案?

这条 if-s 链很难维护或更改。更简单的方法是为权力创建映射(注意我对前面表达的必要性的怀疑):

powers_mapping = {'H': 'Fire',
                  'C': 'Ice',
                  'B': 'Both',
                 }

现在可以编写简单的验证函数来获得用户的权力。为了控制程序流程而不是打印它返回验证值:

def validate(question, **kwargs):
    while (answer := input(question).upper()) not in kwargs:
        print(f'Expected one of {", ".join(kwargs)} but you entered {answer!r}')
    return kwargs[answer]

现在可以这样使用:

print(validate('Enter your power ...', **powers_mapping))

这种方法的优点是,如果需要更新/更改/添加权限,那么您可以在power_mapping 中进行操作,一切正常。

我向用户提出了... 的问题。它应该替换为映射中的值,而不是手动输入(一种可能是 f-string 和 power_mappings.values() 的组合)。

validate 函数足够通用,它也可以用于验证其他映射(武器?)。如果不需要,可以省略**kwargs,直接访问powers_mapping

还应注意,由于walrus operator,需要3.8

【讨论】:

    【解决方案2】:

    变量name1 是函数中的局部变量。您将需要使用 global 使其可作为函数外部的全局变量访问。

    name1 = 'blank'
    
    def q1():
      global name1
      type = str(input("Does your powers work with heat or cold or both? "))
      key = 0
      if type == "H":
        name1 = "Fire"
        key = 1
        q2()   #I edited this
    
      if type == "C":
        name1 = "Ice"
        key = 1
        q2()   #I edited this
    
      if type == "B":
        name1 = "Both"
        key = 1
        q2()   #I edited this
    
      elif key == 0:
        print("Oops, please enter H, C or B")
        q1()
    
    def q2():
        print(name1)
    
    q1()
    

    输出是

    Does your powers work with heat or cold or both? C
    Ice
    

    编辑:感谢@rudolfovic 不鼓励使用全局变量,请参阅帖子Why are global variables evil?

    因此,您也可以使用所需的值作为参数调用下一个函数

    def q1():
      type = str(input("Does your powers work with heat or cold or both? "))
      key = 0
      if type == "H":
        name1 = "Fire"
        key = 1
        q2(name1)   #call next function with desired value
    
      if type == "C":
        name1 = "Ice"
        key = 1
        q2(name1)   #call next function with desired value
    
      if type == "B":
        name1 = "Both"
        key = 1
        q2(name1)   #call next function with desired value
    
      elif key == 0:
        print("Oops, please enter H, C or B")
        q1()
    
    def q2(name1):
        print(name1)
    
    q1()
    

    输出

    Does your powers work with heat or cold or both? H
    Fire
    

    【讨论】:

    • 一般不鼓励使用全局变量。这个值应该简单地由函数返回。
    • 感谢@rudolfovic,很好。我已将您的 cmets 添加到答案中
    【解决方案3】:

    您可以使用global,但这将是一种反模式。而是在函数末尾返回值,然后返回 print(q1())。根本不需要q2

    def q1():
      type = str(input("Does your powers work with heat or cold or both? "))
     
      if type == "H":
        return 'Fire'
    
      if type == "C":
        return 'Water'
    
      if type == "B":
        return "Both"
    
      print("Oops, please enter H, C or B")
      return q1()
    
    name = q1()
    print(name)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多