在python中使用if-else函数缩短代码



虽然我很抱歉标题很糟糕,但这是我目前正在努力解决的问题

我当前的代码很难看

morality = 0
test = input("You see someone by a cliff, do you:n1.Warn them about getting too closen2.Push them offn")
if test == "1":
morality = morality + 1
elif test == "2":
morality = morality - 1
test = input("A child drops its icecream, do you:n1.Console the childn2.Laugh and mock the childn")
if test == "1":
morality = morality + 1
elif test == "2":
morality = morality - 1
test = input("You are given immunity and a gun, do you:n1.Kill someonen2.Not kill someonen")
if test == "1":
morality = morality + 1
elif test == "2":
morality = morality - 1
test = input("You are given the cure to aids, do you:n1.Cure aidsn2.Destroy the curen")
if test == "1":
morality = morality + 1
elif test == "2":
morality = morality - 1
if morality == -4:
print("You absolute evil man")
elif morality == -1 or morality == -2 or morality == -3:
print("you kinda evil man")
elif morality == 1 or morality == 2 or morality == 3:
print("You kinda nice")
elif morality == 4:
print("pretty nice person aint ya")

它本应是一个道德体系的草案,但它庞大而混乱的

我试着创建一个叫做道德的函数

def moral():
if test == "1":
morality = morality + 1
elif test == "2":
morality = morality - 1

但有一个原因我不知道,这不起作用。我用Pycharm和Pycharm只是有点灰色的第一道德。没有错误消息或任何东西,只是变灰

基本上,我想美化我的代码,但我不知道如何

您有了一个良好的开端:函数在缩短代码方面极其重要,也是大多数程序成功的基础。

moral()函数有两个主要问题,这两个问题是相辅相成的。函数有一个局部作用域,因此除非变量被声明为global,否则它们不能访问作用域之外的变量。注意,不鼓励使用global关键字,因为它会使代码难以理解,并且随着项目的扩展,它会使函数产生可能不必要的副作用,从而使代码变得越来越混乱。在你的代码中,你不会初始化道德测试(可能是它变灰的原因(,但你会尝试访问和修改它。

def moral(test):
if test == "1":
return 1
elif test == "2":
return -1

在上面,moral()取一个参数"0">测试";你可以在测试结果中通过。然后,您可以使用该函数的返回值轻松地递增变量。

例如:

morality = 0
test = input("You are given the cure to aids, do you:n1.Cure aidsn2.Destroy the curen")
morality += moral(test)

在美化代码方面,由于您有一个重复的操作,您可以简单地创建一个所有提示的列表,然后通过迭代提示用户的输入。

tests = [
"You see someone by a cliff, do you:n1.Warn them about getting too closen2.Push them offn",
"A child drops its icecream, do you:n1.Console the childn2.Laugh and mock the childn",
"You are given immunity and a gun, do you:n1.Kill someonen2.Not kill someonen",
"You are given the cure to aids, do you:n1.Cure aidsn2.Destroy the curen"
]
morality = 0
for test in tests:
answer = input(test)
morality += moral(answer)

最新更新