When the code you used is ran, it does not throw a syntax error. It instead returns a list of the numbers from 1 to 1000. The reason why is the following statement:
if 3 % counter3 : True
theList.append(counter3)
The :
operator denotes the end of the if
statement, and what is placed after that is executed if the statement is true. In this scenario, you would want to replace the :
with a ==
. Since the if statement is executed automatically if 3 % counter3
is true, then you don't need == true
at all.
Then, you would want to indent theList.append(counter3)
, so that it runs if the statement is true. New code:
counter3 = 1
theList = []
while counter3 <= 1000:
if 3 % counter3:
theList.append(counter3)
counter3 = counter3+1
print(theList)
However, it still prints the numbers from 1 to 1000. This is because the numbers used in the %
operator are on the wrong sides. You want to check if the number is divisible by 3, using the line if counter3 % 3:
.
Now it prints everything except numbers divisible by 3. This is because a number divisible by 3 will return 0. 0 is a falsy value, which means it evaluates to false in the if
statement. 1 and 2 (the other options) evaluate to true.
Falsy values are False
, 0
, []
, ""
, 0.0
, 0j
, ()
, {}
, and set()
.
Check this link for details.
Since you want to check if it is divisible by 3, then you want to check if the number mod 3 is equal to 0. Now your code is the following:
counter3 = 1
theList = []
while counter3 <= 1000:
if counter3 % 3 == 0:
theList.append(counter3)
counter3 = counter3+1
print(theList)
You could do if not counter3 % 3
, as 0 is falsy, but that obscures the function of your code and is not a good practice.
Since your question says to do numbers between 0 and 100, you should change the while statement to while counter3 <= 100:
.
Another thing is that you should probably use a for
loop. This lets you iterate over a range
, allowing you to not have to keep track of the variable and increment it over time.
theList = []
for counter3 in range(1, 100):
if counter3 % 3 == 0:
theList.append(counter3)
print(theList)
This code works, and it observes most best practices.
If you wanted to, you could use a list comprehension for a one-liner, but this wouldn't be needed.
print([i for i in range(1, 100) if i % 3 == 0])
print([i * 3 for i in range(1, 34)]) #Prints first 33 numbers multiplied by 3, has the same result.