Kibbee.ca
icon
Learning Python, And Project Euler Problem 1

I've recently wanted to start learning Python. Why Python? No reason really. I just wanted to program in something that wasn't VB.Net, which is what I use at work. I find that since I'm using VB.Net so much, I find it hard to program in anything else, and my mind is getting stuck in kind of a rut.

In order to aid with my learning of Python, I've decided to tackle some of the problems on Project Euler. Basically it's a bunch of math type problems. Which I also find is something I don't get enough practice with. I've done the first 20 or so before, in VB.Net of course, but I think time will be much more interesting as I'll be learning a new language as I go along.

I'm also going to be chronicling my answers here, with extensive commenting for anybody else who wants to learn from my code. Here is my solution to the first question.

Project Euler: Problem 1

Find the sum of all natural numbers less than 1000 that are divisble by 3 and 5.

[Full Problem]

Answer

#initialize total to 0
sumOfNumbers = 0

#a simple for loop that goes from 1 to 999
for i in range(1,1000):
    #if i mod 3 is 0, add to sum of numbers
    if i % 3 == 0:
        sumOfNumbers += i
    #else if i mod 5 is 0, then add to sum of numbers
    elif i % 5 == 0:
        sumOfNumbers += i

#print sum of numbers, which is the final answer
print sumOfNumbers

[Download Code]

I'd also like to point out that I learning something very neat in Python. Python is very list oriented. If you look at that for loop, you will see range(1,1000). This gives you a list of all the nubmers from 1 to 999. So, instead of incrementing i from 1 to 999 as would be done in many other languages, you create a list with the values from 1 to 999 in it, and enumerate over the values in that list. Basically, you have to approach things quite differently when working in Python as compared to VB.Net.

No Comments Posted