【问题标题】:Why are my python functions being called twice?为什么我的 python 函数被调用了两次?
【发布时间】:2019-10-24 00:10:31
【问题描述】:

我对 python 还很陌生,每当我运行我的脚本时,前两个函数 humanPlay()computerPlay() 都会被调用两次。我不想要这个。

我注意到,当我在 setRules() 函数中注释掉 draw 变量时,程序可以正常运行。我不确定为什么 f"{computerPlay()}"f"{humanPlay()}" 不打印返回值。

我还验证了py文件没有命名为Random,以防止模块自行导入。

import random


Player = "Player"
Computer = "Computer"
options = ["ROCK","PAPER","SCISSORS"]

def main():
    def humanPlay():
        response = input("Make a selection between Rock, Paper, Scissors: ", )
        response.upper()

        if response.upper() in options:
            print(response.upper())
            return response.upper()
        else:
            print(f"{response.upper()}, is not a valid selection")
            return humanPlay()

    def computerPlay():
         print(random.choice(options))
         return random.choice(options)

    def setRules():
        rockWin = "You Win! ROCK beats SCISSORS "
        paperWin = "You Win! PAPER beats ROCK "
        scissorsWin = "You Win! SCISSORS beats PAPER "
        draw = print("It's a Draw!, computer selected", f"{computerPlay()}", "and you selected", f"{humanPlay()}")
        #loser = print(f"You Lose! {humanPlay()}", f"can't beat {computerPlay()}")


    humanPlay()
    computerPlay()
    setRules()

main()

理想情况下,draw 变量应该类似于以下内容:

It's a Draw!, computer selected ROCK and you selected ROCK

注意:我仍然需要为程序编写逻辑才能知道石头、纸和剪刀之间的区别。

现在我只想返回正确的值,而不是整个函数。

【问题讨论】:

  • 它们运行两次,因为它们被调用了两次。您在main 的底部调用humanPlaycomputerPlay,然后在setRules 中再次调用它们。
  • 您调用humanPlay()computerPlay(),然后调用setRules(),它本身调用这两个函数。您需要调用它们一次,将它们的结果保存在变量中,然后将这些变量传递给setRules(),以便它可以使用它们。
  • f"{computerPlay()}"f"{humanPlay()}" 调用函数。我认为这不是您想要的,但解决方案并不完全清楚。请发minimal reproducible example
  • 顺便说一句,两次调用random.choice(options) 会产生两种不同的选择,你知道的,对吗?
  • main 结构不正确。这 3 个函数不属于 main。这三个函数中的每一个都应该做一些事情,它们应该从main 中调用,但不能驻留在那里。

标签: python python-3.x


【解决方案1】:
  • 如 cmets 中所述,函数在 main 内被调用两次
    • 一次在main的底部
    • 曾经在setRules
  • 函数不应驻留在main
  • 应从main 调用函数,并将值returned 存储为变量以在setRules 中使用
  • 逻辑未设置为在rockpaperscissor 之间确定获胜者
  • 有效的scope ofPlayerComputeroptions是全局的。
def humanPlay() -> str:
    response = input("Make a selection between Rock, Paper, Scissors: ", )
    response = response.upper()

    if response in options:
        print(response)
        return response
    else:
        print(f"{response}, is not a valid selection")
        return humanPlay()

def computerPlay() -> str:
    comp_choice = random.choice(options)
    print(comp_choice)
    return comp_choice

def setRules(comp_choice: str, human_choice: str):
    rockWin = "You Win! ROCK beats SCISSORS "
    paperWin = "You Win! PAPER beats ROCK "
    scissorsWin = "You Win! SCISSORS beats PAPER "
    draw = print("It's a Draw!, computer selected", f"{comp_choice}", "and you selected", f"{human_choice}")
    #loser = print(f"You Lose! {human_choice}", f"can't beat {comp_choice}")

Player = "Player"
Computer = "Computer"
options = ["ROCK","PAPER","SCISSORS"]

def main():

    h_choice = humanPlay()
    c_choice = computerPlay()

    setRules(c_choice, h_choice)

main()

【讨论】:

    【解决方案2】:

    问题在于您对 f 字符串插值和一般函数调用的解释。

    当您拥有some_func() 时,这将调用该函数(即其中的代码将被执行)。

    f-string 插值的工作原理是它里面的任何东西都会被执行,并且它的结果将被转换为字符串。

    因此,要修复(这方面)您的代码,您应该将humanPlay()computerPlay() 的结果收集到某个变量中,例如human_move = humanPlay() 然后将该值传递给setRules()(同时确保setRules() 实际接受该值)。

    【讨论】:

      【解决方案3】:

      您看到humanPlay()computerPlay() 被调用两次的原因是因为您是!
      当您在 setRules 中打印它们时:
      draw = print("It's a Draw!, computer selected", f"{computerPlay()}", "and you selected", f"{humanPlay()}") 您没有得到以前的结果,而是再次调用它们。

      我会将 humanPlay 和 computerPlay 的返回值分配给一些变量并将其传递给 setRules。

      import random
      
      
      Player = "Player"
      Computer = "Computer"
      options = ["ROCK","PAPER","SCISSORS"]
      
      def main():
          def humanPlay():
              response = input("Make a selection between Rock, Paper, Scissors: ", )
              response.upper()
      
              if response.upper() in options:
                  print(response.upper())
                  return response.upper()
              else:
                  print(f"{response.upper()}, is not a valid selection")
                  return humanPlay()
      
          def computerPlay():
               choice = random.choice(options)
               return choice
      
          def setRules(humanResult, computerResult):
              rockWin = "You Win! ROCK beats SCISSORS "
              paperWin = "You Win! PAPER beats ROCK "
              scissorsWin = "You Win! SCISSORS beats PAPER "
              print("It's a Draw!, computer selected", f"{computerResult}", "and you selected", f"{humanResult}")
              #loser = print(f"You Lose! {humanResult}", f"can't beat {computerResult}")
      
      
          hResult = humanPlay()
          cResult = computerPlay()
          setRules(hResult, cResult)
      
      main()
      

      【讨论】:

        猜你喜欢
        • 2019-12-31
        • 2013-01-12
        • 1970-01-01
        • 1970-01-01
        • 2015-07-26
        • 1970-01-01
        • 2012-08-02
        • 2011-09-04
        • 1970-01-01
        相关资源
        最近更新 更多