+ 1
Python Challenge 17: Round 2 - would love explanation of answer
Hi, I am having trouble understanding the solution to python challenge 17: round 2 by StarLord. I would greatly appreciate it if anyone could walk through how to read the below code. def function(var): sum = 0 sq=[x for x in range (1,var+1) if x%83==0 or x==3] for y in sq: sum+=y return(int(sum)) print(function(100))
3 Respuestas
+ 5
The function is called with argument 100. (that is the last line)
Within the function (def):
-initial value of the 'sum' variable is 0
- sq is a list comprehension, to include all numbers between 1 and 100 which are divisible by 83 or are equal to 3. As a result: sq = [3, 83]
- the for loop cycles through the values of sq and adds them to sum (which was 0). As a result sum = 86
- finally sum is converted to integer (which it already was so this wouldn't change anything) and returned to the calling statement
- and the result is printed
+ 4
Sorry, didn't realize this was already answered!
The function "function" takes one input (var), which in this case is 100. It also initializes a variable (sum) set equal to 0. The list "sq" creates a list of numbers between 1 and var+1 (range functions run up to the last number in the list and do not include it), only if the number "x" in the range has a remainder of 0 after being dividing by 83 (a modulo), OR if "x" is equal to 3. In this case, only two numbers will be added to the list, 83 and 3 since they are the only numbers that match the if statement. Next, we run through each item in the "sq" list, which will be 3 and 83, and add those to the "sum" variable, which will result in an integer, 86.
+ 1
Thank you Tibor Santa!