193. Python Program to Find the Factorial of a Number
EasyPhase 1 · Warm-up
One for loop and range() solve this. You know both.
Overview
The factorial is a classic first question in coding interviews. It shows that you can keep a running result in a loop.
Problem Statement
Lucía has 5 books. Lucía wants to know in how many different orders the books can stand on a shelf. The answer is the factorial of 5.
The factorial of a number n is all the whole numbers from 1 to n multiplied together: 1 × 2 × 3 × ... × n. The factorial of 0 is 1. This is a fixed rule in maths.
Read n and print Factorial of <n> is <answer>.
Steps
- Read
nand turn it into a whole number. - Start the answer at 1, not at 0.
- Loop over every number from 1 to
n. Multiply the answer by each number. - Print the sentence with
nand the answer.
Examples
Example 1. Input 5 gives:
Factorial of 5 is 120
Why: 1 × 2 × 3 × 4 × 5 = 120.
Example 2. Input 0 gives:
Factorial of 0 is 1
Why: there are no numbers from 1 to 0, so the answer stays at its start value, 1. This matches the rule that the factorial of 0 is 1.
Input
One whole number n (0 to 20). Use input() with no prompt text: the tests type the input for you, and a prompt would end up in your output.
Output
One line: Factorial of <n> is <answer>. The tests try 6 different inputs, also 0, 1 and 20.
Try it first. The solution opens when you solve this question, or after 3 tries with Submit.