Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can anyone please help how to write this code on Python?

Create a counter that takes in a number from the user, counts from 0 to that number, tells the user as it counts if each number is even or odd, then sums all the numbers together and prints the sum.

The following code and comments are a starting point. The text following each # is a comment, you will need to replace the comments with the necessary code:

count = 0

sum = 0

num = 0

# Ask user for a number

#All code lines that need to be inside the while loop, need to be tabbed over once.

while (count <= num):

          # add count to sum

         # Use the following if statement along with the remainder operator (modulus, %) to check if a number is even or odd.

         if count%2!=0:

                #print the number is odd

         else:

              #print the number is even

        count = count +1 #update counter for the while loop exit condition

#print the sum

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Using for loop

count=0
sum=0

for i in range(0,n+1):
    if (i%2==0):
        print("Number is Even")
    else:
        print("Number is Odd")
    
    sum+=i

print(sum)

Using While loop:

count=0
sum=0

while(count<n):
    if(count%2==0):
        print("Number is Even")
    else:
        print("Number is odd")
    
    count+=1
    sum+=count
    
print(sum)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading