Welcome to HBH! If you have tried to register and didn't get a verification email, please using the following link to resend the verification email.

simple python program help


ghost's Avatar
0 0

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

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

ghost's Avatar
0 0

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

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

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

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.


ghost's Avatar
0 0

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

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 re-evaluted 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!