Page 498 - ComputerScience_Class_11
P. 498

Program 6: Write a program to find the factorial of a number entered by user.

                   Program 6.py
               File  Edit  Format    Run   Options   Window    Help

                n = int(input('Enter any number: '))
                f = 1
                for i in range(1, n+1):
                    f = f * i
                print('The factorial of', n, 'is:', f)



                   Output

                Enter any number: 5
                The factorial of 5 is: 120



              The range() Function
              The range() function in Python is a built-in function that is commonly used with loops to generate a sequence of
              numbers. It is often used in for loops to specify the number of iterations. Understanding how range() works is important
              for controlling the flow of loops in Python.
              This function generates a sequence of numbers, starting from a specified number and ending before a specified limit.
              This sequence is useful when you want to repeat a task a certain number of times or iterate over a series of numbers.
              Syntax:

              range(start, stop, step)
              where:
              •  start (optional): The number to start the sequence from. If not provided, it defaults to 0.

              •  stop (required): The number where the sequence stops, but the stop value is not included in the sequence.
              •  step (optional): The difference between each number in the sequence. If not provided, it defaults to 1.
              Program 7: Write a program to generate the number pyramid as shown below:
                  1
                 1 2
                1 2 3
               1 2 3 4

              1 2 3 4 5
                   Program 7.py

               File  Edit  Format    Run   Options   Window    Help

                rows = 5
                for i in range(1, rows + 1):
                    print(" " * (rows - i), end="")
                    for j in range(1, i + 1):
                        print(j, end=" ")
                    print()






                  496  Touchpad Computer Science (Ver. 3.0)-XI
   493   494   495   496   497   498   499   500   501   502   503