Python Programming - Solving Our First Problem

January 9, 2014 | By
| 2 Replies More

Since there are many python people out there and they are not at the same level in python programming language I have decided to make different types of tutorials. In this article I will use my lovely tool (python) to solve a very simple math problem.

Level Of This Tutorial: Beginner

What You Need To Know:

1. range() function.

2. for loops.

3. if statments.

4. % operator.

What You Will Learn:

You will learn how to use the above skills to solve a nice math problem.

The Problem

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below 1000.

My Solution In Python

So we need to find the sum all multiples of 3 or 5 below 1000. We can start by writing numbers down but it will take a 'year'. Time is priceless! We will use Python to find the sum of these multiples of 3 and 5 below 1000.

1. First we need to find all multiples of 3 and 5 below 1000.

2. What does it mean for a number to be a multiple of 3 or 5? It means that when this number is divided by 3 or 5 the remainder will equal to 0.

3. Ok, we can easily test the remainder with the % operator, right?

4. Open a new .py file and start typing the following parts of code.

5. Add the shebang line (I will explain it in New To Python series. ).

#!/usr/bin/python

6. Create a variable called sum and assign it to the value 0

sum = 0

7. Then add the following code.

for i in range(0,1000):
if i % 3 == 0 or i % 5 == 0:
sum +=i

Make sure you use indent the code right.

8. Add the following line at the end of the file to print the sum in the screen with the print function.

print sum

The script is shown in the following screenshot.

python programming

After you have saved the file, open a new terminal in the same directory where the script is and run the following command.

python program_name.py

python programming

Filed Under : HOWTOS, PROGRAMMING

Free Linux Ebook to Download

Comments (2)

Trackback URL | Comments RSS Feed

  1. Sean Murphy says:

    This is a nice intro to the language, but this is also a great opportunity for list comprehension. Here is another solution in only one line:

    >>> sum([x for x in range(1000) if not (x%3 and x%5)])
    233168

Leave a Reply

Commenting Policy:
Promotion of your products ? Comment gets deleted.
All comments are subject to moderation.