python - 如何在新函数中调用 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
. 这使它避免了郁金香。我知道这不是最美丽的解决方案,但它确实奏效了。=)
但是如何将这段代码放入一个函数中,以便每次我想使用它时都可以调用它呢?
这个问题可能很难回答,但请告诉我,我会尽力改进我的问题,以便可以理解。
解决方案
我不完全确定我是否正确回答了您的问题,但我相信您可以将 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 。
请让我知道这是否是您要查找的内容,或者我是否应该编辑任何内容。
推荐阅读
- java - Mac上有_JAVA_OPTIONS吗?
- python - fromkeys 方法的意外结果
- swift - SwiftUI - 数组中只有一个对象属性为真
- c++ - Qt Quick2 为单例类类型创建 qmlRegisterSingletonType
- python - 使用 pandas 对行进行子集化
- android - 如果 edittext 在 TextInputlayout 内,将 drawableLeft 添加到 EditText 会使提示向右移动。当 proguard 启用时
- python - 用户存在但无法使用 simpleJWT 和 Django Admin 进行身份验证
- python - 计算 df 的平均值,但如果 =>1 的值与该平均值相差 >20%,则平均值设置为 NaN
- c# - 如何为 ASP.NET Core API 设置 OAuth2 不记名令牌?
- javascript - js转义特殊字符