Python Develop a program that takes a positive integer input and calculates thre
ID: 3855322 • Letter: P
Question
Python
Develop a program that takes a positive integer input and calculates three things:
1. The sum of all integers from 1 up to and including the input integer.
2. The factorial of the input integer.
3. Use the integer to calculate that number in the Fibonacci sequence listed above.
I have no idea how to begin to calculate the factora and fibonacci section of this. Has anyone ever had any experience with this before?
Here is some code that I had some help with, but its not working. Any info to make this work would be great.
__________________________________________________________________-
if __name__ == "__main__":
n = input("Enter a integer number ")
#sum of numbers from 1 to n
sumOfIntegers = 0
for i in range(1,n+1):
sumOfIntegers = sumOfIntegers + i
print (" Sum of integers up to ",n,"is ",sumOfIntegers)
#factorial of the number
factorial = 1
if n == 0:
factorial = 1
else:
for i in range(1,n+1):
factorial = factorial*i
print (" The factorial of ",n, "is ",factorial)
print (" ")
#Third question can be
#1.finding all the fib numbers up to n
#2.finding n fib numbers
#solving 1
print (" a.fib numbers up to ",n," are")
old = 0
cur = 1
print (old)
print (cur)
while ( cur < n):
new = old + cur
old = cur
cur = new
print (new)
#solving 2
print (" b.",n,"fib numbers")
old = 0
cur = 1
print (old)
print (cur)
count = 2
while (count < n):
new = old + cur
old = cur
cur = new
print (new)
count = count + 1
Explanation / Answer
NOTE: If you face any issues in code execution let me know. I will revert back within 24 hours.
Code link also here for easy copying: http://pasted.co/d0350470
Code:
#!/usr/local/bin/python3
def main():
n = int(input('Enter a number: '))
# sum of integers from 1 to n(including)
sum = 0
for i in range(1, n+1):
sum += i
print('Sum of integers from 1 to',n, 'is:',sum)
# factorial of a number n
i = 1
fact = 1
while i <= n:
fact *= i
i += 1
print('Factorial of number',n,'is:',fact)
# fibonaccei series
a = 0
b = 1
# if n is less than that 2 i.e. 1 we will print the first number and return back
if(n < 2):
print('Fibonaccei series of number',n,'is:')
print(a)
return
i = 2
print('Fibonaccei series of number',n,'is:')
print(a)
print(b)
while i < n:
c = a + b
a = b
b = c
i += 1
print(c)
if __name__=='__main__':
main()
Execution output screenshot:
https://pasteboard.co/GAdMGK5.png
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.