我想知道是否有一种方法可以在代码中重复一个具有不同值的函数
我已经问过我的老师,在网上搜索过,问过一些同龄人,没有一个答案
while cashChoice > 0:
cash1 = 200 + int(offer1)*50
cashorBox = input("Would you like the money or the box? You have been offered $" + str(cash1) + ". If you want money, press [m], if you want the box, press [b]")
if cashorBox == "m":
print("Congratulations, you get " + str(cash1) + "! The prize you could've won from the box was " + str(userBox) + ". See you!")
sys.exit
elif cashorBox == "b":
print("Ok... you will be offered another cash amount.")
cashChoice -= cashChoice
if cashChoice == 0:
print("Great! You may have the box. It contains " + str(userBox) + "! Farewell :)")
sys.exit
else:
continue
我希望它重复,但是“ cash1”的值与“ cash2”中的值不同
答案 0 :(得分:1)
对此有一个非常简单的答案,以后知道是否希望精通Python将会非常重要。我不知道您到底想如何实现它,但是您可以这样做:
def yourFunction (cash1Param):
while cashChoice > 0:
cash1 = cash1Param
cashorBox = input("Would you like the money or the box? You have been offered $" + str(cash1) + ". If you want money, press [m], if you want the box, press [b]")
if cashorBox == "m":
print("Congratulations, you get " + str(cash1) + "! The prize you could've won from the box was " + str(userBox) + ". See you!")
sys.exit
elif cashorBox == "b":
print("Ok... you will be offered another cash amount.")
cashChoice -= cashChoice
if cashChoice == 0:
print("Great! You may have the box. It contains " + str(userBox) + "! Farewell :)")
sys.exit
else:
continue
然后,当您调用该函数时,可以为cash1Param输入任何值,例如:
yourFunction(5)
或
yourFunction(678678967)
您甚至不需要为所有内容使用cash1。您可以将使用它的所有时间都替换为cash1Param以直接使用该参数。
这些称为函数参数。以下是学习它们的相关链接:https://www.protechtraining.com/content/python_fundamentals_tutorial-functions
如果您还有其他问题,请不要害怕询问。