Python — if in for
In a list of all natural numbers below a given number (x), return a list of numbers that multiples of 3 or 5.
Note: natural numbers are the positive integers (whole numbers) 1, 2, 3, etc.
Solution:
Firstly we need to define the natural numbers in a list:
n = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16…]
The passed number (x) is will be used to slice the our list of natural number into a smaller list that we can work with, assume x = 10 then the our list will be range from 1 to 10.
new_n= [1,2,3,4,5,6,7,8,9,10]
and then we need to find all numbers that multiples of 3 and 5, in the list above we will return list of [3, 5, 6 ,9]. and this will fulfill the first requirement of the challenge. Then we can sum up the elements of the final list to meet the final expected result of this function.
Code:
We started off by defining a variable called sum to return the end of our code, it defined as an integer with 0 as the initiation value. Then we looped through the range of natural number to the maximum number which is the number passed in the function argument. Then inside the loop we construct checking points to start building our filtered list, the condition here says as long as the number has no remains when divided by 3 or 5, Then we can add that number to the the sum variable, after looping through the whole list we returned the summation of all number.
Enhancement:
You can utilize the list comprehension structure in python to rewrite you code to look cleaner.
Python for QA Engineer, By Sam Shamsan
If you work the Right to left design or languages, or you know someone who do, then buying my book will be great way to gain RTL end to end knowledge and support me to keep writing book at the same time.
https://www.amazon.com/RTL-Foundations-Sam-Shamsan/dp/1656300087