🔒 Closed Mga boss newbie lang po baka pwede patulong using for loop

Status
Not open for further replies.

Ak1ko

Fanatic
PYTHON po ha.

Paano maka-calculate yung sum ng all even numbers and odd numbers?

Halimbawa input ko 15 tas ifactor muna then lahat ng even iadd tas lahat ng odd iadd.
 
0down vote
def get_even_odd_sum(N):
sum_even, sum_odd = (0, 0)
for i in range(1, N+1):
if i%2:
sum_odd += i
else:
sum_even += i
return (sum_even, sum_odd)

(X, Z) = get_even_odd_sum(20)
print X
print Z
 
>>>def func(n):
>>> num = range(n)
>>> odd = [x for x in num if x%2]
>>> even = [x for x in num if not x%2 and x != 0]
>>> return odd, even

>>> odd, even = func(20)
>>> print odd
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
>>> print even
[2, 4, 6, 8, 10, 12, 14, 16, 18]
 
Status
Not open for further replies.

About this Thread

  • 2
    Replies
  • 641
    Views
  • 2
    Participants
Last reply from:
NEVERGROWTIREDOFDOINGGOOD

Trending Topics

Online now

Members online
1,118
Guests online
12,824
Total visitors
13,942

Forum statistics

Threads
2,367,495
Posts
29,439,880
Members
1,040,803
Latest member
ea92
Back
Top