Genomics-CRT / Data-Science-For-Life-Science

CRT outreach program to assist life scientists in learning basic data science skills.
28 stars 44 forks source link

Python_troubleshooting #12

Closed LisaLombardi86 closed 4 years ago

LisaLombardi86 commented 4 years ago

Hi Stephen,

There is still one example of code block from last week that puzzles me (I am sorry I am only asking this now!)
I defined the add_one function as indicated, but the loops does not seem to be working. It only add +1 to the first item in the list. I am copy pasting it below.

def add_one(numbers):
    for i in range(0, len(numbers)):
        numbers[i] = numbers[i] + 1
        return numbers

yet_another_list = [1, 2, 3, 4, 5 , 6]

add_one(yet_another_list)

The loop itself is working (see below), but when I define it as a function something goes wrong.

for i in range(0, len(yet_another_list)):
        yet_another_list[i] = yet_another_list[i] + 1

I could use your help.. Thanks a million!!

Lisa

Genomics-CRT commented 4 years ago

Hi Lisa, Everything looks good except where you put the return statement, if you remember about indentation in python you will be able to fix this.

I'll explain what you have happening here

def` add_one(numbers):
    for i in range(0, len(numbers)):
        numbers[i] = numbers[i] + 1
        return numbers

Return should be after your for loop finishes. What is happening now is the for loop does one loop (the first item in your list) then return is triggered so that is what is being outputted from your function.

Change it to this:

def add_one(numbers):
    for i in range(0, len(numbers)):
        numbers[i] = numbers[i] + 1
    return numbers

and the for loop will finish running, the numbers list will finish being updated, and then the return statement will be triggered and output the completely updated list.

LisaLombardi86 commented 4 years ago

Hi Stephen, Yeah, I totally see it now.. Thanks a million for your help and your quick reply!