Printing out a list item by item in a function


#1

n = [3, 5, 7]

for i in range(0, len(n)):
    print n[i]
n = [3, 5, 7]

def print_list(x):
    for number in x:
        print number

print_list(n)

I have this now and it gives me the answer, but also gives me the error code.

Oops, try again. The body of your function should not contain any references to 'n'


#2

You are making this more complicated than it needs to be, for one you only need one for loop and to print items in a list one by one the syntax is just,

example_list = [2,1,3,4,5]

 for i in range(0, len(example_list)):
        print example_list[i]
#This code would print each item one by one

So to turn this into a function would be very simple because functions are basically blocks of code that are made reusable,

example_list = [1,23,4,5,3]

def example_func(example)
    for i in range(0, len(example)):
        print example[i]
example_func(example_list)

#3

   for i in range(0, len(x)):

so is this the function then?


#4

Yes, that would be how you would write it in your function. :slight_smile:


#5

Hi

I have written the following code, yet I still get an error "Oops try again. The body of your function should not contain any references to 'n'"

n = [3, 5, 7]

for i in range(0, len(n)):
print n[i]

def print_list(x):
for i in range(0, len(x)):
print x[i]

print_list(n)

I can't see any reference to 'n' in my function. Can somebody explain to me why the code is running but I get this error?


#6

okay what exercise are you on?


#7

you know what! I'm on that exercise too! cannot get past it!


#8

n = [3, 5, 7]

def print_list(x):
for i in range(0, len(x)):
print x[i]
print_list(n)

This code will work. The last line of code could be either print print_list(n) or just print_list(n). It will work. Just did it.


#9

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.