# file: InClassAssignment3.py
# Here are the definitions for the following two functions presented:
# sumN(n) returns the sum of the first n natural numbers if n is a positive integer,
# and -1 otherwise
# sumNSquares(n) returns the sum of squares of the first n natural numbers if n is a positive integer,
# and -1 otherwise
#
# Program that has main function, in which it prompts a user for a positive integer,
# and produces sum of the first n integers and the sum of squares of the first n integers,
# using functions sumN and sumNSquares, correspondingly
#
# It also produces results into a file result.txt in the following format:
# The sum of the first integers is:
# The sum of the squares of the first integers is:
def sumN(n):
if n > 0:
sum_=0 # initially sum is 0
for i in range(1,n+1): # sequence [1,2,...,n] is generated, i iterates over it
sum_ += i # i is added to the sum at each iteration
return sum_
else: return -1
def sumNSquares(n):
if n > 0:
sum_=0 # initially sum of squares is 0
for i in range(1,n+1): # sequence [1,2,...,n] is generated, i iterates over it
sum_ += i*i # i^2 is added to the sum at each iteration
return sum_
else: return -1
def main():
print("Hello. This program finds:\n\
1. The sum of the first n natural numbers, and\n\
2. The sum of the squares of the first n natural numbers.\n")
try:
n = int(input("Please, enter a natural number:"))
s = sumN(n)
sq = sumNSquares(n)
answer1 = "The sum of first {0} natural numbers is {1},".format(n,s)
answer2 = "The sum of the squares of the first {0} natural numbers is {1}.".format(n,sq)
print(answer1)
print(answer2)
outSource = open("result.txt","w")
print(answer1,file = outSource)
print(answer2,file = outSource)
outSource.close()
except:
print("incorrect input or something is wrong with the output source")
main()