'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 1:[1]

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)
    

Solution 2:[2]

Following @ex4 answers, you could also do this to simplify code and validate negative inputs:

numberN = abs(int(input("Please enter a positive number N: ")))
sumofodd = 0
for n in range(1,numberN*2,2):
      sumofodd += n
print ("the sum of", numberN, " is ", sumofodd)

abs() returns the absolute value and because: abs(int(input("..."))) The input gets turned into an integer that turns positive.

You could also use this:

 numberN = abs(int(input("Please enter a positive number N: ")))
 print ("the sum of", numberN, " is ", numberN*numberN)

Same result.

Solution 3:[3]

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

Solution 4:[4]

#include <stdio.h>
int main(void) {
    int odd;
    printf("Enter n: ");
    scanf("%d", &odd);
          
    if (odd % 2 == 1) 
        odd = odd + 1;
          
    while (odd <= 1) {
        printf("%d\n", odd);
        odd = odd + 1;
    }
    return 0;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ex4
Solution 2
Solution 3 George Emmanuel
Solution 4 Jakob Liskow