![]() |
Basic function python - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Basic function python (/thread-23689.html) |
Basic function python - sernikov - Jan-12-2020 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)) RE: Basic function python - buran - Jan-12-2020 (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....? RE: Basic function python - sernikov - Jan-12-2020 For example like here below I think it can be understandable variable = 'hello people' 1 print(variable) 2 RE: Basic function python - buran - Jan-12-2020 Please, 1. Use BBcode as advised and 2. Ask clear questions. We won't guess what your questions are. RE: Basic function python - rmspacedashrf - Jan-13-2020 is he asking for a basic sorting algorithm? print(sorted([3,2,4,1])) RE: Basic function python - sernikov - Jan-13-2020 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 RE: Basic function python - perfringo - Jan-13-2020 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))) 55However, no need to convert into list, you can feed range directly into sum: >>> sum(range(n+1)) 55If 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 RE: Basic function python - buran - Jan-13-2020 range() function docs sum_of_numbers(10) prints (as the name suggests) the sum of all numbers between 0 and 10 (incl) RE: Basic function python - sernikov - Jan-14-2020 Thanks perfringo for help now i can continue my journey with python RE: Basic function python - perfringo - Jan-14-2020 (Jan-14-2020, 08:29 AM)sernikov Wrote: Thanks perfringo for help now i can continue my journey with python You are welcome. |