Page 146 - Information_Practice_Fliipbook_Class11
P. 146
6.3.2 Factorial of a Number
Given a non-negative integer n, we wish to compute its factorial (n!). So, we write a program to compute the
factorial (n!) of a number num (>=0). The program accepts an integer and outputs its factorial. We may also be
interested to check if an integer entered by the user is positive. For this purpose, assert statement comprising a
condition num >= 0 is used.
The assert keyword enables you to test whether a condition in your code returns True; if it does not, the program
will throw an AssertionError exception. We are aware that each of 0! and 1! equals 1. To compute the factorial of
a number (positive integer), we compute the product of positive integers up to n. For example, to compute 6!, we
compute the product 1*2*3*4*5*6. Thus, to compute 6!, we initialise the product to be 1, and for each
number in the range(1,7), we multiply the product by it. Note that the function range(1,7) returns a
sequence of six integers: 1, 2, 3, 4, 5, 6. In general, to compute n!, we compute the product 1*2*...*n of
the numbers in the range(1,n+1). Program 6.3 accepts a non-negative integer from the user and computes
and displays its factorial.
Program 6.3 Compute and display n! for a number n, entered by the user.
01 '''
02 Objective:
03 Accept a non-negative number from the user and display its factorial
04 Input: num
05 Output: factorial of num
06 '''
07
08 num = int(input('Enter a non-negative integer: '))
09 #ensure n is an integer and n>=0
10 assert num >= 0
11
12 product = 1
13
14 for i in range(1, num + 1):
15 product = product * i
16
17 print('Factorial of', num, 'is', product)
Sample Output:
>>> Enter a non-negative integer: 5
Factorial of 5 is 120
6.3.3 Multiplication Table of a Number
To do so, we only need to multiply the given number by each number in the range(1, 11) and print the product.
Program 6.4 Write a program that accepts the number num whose multiplication table is to be printed as input and prints
its multiplication table.
01 num = int(input('Enter the number: '))
02 print('Multiplication Table of ', num, ':')
03 for i in range(1, 11):
04 print(num, '*', i, '=', num*i)
Sample Output:
>>> Enter the number: 5
Multiplication Table of 5 :
5 * 1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
132 Touchpad Informatics Practices-XI

