Python Forum

Full Version: Basic function python
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi everyone I'm new to this world and I would appreciate any advice or answer would be better for me if answer would be given in order of numbers something like that (1 2 3 4) Thanks.

def sum_of_numbers(n):
    total = 0
    for i in range(n+1):
        total+=i
    print(total)
sum_of_numbers(10)


def find_even_numbers(n):
      evens = []
      for i in range(n+1):
          if i % 2 == 0:
              evens.append(i)
      return evens
print(find_even_numbers(10))
(Jan-12-2020, 07:38 PM)sernikov Wrote: [ -> ]I would appreciate any advice or answer would be better for me if answer would be given in order of numbers something like that (1 2 3 4)
And the questions are....?
For example like here below I think it can be understandable

variable = 'hello people' 1
print(variable) 2
Please, 1. Use BBcode as advised and 2. Ask clear questions. We won't guess what your questions are.
is he asking for a basic sorting algorithm?
print(sorted([3,2,4,1]))
I just wondering what processes is performing in function range(n+1)
and whenever I've calling a function sum_of_numbers(10) output is 55
I have trouble understanding your questions.

What does range(n+1) do? You can print it out:

>>> n = 10                                                           
>>> list(range(n+1))                                                 
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
As function sum_of_numbers sums all integers in range this is equal to:

>>> sum(list(range(n+1)))                                            
55
However, no need to convert into list, you can feed range directly into sum:

>>> sum(range(n+1))                                                  
55
If the objective is to find sum of integers in the range then instead of brute-force approach triangular number could be used:

>>> n * (n+1) // 2         # // returns integer, / returns float                                           
55
range() function docs
sum_of_numbers(10) prints (as the name suggests) the sum of all numbers between 0 and 10 (incl)
Thanks perfringo for help now i can continue my journey with python
(Jan-14-2020, 08:29 AM)sernikov Wrote: [ -> ]Thanks perfringo for help now i can continue my journey with python

You are welcome.