首页 > 解决方案 > 如何在新函数中调用 a 之外的函数并将参数的值添加到新变量中?

问题描述

我是 Python 和编码的新手,正在尝试学习,但我无法弄清楚或找到如何在外部调用函数并将其用于另一个函数的任何答案。我想运行该函数以获取我调用的函数的结果。我想将结果添加到已经是 INT 的变量中。

这是一个抛硬币游戏。如果用户的答案是正确的,则将 Money 加 10,如果答案无效,则减 10。

我试过了:

Money += flip_coin("hEADS!".title().strip("!?,. "),10)

this produces the following error message:

TypeError: unsupported operand type(s) for +=: 'int' and 'tuple'

这是我的代码。

def flip_coin(guess, bet):
  new_random = random.choice(ls)
  print("You guessed: {0}".format(guess))
  total = 0
  if bet > 0 and bet <= money:
    if (guess == new_random):
      total += bet
      return "Coin flip shows: {0}".format(new_random), "You won {0}".format(total)

我想要Money+=bet 另一个函数中的结果。

金钱是一个范围变量。

我试图这样调用函数,这是错误的:

def amt_money(new_money):
  money += flip_coin(guess, bet )
  return money

amt_money(bet)run 

这是正确的(我得到了这个并想在钱上加 10):

You guessed: Heads
('Coin flip shows: Heads', 'You won 10')

这是错误消息:

Traceback (most recent call last):
  File "script.py", line 32, in <module>
    amt_money(bet)
NameError: name 'bet' is not defined

如果:这是范围

Money = 100
ls = ["Heads", "Tails"]

我想要输出:如果他们赢了,则为 110,如果他们输了,则为 90。

result = flip_coin("heads".title().strip("!?,. "), 5)

tot = []
for res in result[1]:
  if res in result[1]:
    tot += result[1].split(' ')
money += int(tot[2])

我做了这样的事情,它奏效了,我粗暴地分解了字符串并索引了“赌注”并将其转换为 int 并将其添加到money. 这使它避免了郁金香。我知道这不是最美丽的解决方案,但它确实奏效了。=)

但是如何将这段代码放入一个函数中,以便每次我想使用它时都可以调用它呢?

这个问题可能很难回答,但请告诉我,我会尽力改进我的问题,以便可以理解。

标签: pythonpython-3.xfunction

解决方案


我不完全确定我是否正确回答了您的问题,但我相信您可以将 flip_coin 的返回值设为 int,您的代码会变得容易得多。

def flip_coin(guess, bet):
  new_random = random.choice(ls)
  print("You guessed: {0}".format(guess))
  total = 0
  if bet > 0 and bet <= money:
    if (guess == new_random):
      total += bet
      print("Coin flip shows: {0}".format(new_random), "You won {0}".format(total))
      return total # Total if it is correct
    return 0 # 0 if it's the wrong guess
  return -10 # -10 if it is invalid

对于最终的返回值,我不完全确定这是否是您正在寻找的。

从那里,您可以像这样编写 amt_money 函数:

def amt_money(guess, bet):
  global Money # Calls the global variable
  Money += flip_coin(guess, bet) # Add result to money
  return Money

我用我认为你想要的东西创建了一个Colab 。

请让我知道这是否是您要查找的内容,或者我是否应该编辑任何内容。


推荐阅读