Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python programming beginner difficulties

I am trying to write a program in Python, but I am stuck in this piece of code:

def function():
    a=[3,4,5,2,4]
    b=1
    c=0
    for x in range(5):  
        if a[x-1]>b:
            c=c+1
        return c


print(function())

It gives me value 1 instead of 5. Actually the function I am trying to write is a little bit more complicated, but the problem is actually the same, it doesn't give me the right result.

def result():
    r=[0]*len(y)
    a=2
    b=an_integer
    while b>0:
         for x in range(len(y)) :
             if y[x-1] > 1/a and b>0:
                r[x-1]=r[x-1]+1
                b=b-1
                a=a+1

    return r

    print(result())

v is a list of values smaller than 1 and b has an integer as value. If some values x in v are bigger than 1/a then the values x in r should get 1 bigger, then it should repeat a=a+1 until b becomes 0. I want this function to give a result of the type for ex. [7,6,5,4,3] where the sum of the elements in this list is equal to b.
Sometimes it gives me the right value, sometimes not and when the elements in v are equal for example v=[0.33333,0.33333,0.33333] it gets stuck and doesn't give me a result.

I don't know what I am doing wrong !

like image 258
buster Avatar asked Oct 24 '13 21:10

buster


People also ask

How difficult is Python For Beginners?

Is Python hard to learn? Python is actually one of the best programming languages for beginners. Its syntax is similar to English, which makes it relatively easy to read and understand. With some time and dedication, you can learn to write Python, even if you've never written a line of code before.

Is Python suitable for beginner?

Python can be considered beginner-friendly, as it is a programming language that prioritizes readability, making it easier to understand and use. Its syntax has similarities with the English language, making it easy for novice programmers to leap into the world of development.

Why Python is so difficult?

If you're just starting out with programming, Python can be hard... but that's mainly because programming is hard. When I first decided to teach myself programming, I tried starting with Python. I used a beginner book (think it was a "Head First").


1 Answers

Your return statements are incorrectly indented. You want to return after the loop ends, not inside the loop.

def function():
    a = [3, 4, 5, 2, 4]
    b = 1
    c = 0
    for x in range(5):  
        if a[x-1] > b:
            c = c + 1
    return c

Also, a couple of optimizations to the code:

def function(a, b):
    c = 0
    for x in a:
      if x > b:
         c += 1
    return c

or further:

def function(a, b):
    return sum(x > b for x in a)
like image 93
Lev Levitsky Avatar answered Sep 20 '22 23:09

Lev Levitsky