Our sponsor needs your help!
~ Thanks for your help
HBH
View Thread
Author  simple python program help  Member
Posts: Location:
Joined: 01.01.70 Rank: Guest   so i've starting learning python, and im writing a basic program that finds all the multiples of 3 and 5 between 1 and 1000, and returns the sum. Can't seem to get it to work, not sure why :angry:
heres the code
Code
num=1
sum=0
sum1=0
a=num%3
b=num%5
while num < 1000:
if a==0:
sum=num+sum
elif b==0:
sum1=num+sum
num=num+1
print sum+sum1
Edited by on 121209 12:38 

Author  RE: simple python program help  Member
Posts: Location:
Joined: 01.01.70 Rank: Guest   iantharan wrote:
so i've starting learning python, and im writing a basic program that finds all the multiples of 3 and 5 between 1 and 1000, and returns the sum. Can't seem to get it to work, not sure why :angry:
heres the code
Code
num=1
sum=0
sum1=0
a=num%3
b=num%5
while num < 1000:
if a==0:
sum=num+sum
elif b==0:
sum1=num+sum
num=num+1
print sum+sum1
You want your a and b inside the loop
Code
num=1
sum=0
sum1=0
while num < 1000:
a=num%3
b=num%5
if a==0:
sum=num+sum
elif b==0:
sum1=num+sum1
num=num+1
print sum+sum1
a few more edits: your sum1=num+sum should be sum1=num+sum1
also here is a more appropriate way of doing this
Code
sum=0
for i in range(0,1000):
if i%3==0 or i%5==0:
sum+=i
print sum
note neither one actually include 1000 which is a multiple of 5, easy enough to change though.
Edited by on 121209 14:03 

Author  RE: simple python program help  Member
Posts: Location:
Joined: 01.01.70 Rank: Guest   iantharan wrote:
so i've starting learning python, and im writing a basic program that finds all the multiples of 3 and 5 between 1 and 1000, and returns the sum. Can't seem to get it to work, not sure why :angry:
heres the code
Code
num=1
sum=0
sum1=0
a=num%3
b=num%5
while num < 1000:
if a==0:
sum=num+sum
elif b==0:
sum1=num+sum
num=num+1
print sum+sum1
stdio's code is idiomatic.
but think it's worth pointing out why your code failed anyways, you seem to thinkg that a=num%3 will make a into a list of variables. but it doesn't it just does a=1%3 (ie 1.)
instead, you need a reevaluted each time you check. so you need it in the while loop!
Also, once it's there you may aswell drop the whole thing and put them in the if clauses ( as in num%3==0).
Then it's a short step (which you would have taken had you known about the or keyword) to something similar to stdio's.
Again the use of range is just know about that technique and with compound arithmetic.
On the whole good effort!
Edited by on 121209 16:21 

