在 Python 中如何返回上一行

82 阅读2分钟

在 Python 中,我们经常需要在循环或函数中重新分配变量。例如,在下面的代码中,我们定义了一个名为 train 的函数,该函数用于训练一个角色的力量和能量。

huake_00257_.jpg

def train(old_strength, old_energy):
    train = input("What would you like to do now?\n'strentgh' or 'rest'\n>")

    if train == 'strength':
        strength = old_strength + 10
        energy = old_energy - 10

        if energy <= 0:
            print("You do not have enough energy to do this.")

        else:
            pass

        print("You have gained 10 strength, and now have %d strength and %d energy left" % (strength, energy))
        old_strength = strength
        old_energy = energy
        train(old_strength, old_energy)

在这个函数中,我们首先询问用户想要进行哪种训练(力量训练或休息)。然后,根据用户的选择,我们重新分配变量 strengthenergy。如果用户选择力量训练,我们会增加角色的力量并减少角色的能量。如果用户选择休息,我们会保持角色的力量和能量不变。

我们希望这个函数能够反复执行,每次执行时都使用上一次训练后的力量和能量值。然而,在上面的代码中,当我们调用 train 函数时,我们总是使用初始的力量和能量值,而不是上一次训练后的值。这是因为我们在 train 函数中重新分配了变量 train,导致该变量的值从一个函数变为一个字符串。

  1. 解决方案

为了解决这个问题,我们可以使用另一个变量来存储用户的输入,而不是重新分配变量 train。例如,我们可以使用变量 choice 来存储用户的输入,如下所示:

def train(old_strength, old_energy):
    choice = input("What would you like to do now?\n'strentgh' or 'rest'\n>")

    if choice == 'strength':
        strength = old_strength + 10
        energy = old_energy - 10

        if energy <= 0:
            print("You do not have enough energy to do this.")

        else:
            pass

        print("You have gained 10 strength, and now have %d strength and %d energy left" % (strength, energy))
        old_strength = strength
        old_energy = energy
        train(old_strength, old_energy)

    elif choice == 'rest':
        print("You have chosen to rest.")

这样,当我们调用 train 函数时,我们可以使用变量 choice 来存储用户的输入,而不是重新分配变量 train。这样,我们就可以在每次调用 train 函数时都使用上一次训练后的力量和能量值。

以下是完整的代码示例:

def train(old_strength, old_energy):
    choice = input("What would you like to do now?\n'strentgh' or 'rest'\n>")

    if choice == 'strength':
        strength = old_strength + 10
        energy = old_energy - 10

        if energy <= 0:
            print("You do not have enough energy to do this.")

        else:
            pass

        print("You have gained 10 strength, and now have %d strength and %d energy left" % (strength, energy))
        old_strength = strength
        old_energy = energy
        train(old_strength, old_energy)

    elif choice == 'rest':
        print("You have chosen to rest.")

train(10, 50)

运行这段代码,你会发现每次调用 train 函数时,都会使用上一次训练后的力量和能量值。