the question is:
'Considering the numbers between 0 and 100
a.) Write a code to determine the numbers divisible by 6 and print them as a list. The output should be: [6, 12, 18, 24, 30, 36, 42, 48, 54, 60, 66, 72, 78, 84, 90, 96].
Hints:
You can use the append function to add values to a list. You can modify the following code that can be used to determine odd and even numbers. Remember that % gives the modulus or remainder of the division.'
and in response i wrote the code:
new = []
for x in range(1,100):
if ((x % 6) == 0):
new.append(x)
print(new)
but when i print the list it gives me:
[6]
[6, 12]
[6, 12, 18]
[6, 12, 18, 24]
[6, 12, 18, 24, 30]
[6, 12, 18, 24, 30, 36]
[6, 12, 18, 24, 30, 36, 42]
[6, 12, 18, 24, 30, 36, 42, 48]
[6, 12, 18, 24, 30, 36, 42, 48, 54]
[6, 12, 18, 24, 30, 36, 42, 48, 54, 60]
[6, 12, 18, 24, 30, 36, 42, 48, 54, 60, 66]
[6, 12, 18, 24, 30, 36, 42, 48, 54, 60, 66, 72]
[6, 12, 18, 24, 30, 36, 42, 48, 54, 60, 66, 72, 78]
[6, 12, 18, 24, 30, 36, 42, 48, 54, 60, 66, 72, 78, 84]
[6, 12, 18, 24, 30, 36, 42, 48, 54, 60, 66, 72, 78, 84, 90]
[6, 12, 18, 24, 30, 36, 42, 48, 54, 60, 66, 72, 78, 84, 90, 96]
how to make it so it only gives me full list(last line of output)?
sorry I am new to python
CodePudding user response:
You have your print statement inside the loop, so it is printing every iteration. Move it outside the loop and it will work as intended.
new = []
for x in range(1,100):
if ((x % 6) == 0):
new.append(x)
print(new)
[6, 12, 18, 24, 30, 36, 42, 48, 54, 60, 66, 72, 78, 84, 90, 96]
CodePudding user response:
Code inside the for loop will repeat each time the loop executes. Python, unlike some other programming languages, recognizes whitespace and indentation as part of execution order syntax. You must make sure that everything you want within the loop is indented below the "for" statement, and anything you want to execute once after the loop is unindented after the end of your loop code.
CodePudding user response:
This is the simplest and Pythonic way of doing your job:
print([x for x in range(1, 100) if x % 6 == 0])
This code makes a list with all x
elements in the range 1 to 100, where the condition of being divisible by 6 has been met.
Output:
[6, 12, 18, 24, 30, 36, 42, 48, 54, 60, 66, 72, 78, 84, ...]