14/18 Passing a range into a function


#1

what is the correct code for this?

def my_function(x):
for i in range(0, len(x)):
x[i] = x[i] * 2
return x
range(x)=[0,1,2]
print my_function(x)

above is not working


#2

def my_function(x):
for i in range(0, len(x)):
x[i] = x[i] * 2
return x

print my_function(range(0, 3, 1))


#3

def my_function(x):
for i in range(0, len(x)):
x[i] = x[i] * 2
return x

print my_function(range(3))

this works


#4

could you please explain why that worked? Thank you!!


#5

The range function actually generates a list of numbers . Run this code below to test it in the labs if you want

    #generate a list of numbers from 0 to 5-1 --> 4
    #The default increment is 1 in natural order
    print (range(5)) #[0, 1, 2, 3, 4]
    
    #generate a list of numbers starting from 1 to 5-1 --> 4
    #The default increment is 1 in natural order
    print (range(1,5)) #[1, 2, 3, 4]
    
    #generate a list of numbers starting from 1 to 10-1 --> 9
    #The increment is now 2 (as specified by the last argument)
    print (range(1,10,2)) #[1, 3, 5, 7, 9]

or go directly here
Click here to the labs


6/15 what is wrong?
#6

Cool Rydan, now I see.


#7

Hi @rydan the seconds print out is wrong... by the way, your example is better than the course :wink:

#generate a list of numbers starting from 1 to 5-1 --> 4
#The default increment is 1 in natural order
print (range(1,5)) #[1, 2, 3, 4]

#8

Yeah @mrugerio thanks for the pointer must have copied the wrong output there


#9

@felicity_johnson_mai

I guess the reason why a learner would have little issue on this lesson is cause, The instructions are not very clear.
The instructions makes it seem like your answe is suppose to be [0,1,2] meanwhile your output is should be [0,2,4]

1 -def my_function(x):
2- for i in range(0, len(x)):
3- x[i] = x[i]*2
4- return x

5- print my_function(range(0,3,1)) # Add your range between the parentheses!

print my_function(range(0,3,1)) = 0,1,2

To understand how this "start", "Stop", "Step" works, just revisit you "Arithmetic" and "Geometric" progression i mathematics.

@ Line 5 of the code, range(0,3,1) can be mathematically expressed => 0= 0;
0, (0+1) = 1;
1, (1+1) =2;
Therefore output = [0,1,2]
The output, multiplied by * 2 (code on line number 3) = [0,2,4].


#10