Algorithm:
- Create a module fib.py with a recursive fibonacci function that:
- Takes a number n as input
- Returns 0 if n ≤ 0
- Returns 1 if n = 1
- For n > 1, returns sum of fibonacci(n-1) and fibonacci(n-2)
- In the main program:
- Import the fib module
- Get user input for number of terms (n)
- Use a loop from 0 to n-1 to print fibonacci numbers
- Call fib.fibonacci(i) for each number i in the range
Hello, dear reader! 👋
Thanks for visiting my blog! I’m a student just like you, sharing what I learn to help others with Python programming. I hope my posts are useful for your studies! 😊
If you find this post helpful, please leave a comment—even just a few emojis will make my day! 🐍✨ Your feedback keeps me motivated to create more content for everyone. 🚀
Happy programming!
— Abhin Krishna, S01, EB Department, MEC
Pseudocode:
// fib.py module
FUNCTION fibonacci(n)
IF n <= 0 THEN
RETURN 0
ELSE IF n = 1 THEN
RETURN 1
ELSE
RETURN fibonacci(n-1) + fibonacci(n-2)
END IF
END FUNCTION
// Main program
IMPORT fib
OUTPUT "Enter the number of terms in the Fibonacci series: "
INPUT n
FOR i = 0 TO n-1
OUTPUT fib.fibonacci(i) + " "
END FOR
Program:
1. First file (fib.py) - The Module:
# fib.py - module
# Function to return the nth Fibonacci number
def fibonacci(n):
if n <= 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2)
2. Second file (main program):
# Import the fib module
import fib
# Input: Number of terms in the Fibonacci series
n = int(input("Enter the number of terms in the Fibonacci series: "))
# Print the Fibonacci series
for i in range(n):
print(fib.fibonacci(i), end=" ")
To use this code:
1. Save the first code block in a file named fib.py
2. Save the second code block in another Python file (e.g., main.py) in the same directory
3. Run the second file (main program)
1. Save the first code block in a file named fib.py
2. Save the second code block in another Python file (e.g., main.py) in the same directory
3. Run the second file (main program)
Flowchart:
flowchart TD
subgraph Main[Main Program]
M1([Start])
M2[["Import fib module"]]
M3[/Input n/]
M4[Initialize i = 0]
M5{i < n?}
M6[/"Print fib.fibonacci(i)"/]
M7[i = i + 1]
M8([End])
M1 --> M2
M2 --> M3
M3 --> M4
M4 --> M5
M5 -->|Yes| M6
M6 --> M7
M7 --> M5
M5 -->|No| M8
end
subgraph Module[fib.py Module]
A([Start fibonacci])
B{n <= 0?}
C{n == 1?}
D["Return fibonacci(n-1) + fibonacci(n-2)"]
E[Return 0]
F[Return 1]
A --> B
B -->|Yes| E
B -->|No| C
C -->|Yes| F
C -->|No| D
end
Important!
If you find any mistakes in my code or flowchart, please comment below this post. I will be happy to correct them and clear up any doubts you may have.
Program to define a module to find Fibonacci Numbers and import the module to another program |