Pass return as parameter for another function

Viewed 76

In the below code "roll_counts" has been used as a return for the first function and then as a parameter for the second function. my question is if I change roll_counts in second function's parameter to ABC and leave it roll_counts in the first function, the code will still work fine. i know roll_counts = 6 in parentheses but how? and why the result doesn't change when i i am new to python and programming, thanks in advance

import random as rd

def simulate_dice_rolls(N):
    roll_counts = [0,0,0,0,0,0]
    for i in range(N):
        roll = rd.choice([1,2,3,4,5,6])
        index = roll - 1
        roll_counts[index] = roll_counts[index] + 1
    return roll_counts

def show_roll_data(roll_counts):
    number_of_sides_on_die = len(roll_counts)
    for i in range(number_of_sides_on_die):
        number_of_rolls = roll_counts[i]
        number_on_die = i+1
        print(number_on_die, "came up", number_of_rolls, "times")

roll_data = simulate_dice_rolls(1000)
show_roll_data(roll_data)
2 Answers

roll_counts in show_roll_data(roll_counts) is the name of a parameter and is accessible throughout the scope of the show_roll_data function. Its value is passed in from roll_data in the call show_roll_data(roll_data), and has nothing to do with the local variable of the same name defined in simulate_dice_rolls. That's why you can rename roll_counts in show_roll_data to anything and it would still work.

blhsing 's answer is right. But before admitting that answer, you need to understand variable scope. There are global variables and local variables in python. And local variables are binded in functions. If there is same local variable to global variable in function, local variable is used without affection of global variable. Because roll_counts is local variable of simulate_dice_rolls, you don't need to consider roll_counts in show_roll_data.

Related