Ben
Ben

Reputation: 79

debug of an function

The "Faculty " function, should return the faculty of the number it receives as a parameter. The faculty of a number n is 1 * 2 * 3 * 4 * ... * n. For example, faculty (5) should be 1 * 2 * 3 * 4 * 5 = 120. The function as it is written now always returns 0, no matter what number it receives as a parameter.

So, how do I fix the problem? (I'm just trying to learn, I'm new)

def faculty(integer):
    result = 1
    for i in range(integer):
        result *= i
    return result

Upvotes: 0

Views: 93

Answers (3)

azro
azro

Reputation: 54168

The method range(stop) generates the values [0;stop[ so you have the 0 which kill everything, and not stop. What you need is range(start, stop) with range(1, integer+1) to generates [1;value+1[

def faculty(integer):
    result = 1
    for i in range(1, integer+1):
        result *= i
    return result

When debugging, a nice way is in most time to use print to see what values are used to understand the behaviour of the code

Upvotes: 1

dheinz
dheinz

Reputation: 1096

The range statement takes a 0 as starting point. Therefore, the result is directly set to 0. You could change it to:

def faculty(integer):
    result = 1
    for i in range(1, integer+1):
        result *= i
    return result

Upvotes: 2

Graeme
Graeme

Reputation: 169

Consider what values your loop is looping over.

for i in range(integer):
    print(i)

Upvotes: 1

Related Questions