-3

I want to create f(n) for Sn = n(n+1)/2. Does this make sense? I feel like a nerd!

Here's what I wrote:

def f(x):
    sum=n(n+1)/2
    print(sum)
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561

2 Answers2

1

A few issues with your code:

  • Programming languages don't know the mathematical convention of omitting a multiplication symbol.
  • You need to keep your variable names consistent.
  • You should use integer division since n is an integer number and therefore also the sum.
  • Don't use sum as a variable name, as it makes the built-in function sum() inaccessible.
  • You probably don't want to print the result in the function but return it to the caller.

Instead of

def f(x):
    sum=n(n+1)/2
    print(sum)

you need to write

def f(n):
    return n*(n+1)//2

and then do something like print(f(100)).

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
0

You could do something like this

def f(n): 
    sum=(n*(n+1))/2 
    return sum

Note that: - return should replace print in functions. Nonetheless, return should be the last thing your function does. Anything after return will yield an error.

Now, you can call your function and send input to it as follows:

print(f(5))  #eg. 5