Previous Index Next

Solved Examples

Question 1

Write a program that accepts a list from user. Your program should multiply the odd elements by 3 and divide the even elements by 2 and display the list.

Program

number = []
size = int(input('How many elements you want to enter? '))

print('Enter',str(size),'numbers')

for i in range(size):
    data = int(input())
    number.append(data)

print(number)

for i in range(size):
    if number[i]%2 == 0:
        number[i] = number[i] / 2
    else:
        number[i] =  number[i] * 3

print(number)

Output

How many elements you want to enter? 5
Enter 5 numbers
10
14
23
35
90
[10, 14, 23, 35, 90]
[5.0, 7.0, 69, 105, 45.0]

Question 2

Write a program that counts number of words in a sentence.

Program

text = input('Enter a string: ')

#converting string to list of words
words = text.split()

#length of list
count = len(words)

#display number of words
print('No of words are',str(count))

Output

Enter a string: Work hard to achieve your goal
No of words are 6

Question 3

A matrix is the rectangular array of numbers. Write a program to input and display a matrix of size m x n, where m is the number of rows and n is the number of columns of the matrix.

For example matrix of size 3 x 4 should display like this:

Program

row = int(input("Enter the number of rows:")) 
col = int(input("Enter the number of columns:")) 
  
matrix = [] 

print("Enter values in matrix :") 

# For user input 
for i in range(row):
    data =[] 
    for j in range(col):
         data.append(int(input())) 
    matrix.append(data) 
  
# For printing the matrix 
for i in range(row): 
    for j in range(col): 
        print(matrix[i][j], end = " ") 
    print() 

Output

Enter the number of rows:3
Enter the number of columns:4
Enter values in matrix :
2
11
7
12
5
2
9
15
8
3
10
42

2	11	7	12	
5	2	9	15	
8	3	10	42

Previous Index Next