grindbert grindbert - 6 months ago 10
Python Question

Generating a List - nothing happens

i took a piece of code that generates a random gene sequence and i want to put n number of generated sequences into a list. this is what i came up with but i don't get anything when i run it. can somebody help?

import random

def generateSequence (n):

n = input('Enter # of list entries: ')
L = []
dna = ["A","G","C","T"]
for i in range(n):

random_sequence=''

for i in range(50):
random_sequence+=random.choice(dna)

L.append(random_sequence)

print(L)
return(L)


my second try before i received answers:

import random

def generateSequence (n):

L = []
dna = ["A","G","C","T"]
for i in range(n):

random_sequence=''

for i in range(50):
random_sequence+=random.choice(dna)

L.append(random_sequence)

print(L)
return(L)

b = input('Enter # of list entries: ')
generateSequence(b)

Answer

You forgot to actually call the function.

For example, if you put this in a file called main.py

import random

def generateSequence (n):

    n = input('Enter # of list entries: ')
    L = []
    dna = ["A","G","C","T"]
    for i in range(n):

        random_sequence=''

        for i in range(50):
            random_sequence+=random.choice(dna)

        L.append(random_sequence)

    print(L)
    return(L)


if __name__ == "__main__":
    generateSequence(3)

gives me the following output when I run it with python main.py

Enter # of list entries: 2
['GCTGTCTAAATTCGGCTTCACCTAGAAATGTTCAGATGAAATCCAGATGT', 'ACTAGGCGGTATGTTCAGAGCGAGTCGGCGGTTCCCTGGTGGGACTATCC']

Also, the argument of generateSequence is useless, because you reset its value in the function with the input call.

Edit For the TypeError, input will give you a str (string). You need an integer for the range function (https://docs.python.org/2/library/functions.html#range) so you will need to convert n first. For example for i in range(int(n))

Note that this assume that n can be converted to an integer. If not, int(n) will raise an exception. ValueError: invalid literal for int() with base 10: 'fefw'