def Factorial(n):
n=int(input("Input a number?"))
if n==0:
return 1
else:
return n * Factorial(n-1)
def Fibonacci(num):
i=0
present=1
previous=0
while i<=num:
nextterm=present+previous
present=previous
previous=nextterm
i=i+1
print("The fibonacci number for", i, "is", nextterm)
def CallFibOrFac(s):
s=input('Fib or Fac?')
if s == 'Fib':
num=input('Up to what number?')
print(Fibonacci(num))
elif s == 'Fac':
n=input('What number?')
print(Factorial(n))
CallFibOrFac()
I've spent a lot of time trying to solve this assignment. I don't understand how I'm supposed to have my defined function CallFibOrFac call the other two functions for solving the Fibonacci or Factorial numbers. Any help/explanation is appreciated. Thanks!
This is the exact prompt that I was left with in class:
Write a Python program that has 3 Functions:
The first function will be called CallFibOrFac
It will receive a single string as a parameter.
If the string is "Fib" it will call the second function called Fibonacci
If the string is "Fac" it will call the third function called Factorial.
The Second function prints the first 10 numbers in the Fibonacci sequence.
The Third function prints the value of 10 factorial.
We want to make the second and third functions work for cases other than just the first 10 numbers so add a parameter to the Fibonacci function and the Factorial function which will tell it how far to go along the Fibonacci sequence or the Factorial.
There are a few errors on your code:
CallFibOrFac
function receives a string but overwrites it. The task says it will just pass the string, use it as given;That said, all the corrected functions should be:
Factorial Function:
def Factorial(n):
# Removed the input read
if n==0:
return 1
else:
return n * Factorial(n-1)
Fibonacci Function:
# It is working as expected
def Fibonacci(num):
i=0
present=1
previous=0
while i<=num:
nextterm=present+previous
present=previous
previous=nextterm
i=i+1
print("The fibonacci number for", i, "is", nextterm)
CallFibOrFac
def CallFibOrFac(s):
# Moved the number detection out of the ifs, since both will use it
# Note that the task says it will _receive_ the string as parameter, so you don't need to ask here.
num=int(input('Up to what number?'))
if s == 'Fib':
print(Fibonacci(num))
elif s == 'Fac':
print(Factorial(num))
Note: There are stuff left to fix and / or improve, I just worked on which might be a problem for you right now (As noted by @abarnert)