0

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

2
  • 1
    put the print outside the loop Commented Feb 25, 2022 at 17:15
  • 1
    Thank you! Don't know why I didn't think of that 😅 Commented Feb 25, 2022 at 17:20

3 Answers 3

1

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]
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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, ...]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.