为什么我的running_profit变量没有更新?

时间:2020-09-14 22:33:36

标签: python variables

我正在尝试创建一个Martingale博彩模拟器。我的全局“ running_profit”变量应该由“ change_running_total”函数间接更新。 running_total变量正在正确更新,但是受running_total影响的running_profit变量未更新。

import random

round_n = 0
bet = 25
starting_funds = 5000
running_total = starting_funds
running_profit = running_total - starting_funds
goal_profit = 5000
wins = 0
losses = 0
rng_v = 0.00


def rng():
    """Generates random number"""
    global rng_v
    rng_v = random.random()


def winloss_generator():
    """Generates win/loss condition"""
    global rng_v
    if rng_v <= .49:
        return 'win'
    else:
        return 'loss'


def increase_winloss():
    """Increases wins or losses variable based on winloss_generator output"""
    global wins
    global losses

    if winloss_generator() == 'win':
        wins += 1
        return 'win'
    elif winloss_generator() == 'loss':
        losses += 1
        return 'loss'
    else:
        print('error')


def increase_round():
    """Increases round number by 1"""
    global round_n
    round_n += 1
    print('round: ', round_n)


def change_running_total():
    """Increases or decreases running_total based on winloss_generator"""
    global running_total
    if winloss_generator() == 'win':
        running_total += bet
    elif winloss_generator() == 'loss':
        running_total -= bet
    else:
        print('error')


def print_current_record():
    """Prints current win/loss record to screen"""
    print('Current Record: ', wins, 'wins, ', losses, 'losses')


def print_winloss():
    """Prints win/loss condition to screen"""
    print(winloss_generator(), 'print_winloss'.upper())


def print_profit():
    """Print running profit to screen"""
    print(running_profit, 'print_profit (variable)'.upper())
    print(running_total - starting_funds, 'print_profit (calculated)'.upper())


def return_current_funds():
    """Returns running total of funds"""
    global running_total
    return running_total


for x in range(5):
    increase_round()
    rng()
    print(rng_v, 'rng_v'.upper())
    print(winloss_generator(), 'winloss_generator'.upper())
    print(increase_winloss(), 'increase winloss'.upper())
    print_winloss()
    change_running_total()
    print(running_total, 'running total'.upper())
    print_profit()
    print()
print_current_record()

1 个答案:

答案 0 :(得分:0)

您在顶部声明变量:

running_profit = running_total - starting_funds

但是,此行仅运行一次;您并未在此处建立某种关系,只要您更改running_totalstarting_funds,它就会自动更新。如果要这样做,请改为将其转换为函数:

def running_profit():
    global running_total, starting_funds
    return running_total - starting_funds

现在,每次调用running_profit()时,它将根据这些变量的当前值进行计算。

旁注,而不是使用全局变量来完成所有这些操作,最好将其封装到一个类中。