Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

new code #55

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 13 additions & 8 deletions Basic Python Pratice Program/14_Factorialiterative.py
Original file line number Diff line number Diff line change
@@ -1,24 +1,29 @@
""" This is a program to calculate the factorial of a number using a for loop and a while loop. """
""" This program calculates the factorial of a number using different methods. """

def factorial_for(n):
""" This function calculates the factorial of a number using a for loop. """
def factorial(n):
""" This function calculates the factorial of a number using an iterative approach. """
if n < 0:
raise ValueError("Factorial is not defined for negative numbers.")
result = 1
for i in range(1, n+1):
for i in range(2, n + 1): # Start from 2 to avoid unnecessary multiplications
result *= i
return result

def factorial_while(n):
""" This function calculates the factorial of a number using a while loop. """
if n < 0:
raise ValueError("Factorial is not defined for negative numbers.")
result = 1
while n > 1:
result *= n
n -= 1
return result

def main():
""" This is the main function. """
print(f"factorial_for(5) = {factorial_for(5)}")
print(f"factorial_while(5) = {factorial_while(5)}")
""" The main function to demonstrate the factorial calculations. """
test_value = 5
print(f"factorial({test_value}) = {factorial(test_value)}")
print(f"factorial_while({test_value}) = {factorial_while(test_value)}")

if __name__ == "__main__":
main()
main()