Search code examples
pythonpython-3.xloopsfor-loopsum

program to find the sum of the first N odd numbers


I'm trying to make a program that calculates the sum of the first N odd numbers. where N is the number of the first odd numbers (e.g. N=4, then the first odds are 1,3,5,7)

it should output the odd numbers.

is the code correct? (given that it needs to be in a loop) or is there a better code for calculating the sum? Also, how to input validate negative numbers? I only know how to do it for integers. (the input needs to be only positive integers)

numberN=input("Please enter a positive number N: ")
sumofodd = 0
try:
    digit = int(numberN)
    if digit > 0:
        for n in range (0,digit+1,1):
            sumofodd = n*n
        print("the sum of", digit, " is ", sumofodd)
except ValueError: 
    print("you did not enter a positive integer")
    exit(1)

Thank you very much


Solution

  • Your code doesn't seem right. You are note calculating sum of numbers. Instead you are calculating n² for last digit it comes across. And your range doesn't loop through odd numbers.

    @S3DEV give you a great reference to totally different (and better) approach, but here is your approach fixed:

    numberN=input("Please enter a positive number N: ")
    sumofodd = 0
    try:
        digit = int(numberN)
    except:
        print("you did not enter a integer")
        exit(0)
    if x < 0:
        pring("give positive number")
        exit(0)
    for n in range(1,digit*2,2):
        sumofodd += n
    print ("the sum of", digit, " is ", sumofodd)