我从学校学习编码。上个学期学习Python,与它没有很好地融合,但我想学习它。在这个学期学习Swift并且它是有意义的,所以我一直在尝试使用我在Swift中学到的东西来理解Python。到目前为止,这种方法一直在帮助我。
我所做的一个Swift任务是制作一个简单的程序来在飞镖游戏中得分。它如下:
//Swift example
var myTotalScore = 501
var roundDartPoints = 0
var hisTotalScore = 501
roundDartPoints += 6
roundDartPoints += 8
roundDartPoints += 9
var hisDarts = 17+19+32
func resetRoundScore() {
roundDartPoints = 0
hisDarts = 0
}
func addAllToTotal() {
myTotalScore -= roundDartPoints
hisTotalScore -= hisDarts
}
addAllToTotal()
print("You don't seem to be any good at this. You're only at \(myTotalScore) points. I'm already at \(hisTotalScore).")
resetRoundScore()
roundDartPoints += 9
roundDartPoints += 8
roundDartPoints += 12
hisDarts = 43+29+18
addAllToTotal()
print("Ha! It's almost like you're this bad on purpose. You'll lose for sure now. You're at \(myTotalScore) points and I'm at \(hisTotalScore).")
resetRoundScore()
roundDartPoints += 60
roundDartPoints += 60
roundDartPoints += 60
hisDarts = 22+30+3
addAllToTotal()
print("Oh. I get it now: you were going easy on me. \(myTotalScore) to \(hisTotalScore). Good game!")
我试图在Python中做同样的事情,但是无法将分数添加到总数并重置飞镖计数。我用了def函数。这不起作用,因为在该结构中定义的内容似乎不可用于它之外。
所以,我在Python 3中复制了这个任务,我知道如何:
#python example
myTotalScore = 501
roundDartPoints = 0
hisTotalScore = 501
roundDartPoints += 6
roundDartPoints += 8
roundDartPoints += 9
hisDarts = 17+19+32
myTotalScore -= roundDartPoints
hisTotalScore -= hisDarts
print(f"You don't seem to be any good at this. You're only at {myTotalScore} points. I'm already at {hisTotalScore}.\n")
roundDartPoints = 0
roundDartPoints += 9
roundDartPoints += 8
roundDartPoints += 12
hisDarts = 43+29+18
myTotalScore -= roundDartPoints
hisTotalScore -= hisDarts
print(f"Ha! It's almost like you're this bad on purpose. You'll lose for sure now. You're at {myTotalScore} points and I'm at {hisTotalScore}.\n")
roundDartPoints = 0
roundDartPoints += 60
roundDartPoints += 60
roundDartPoints += 60
hisDarts = 22+30+3
myTotalScore -= roundDartPoints
hisTotalScore -= hisDarts
print(f"Oh. I get it now: you were going easy on me. {myTotalScore} to {hisTotalScore}. Good game!")
编辑:对不起,我刚才意识到我发送的太快了。
所以我的问题如下:我能做些什么来简化它?如果我可以在Python中定义函数并像在Swift中那样使用它们,我就没有问题,但是由于我必须重复相同的代码行。
你的python函数要么明确地说它使用global
变量,要么return
值。
例如,使用全局变量:
def resetRoundScore():
global roundDartPoints, hisDarts
roundDartPoints = 0
hisDarts = 0
def addAllToTotal():
global myTotalScore, hisTotalScore, roundDartPoints, hisDarts
myTotalScore -= roundDartPoints
hisTotalScore -= hisDarts
并返回:
def tallyScore( my_points, his_points, my_score, his_score ):
my_score -= my_points
his_score -= his_points
return my_score, his_score
...
myTotalScore, hisTotalScore = tallyScore( roundDartPoints, hisDarts, myTotalScore, hisTotalScore )