omics.co.in

Returning values from functions

Returning values from functions

In Python, functions can return values using the return keyword. The return statement is used to exit a function and return a value to the caller. Here is an example:

Pyton
				def square(x):
    return x ** 2

result = square(5)
print(result)

			

In this example, the square function takes a single argument x and returns the value of x squared using the ** operator. The function call square(5) returns the value 25, which is assigned to the variable result. The print statement then outputs the value of result, which is 25.

 

Functions can also return multiple values by returning them as a tuple. Here is an example:

Pyton
				def calculate_stats(data):
    mean = sum(data) / len(data)
    variance = sum((x - mean) ** 2 for x in data) / len(data)
    return mean, variance

sequences = ['ATCGCGTA', 'CGCGCGCG', 'ATCGATCG']
gc_contents = []

for seq in sequences:
    gc_count = seq.count('G') + seq.count('C')
    gc_content = gc_count / len(seq)
    gc_contents.append(gc_content)

#print(gc_contents)

mean_gc, var_gc = calculate_stats(gc_contents)

print("Mean GC content:", mean_gc)
print("Variance of GC content:", var_gc)

			

In this example, we first define the calculate_stats function that we can use to calculate the mean and variance of any list of numerical data.

 

We then define a list of DNA sequences and use a for loop to calculate the GC content of each sequence and append it to the gc_contents list. We then call the calculate_stats function on the gc_contents list to calculate the mean and variance of the GC contents, which are stored in the mean_gc and var_gc variables.

 

Finally, we print the mean and variance of the GC contents using the print function.

← Return to Home Hub Scroll to Top ↑