Previous Index Next

Solved Examples

Question 1

Write a program that accepts a number from the user and calculate the factorial of that number. The factorial of an integer n is defined as
n ! = n ( n - 1)( n - 2)( n - 3) ... (3)(2)(1) ; if n>0
For example, 5! = 5 x 4 x 3 x 2 x 1

Program

n = int(input('Enter a number: '))
fact = 1

while n > 0:
    fact = fact * n
    n = n - 1

print('Factorial :',fact)

Output

Enter a number: 6
Factorial : 720

Question 2

Write a program that generates a random number and asks the user to guess what the number is. If the user's guess is higher than the random number, the program should display "Too high, try again." If the user's guess is lower than the random number, the program should display "Too low, try again." The program should use a loop that repeats until the user correctly guesses the random number.

Program

import random

computer = random.randint(1,100)
player = 0

while(player != computer):
    player = int(input('Enter your guess: '))
	
    if player < computer:
        print('Too low, try again.')
    elif player > computer:
        print('Too high, try again.')
    else:
        print('Correct!, You are winner')

Output

Enter your guess: 67
Too high, try again.
Enter your guess: 34
Too low, try again.
Enter your guess: 45
Too high, try again.
Enter your guess: 39
Too low, try again.
Enter your guess: 42
Too high, try again.
Enter your guess: 40
Correct!, You are winner

Question 3

Write a program to obtain the first 10 numbers of a Fibonacci sequence. In a Fibonacci sequence the sum of two successive terms gives the third term.

Following are the first 10 terms of the Fibonacci sequence:
0 1 1 2 3 5 8 13 21 34

Program

first=0
second=1

print(first,second,end=' ')

for i in range(3,11):
    third=first+second
    print(third,end=' ')
    first=second
    second=third

output

0 1 1 2 3 5 8 13 21 34

Previous Index Next