如何将新的有价值的东西重新分配给变量

时间:2017-06-20 21:56:37

标签: python python-3.x variables

所以我创造了一个非常简单的功能,可以指定每天做一定数量的俯卧撑和仰卧起坐。代码如下:

import random

def exercise_rep_num():
    situps = random.randint(50,75)
    situps_feedback = 'You need to do %s situps today!' % situps
    print(situps_feedback) 

    pushups = random.randint(25,65)
    pushups_feedback = 'You need to do %s pushups today!' % pushups
    print(pushups_feedback)

    if situps >= 70:
        print("Making it easier...")
        pushups = random.randint(25,40)
        print(pushups_feedback)

    elif pushups >= 60:
        print("Making it easier...")
        situps = random.randint(30,60)
        print(situps_feedback)

    elif pushups >= 60 and situps >= 70:
        print("Making it easier... Hooray! No workout tofay :)")

exercise_rep_num()

我希望该功能能够改变" pushups_feedback"和" situps_feedback"值一旦" if语句"开始。例如,我得到了一个"仰卧起坐"值为71,所以俯卧撑值应该减少。但是,打印的功能" pushups_feedback"与之前相同的值。有什么建议?

2 个答案:

答案 0 :(得分:0)

您必须在更新金额后重新格式化字符串,因为字符串不“记住”替换为变量的变量。

pushups = random.randint(25,40)
print('You need to do %s pushups today!' % pushups)

您还可以定义一个类似的方法,为所有锻炼制作“快捷方式”

def feedback(workout, amt):
    return 'You need to do %d %s today!' % ( amt, workout)

然后

print(feedback('pushups', random.randint(25,40)))

答案 1 :(得分:0)

当您分配到pushups_feedback时,它会在当时将变量替换为模板。它不记得与变量的关系,因此重新分配变量并不会更新字符串。

您可以编写一个显示消息的函数,并在两个地方调用该函数。

def print_pushups(pushups):
    pushups_feedback = 'You need to do %s pushups today!' % pushups
    print(pushups_feedback)
def print_situps(situps):
    situps_feedback = 'You need to do %s situps today!' % situps
    print(situps_feedback)

def exercise_rep_num():
    situps = random.randint(50,75)
    situps_feedback = 'You need to do %s situps today!' % situps
    print(situps_feedback) 

    pushups = random.randint(25,65)
    pushups_feedback = 'You need to do %s pushups today!' % pushups
    print(pushups_feedback)

    if situps >= 70:
        print("Making it easier...")
        pushups = random.randint(25,40)
        print_pushups(pushups)

    elif pushups >= 60:
        print("Making it easier...")
        situps = random.randint(30,60)
        print_situps(situps)

    elif pushups >= 60 and situps >= 70:
        print("Making it easier... Hooray! No workout tofay :)")

exercise_rep_num()