Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array in a program

So, first I like to state that I'm very new to Python, so this probably will be an easy question. I'm exercising my programming skills and am trying to write a simple program. It goes like this:

def cal(alpha, k):
    sqrt = np.zeros(len(alpha))
    for i in range(len(alpha)):
        sqrt[i] = np.sqrt(alpha[i])*k
        return sqrt

Which, for a certain alpha and k, should give me an array sqrt[]. For example, if alpha = [1,4,9] and k = 3, the answer should be [3,6,9]. However, when executed in Python, it gives [3,0,0].

My question is: why? I know I can get what I want if I simply put

 def cal(alpha, k):
     sqrt = np.zeros(len(alpha))
     sqrt= np.sqrt(alpha)*k
     return sqrt

but I want to know where my mistake in reasoning is.

Thanks!

like image 901
Riley Avatar asked Jul 13 '18 11:07

Riley


People also ask

How do you write an array in a program?

To create an array, define the data type (like int ) and specify the name of the array followed by square brackets []. To insert values to it, use a comma-separated list, inside curly braces: int myNumbers[] = {25, 50, 75, 100};

What is an example of an array?

An array is any arrangement in rows or columns. Cards laid out into rows to play Memory, seats arranged in rows for a recital, or numbers arranged in an Excel spreadsheet are all examples of arrays.


1 Answers

Indentation is important in Python. As soon as your function reaches the return statement, it will stop and return an object.

In your for loop, return is met at the end of the first iteration but before the start of the second, which is why you find only the first value filled in [3, 0, 0].

Therefore, simply unindent the last line. This will ensure return is only processed after your for loop is completed:

import numpy as np

def cal(alpha, k):
    sqrt = np.zeros(len(alpha))
    for i in range(len(alpha)):
        sqrt[i] = np.sqrt(alpha[i])*k
    return sqrt

cal([1, 4, 9], 3)

# array([ 3.,  6.,  9.])
like image 172
jpp Avatar answered Oct 10 '22 12:10

jpp