From the documentation,
The arguments to the range constructor must be integers (either built-in int or any object that implements the index() special method). If the step argument is omitted, it defaults to 1. If the start argument is omitted, it defaults to 0. If step is zero, ValueError is raised.
# Start at 0, stop before 10, Step size omitted so default step size: 1
for i in range(0, 10):
print(i)
# Output: 0 1 2 3 4 5 6 7 8 9 (printed on separate lines)
# Start omitted, so default start: 0, stop before 10,
# Step size omitted so default step size: 1
for i in range(10):
print(i)
# Output: 0 1 2 3 4 5 6 7 8 9
# Start at 0, Stop before 10, Step size: 2
for i in range(0, 10, 2):
print(i)
# Output: 0 2 4 6 8
# Start at 0, Stop before 10, Step size: 3
for i in range(0, 10, 3):
print(i)
# Output: 0 3 6 9
In the snippet you posted, the variable y
outside the function and the parameter y
of the function have different scope and don’t refer to the same thing (even though they are both named y
). The parameter y
of my_function
is local to the function whereas y=(2,4,5,6,7,9)
is a tuple at the global scope.
Basically, the parameter y
in def my_function(y)
says that whatever input/data(argument) is passed to the function, we are going to assign it to a a variable named y
. Within the body of the function, we are going to manipulate/use the input by using the variable y
. We don’t care about what the input is named outside the function. This abstraction allows us to pass different inputs to the function without need of editing the function.
# y = (2,4,5,6,7,9) will also work.
# I am just using x to avoid confusion
x = (2,4,5,6,7,9)
def my_function(y):
for i in range(0, len(y), 2):
print(y[i])
# Function call with x being passed as the argument.
my_function(x)
#########################
# Output: 2 5 7 (on separate lines)
#########################
# Within the function, the input x = (2,4,5,6,7,9) will be
# assigned to the parameter y.
# In the body of the function, y will refer to the input
# regardless of the fact that it is named x outside the function.
# Since step size of 2 was specified, so the 0th, 2nd and 4th elements
# will be printed i.e. 2, 5 and 7 will be printed.
# (Outside the function, instead of x we could have used y as the variable name
# i.e. y = (2,4,5,6,7,9) in which case we would make the function call
# my_function(y). Within the function, we will assign this tuple to the
# parameter (local to the function) named 'y'. The input can be named
# x,y, myVar, whatever outside the function. But, once the input is passed
# to the function, it will be assigned to the parameter y)
In the snippet you posted, you made the function call
my_function(range(0,6,2))
You are passing the sequence 0, 2, 4 as the input to my_function
. In the function, this sequence will be assigned to the parameter y
. Within the body of the function, whenever you use y
in your code, it will refer to the input sequence, not to the global variable.