🔒 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
  • 619
    Views
  • 2
    Participants
Last reply from:
NEVERGROWTIREDOFDOINGGOOD

Trending Topics

Online now

Members online
819
Guests online
5,602
Total visitors
6,421

Forum statistics

Threads
2,317,678
Posts
29,192,521
Members
1,181,580
Latest member
JeffMan
Back
Top