首页 > 解决方案 > 编写一个从 Swift 到 Python 的基本学校作业示例,但在简化方面遇到了麻烦

问题描述

我从学校学习编码。上个学期学了 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 中一样使用它们,那么我不会有任何问题,但多亏了这一点,我不得不重复相同的代码行。

标签: pythonpython-3.x

解决方案


您的 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 )

推荐阅读