1

The question in my book I am working through (I am new to programming) is:

Threes: Make a list of the multiples of 3 from 3 to 30. Use a for loop to print the numbers in your list.

I have tried a few different things to do this, but in my book Python Crash Course, it doesn't explain the syntax or show me examples on how to do multiples. Only exponents. I have reread the chapter several times over and still am not able to find the tutorial on how to do this. And also, being that I am new to programming, I don't exactly know the keywords or phrases I should be searching for.

It would be of great help to me (I've been confused by this for over an hour) if someone could explain this to me and give me an example.

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
Cpytron
  • 13
  • 1
  • 5

1 Answers1

1

It's easy, you can use the range function to iterate over a sequence of numbers and then create the list by examining the result of value % 3 (modulus 3). If it is zero, you got a multiple, if not, you don't:

# Create an empty list
l = []  
# 31 because the end of the range is exclusive
for i in range(3, 31):
    # if equal to zero it is a multiple of 3
    if i % 3 == 0:  
        # add it to the list
        l.append(i)   

This can be mushed into a single line called a comprehension:

l = [i for i in range(3, 31) if i % 3 == 0]

As for printing, you can tackle it, you use a similar for loop through the list l created and then use the print function!

Since you're new to the language, go over to the Python homepage and read the official tutorial on the language, it is nicely written and will help you much more than any answer can.

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253