sync
This commit is contained in:
@@ -0,0 +1,53 @@
|
||||
# sumnN(n) returns the sum of the first n natural numbers.
|
||||
# sumNCubes(n) returns the sum of the cubes of the first n natural numbers.
|
||||
|
||||
# Then use these functions in a program that prompts a user for an n and prints out the sum of the first n natural numbers and the sub of the cubes of the first n natural numbers.
|
||||
|
||||
# What the heck is a natural number?
|
||||
# number that is positive and whole
|
||||
|
||||
# Prompt function
|
||||
def prompt():
|
||||
promptresponse = int(input("Please enter a number for n:"))
|
||||
return promptresponse
|
||||
|
||||
def sumN(n):
|
||||
sum = 0 #initialize sum for use
|
||||
print("Let's show the work for the sum of the natural numbers:\n")
|
||||
for i in range(1,n+1): # start building the natural numbers leading up to n.
|
||||
sum += i
|
||||
if sum != n+1:
|
||||
string_concatenate = f"{i} + " # concatenate the string to show the user the sum
|
||||
else:
|
||||
string_concatenate = f"{i}"
|
||||
print(string_concatenate, end="") # print the string
|
||||
print(f" = {sum}") # print the sum
|
||||
return sum # return the sum to the function
|
||||
|
||||
def sumNCubes(n):
|
||||
sum = 0 #initialize sum for use
|
||||
for i in range(1,n+1): # start building the natural numbers leading up to n.
|
||||
sum += i**3 # add the cube of the number to the sum
|
||||
if sum!=n+1:
|
||||
string_concatenate = f"{i}^3 + "
|
||||
else:
|
||||
string_concatenate = f"{i}^3"
|
||||
print(string_concatenate, end="") # print the string
|
||||
return sum # return the sum to the function
|
||||
|
||||
# Main Function
|
||||
def main():
|
||||
# Prompt the user for n.
|
||||
n=prompt()
|
||||
print(f"The sum for sumN of the 'natural numbers is': {sumN(n)}")
|
||||
|
||||
print(f"The sum for sumN of the 'natural numbers is': {sumNCubes(n)}")
|
||||
|
||||
# Ask the user to see if they want to continue
|
||||
continueprompt = input("Would you like to continue? (y/n)")
|
||||
if continueprompt == "y":
|
||||
main()
|
||||
else:
|
||||
print("Goodbye!")
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user