Recap - Factorial
Part of the Fundamentals section of Coddy's Python journey — lesson 39 of 77.
Challenge
BeginnerFactorial is a mathematical operation.
Factorial of n is the product of all positive integers less than or equal to n.
Important edge cases:
- Factorial of 0:
1(by mathematical convention) - Factorial of 1:
1= 1
Examples:
- Factorial of 2:
2= 1 × 2 - Factorial of 3:
6= 1 × 2 × 3 - Factorial of 6:
720= 1 × 2 × 3 × 4 × 5 × 6
Write a program that calculates the factorial of a given integer.
Important: Your program should handle all non-negative integers, including 0 and 1.
How to approach this problem:
- Read an integer input using
int(input()) - Initialize a result variable to 1 (since multiplying by 1 doesn't change the result)
- Use a loop to multiply all numbers from 1 to the input number
- Print the final result (just the number, no extra text)
Example walkthrough:
For input 5:
- Start with result = 1
- Multiply by 1: result = 1 × 1 = 1
- Multiply by 2: result = 1 × 2 = 2
- Multiply by 3: result = 2 × 3 = 6
- Multiply by 4: result = 6 × 4 = 24
- Multiply by 5: result = 24 × 5 = 120
Key concepts you'll need:
- Multiplication assignment:
result *<i>= i</i>(same as<i>result = result * </i>i) - The range function:
range(1, n + 1)includes numbers from 1 to n
Try it yourself
All lessons in Fundamentals
4Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 48Loops
For LoopWhile LoopBreakContinueRecap - FactorialThe Range FunctionNested LoopRecap - Dynamic Input3Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsRecap - Simple MathComparison Operators9Functions
Declare a FunctionArgumentsReturnRecap - Sigma FunctionRecap - Validation FunctionDefault Values12Iterating Over Sequences
Iterating Over ElementsThe Enumerate FunctionIterating Over Strings Part 1Iterating Over Strings Part 2