SsolGom
SsolGom

Reputation: 49

Python gives strange values of factorial

x = 5

def SsolGom():
  k = 1
    for i in range( 1 , x+1 ):
       k = k * i

print(SsolGom)

=function SsolGom at 0x00F1B660

120 must come out but strange value came out...

Upvotes: 0

Views: 65

Answers (3)

kirannambu
kirannambu

Reputation: 11

  1. You are printing the function without the parenthesis. Calling a function with and without parenthesis gives different results in Python. If you do not provide a parenthesis, Python considers it as properties and not a method/function. Hence you got that result

  2. provide a return statement in the function.

Updated Code:

x=5
def SsolGom():
    k=1
    for i in range( 1 , x+1 ):
        k=k*i
    return k

print(SsolGom())

Upvotes: 0

Eric Duminil
Eric Duminil

Reputation: 54223

SsolGom is a function, SsolGom() is the value returned by this function. It's similar in math: sin is a function, sin(0) is a number.

x = 5

def SsolGom():
    k = 1
    for i in range( 1 , x+1 ):
       k = k * i
    return k

print(SsolGom())
# 120

You need to have a correct indentation inside your function, and you need to return a value. SsolGom() would be None otherwise.

Note that x probably shouldn't be a global variable. Otherwise, your function could be replaced by return 120:

def factorial(x):
    k = 1
    for i in range(x):
       k = k * (i + 1)
    return k

print(factorial(5))

Finally, here's the easiest way to get factorial in Python:

>>> from math import factorial
>>> factorial(5)
120

Upvotes: 1

Sean
Sean

Reputation: 62472

You're missing the brackets. It should be:

print(SsolGom())

Upvotes: 0

Related Questions