Python Loop Exercises with Solution – for loop(), while loop()
Python Loop Exercises: For loop() and while loop() is used to iterate over each element or data depending upon the condition satisfied. While on the other side to control the flow of a program, we have control flow statements i.e. if, if-else statements in Python.
In most cases, we use loops and control flow statements together in our program. Looping and control flow statements are the backbone of any programming language. So, it is necessary to have a good understanding and command over these concepts.
The main idea behind solving these questions is to make your concept more clear and improve logical thinking of how to approach a problem. We are going to cover conditional statements i.e if, if-else, for loop(), range(), while loop() etc.
For reference
Loop Exercises in Python:
We will solve 15 loop programming exercises in python with a solution & detailed code explanation.
Exercise 1: Write a program in Python to display the Factorial of a number.
Hint 1
Input : 5
Expected output
Factorial is 120
Hint 1
Input : 6
Expected output
Factorial is 720
Exercise 2: Write a program in Python to reverse a word.
Hint 1
Input a word to reverse : python
Expected output
Result: nohtyp
Exercise 3: Write a Python program to reverse a number.
Hint 1
Input a number to reverse : 43521
Expected output
Result: 12534
Exercise 4: Write a program to print n natural number in descending order using a while loop.
Hint 1
Enter a range : 10
Expected output
Result: 10 9 8 7 6 5 4 3 2 1
Exercise 5: Write a program to display the first 7 multiples of 7.
Hint 1
Use if and for loop with break
Expected output
Result: 0 7 14 21 28 35 42 49
Exercise 6: Write a program that appends the square of each number to a new list.
Hint 1
Given x = [2,3,4,5,6,7,8]
Expected output
Result: [4, 9, 16, 25, 36, 49, 64]
Exercise 7: WAP to separate positive and negative number from a list.
Hint 1
Given x = [23, 4, -6, 23, -9, 21, 3, -45, -8]
Expected output
Result:
Positive: [23, 4, 23, 21, 3]
Negative: [-6, -45, -9, -8]
Exercise 8: Write a program that appends the type of elements from a list.
Hint 1
Given x = [23, ‘Python’, 23.98]
Expected output
Result:
[<class ‘int’>,<class ‘str’>,<class ‘float’>]
Exercise 9: Write a program to filter even and odd number from a list.
Hint 1
Given x = [10, 23, 24, 35, 65, 78, 90]
Expected output
Even numbers: [10, 24, 78, 90]
Odd numbers: [23, 35, 65]
Exercise 10: Write a program to fetch only even values from a dictionary.
Hint 1
dic = {‘val1’:10, ‘val2’:20, ‘val3’:23, ‘val4’:22 }
Expected output
Result : 10 20 22