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

时间:2020-10-17 21:31:10

标签: python-3.x

尽管我很抱歉标题很糟糕,但目前我正遇到这个问题

我当前的代码很丑

morality = 0

test = input("You see someone by a cliff, do you:\n1.Warn them about getting too close\n2.Push them off\n")
if test == "1":
    morality = morality + 1
elif test == "2":
    morality = morality - 1

test = input("A child drops its icecream, do you:\n1.Console the child\n2.Laugh and mock the child\n")
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 someone\n2.Not kill someone\n")
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 aids\n2.Destroy the cure\n")
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只是使第一种道德变灰。 没有错误消息或任何东西,只是变灰了

基本上,我想美化我的代码,但是我不知道怎么做

1 个答案:

答案 0 :(得分:1)

您将有一个良好的开端:函数对于缩短代码极为重要,并且是大多数程序成功的基础。

moral()函数有两个主要问题,这两个问题并存。函数具有局部作用域,因此除非声明了变量global,否则它们将无法访问其作用域之外的变量。注意,不建议使用global关键字,因为它会使您的代码难以理解,并且随着项目的扩展而变得混乱,因为它允许函数产生可能的不良副作用。在您的代码中,您不会初始化道德 test (可能是为什么它变灰的原因),但是您尝试访问和修改它。

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

以上,moral()带有一个参数“ test ”,您可以在测试结果中传递该参数。然后,您可以轻松地使用该函数返回的值来递增变量。

例如:

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

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

tests = [
    "You see someone by a cliff, do you:\n1.Warn them about getting too close\n2.Push them off\n",
    "A child drops its icecream, do you:\n1.Console the child\n2.Laugh and mock the child\n",
    "You are given immunity and a gun, do you:\n1.Kill someone\n2.Not kill someone\n",
    "You are given the cure to aids, do you:\n1.Cure aids\n2.Destroy the cure\n"
]

morality = 0
for test in tests:
    answer = input(test)
    morality += moral(answer)
相关问题