I am trying to create a program that takes only even numbers from a range of numbers from 1 to 100 and add all of the even numbers. I am a beginner and I have been trying to get this working since yesterday, and nothing I have tried works. This is my first post, so sorry if the format is wrong but here is my code.
for i in range(1, 100):
if i % 2 == 0:
x = [I]
y = sum(x)
print(y)
CodePudding user response:
The problems with your code has multiple issues that - 1)if you want to get all even numbers from 1 to 100, your range should be (1, 101); 2) the way you build list is wrong (syntax); 3) the sum expect an iterable (list).
There are a few ways to accomplish this sum from 1 to 100 (inclusive), here it will start with yours, and try to show List Comprenshion and Generator Expression way:
lst = [] # to store the build-up list
tot = 0 # to store the answer
for i in range(1, 101):
if i % 2 == 0: # it's a even number
lst.append(i) # store it into lst
tot = sum(lst) # 2550
Generator expression:
all_evens_sum = sum(x for x in range(1, 101) if x % 2 == 0) # 2550
Or List Comprehension:
lst = [x for x in range(1, 101) if x % 2 == 0] # even nums
total = sum(lst) # 2550
CodePudding user response:
I am a beginner too but it looks I can help you some.
for i in range(1, 100):
if(i % 2 == 0):
sum = i
print(sum) // do what you want