pythonbeginner10 minutes
Refactor a Function to Calculate Factorial More Cleanly
Improve the clarity and simplicity of a provided factorial function without changing its behavior. Practice writing clean and readable Python code.
Challenge prompt
You are given a function that calculates the factorial of a number using a while loop and extra variables. Refactor the function to make it cleaner and more Pythonic, maintaining the same output, but removing unnecessary variables and improving readability. The function should return the factorial of the given non-negative integer.
Guidance
- • Keep the same functionality of computing the factorial.
- • Simplify variable usage and consider using a for loop if it improves readability.
- • Make sure the function is easy to understand at a glance.
Hints
- • Factorials can be computed cleanly using a for loop running from 1 up to the number.
- • Try to name variables descriptively or reduce them to just what is necessary.
Starter code
def factorial(n):
if n == 0:
return 1
result = 1
i = 1
while i <= n:
result = result * i
i = i + 1
return resultExpected output
factorial(5) returns 120
Core concepts
functionsloopsvariablescode readability
Challenge a Friend
Send this duel to someone else and see if they can solve it.