PYnative

Python Programming

  • Learn Python
  • Exercises
  • Quizzes
  • Code Editor
  • Tricks
Home » Python Exercises » Python if else, for loop, and range() Exercise with Solutions

Python if else, for loop, and range() Exercise with Solutions

Updated on: March 9, 2021 | Python Tags: Basics Python Python Exercises

TweetF  sharein  shareP  Pin

To decide or control the flow of a program, we have branching and looping techniques in Python. To perform decision-making, we use the if-else statement in Python. To iterate over a sequence of elements, we use for loop, and when we want to iterate a block of code repeatedly, as long as the condition is true, we use the while loop.

We often use a loop, and if-else statement in our program, so a good understanding of it is necessary.

This Python loop exercise aims to help Python developers to learn and practice if-else conditions, for loop, range() function, and while loop. All questions are tested on Python 3.

Also Read:

  • Python Loop Quiz

This Python loop exercise include the following: –

  • The exercise contains 18 questions and solutions provided for each question.
  • This exercise is nothing but Python for loop and while loop assignments to solve, where you can solve and practice different looping techniques programs and challenges.

This Python loop exercise covers questions on the following topics:

  • Python for loop and while loop
  • Python nested if-else and nested loop
  • Break, continue and pass statement

When you complete each question, you get more familiar with the if-else conditions, for loop, and while loop. Let us know if you have any alternative solutions. It will help other developers.

Use Online Code Editor to solve exercise questions.

Read: Python range().

Exercise 1: Print First 10 natural numbers using while loop

Expected output:

0
1
2
3
4
5
6
7
8
9
10
Show Solution
i = 0
while i <= 10:
    print(i)
    i += 1

Exercise 2: Print the following pattern

1 
1 2 
1 2 3 
1 2 3 4 
1 2 3 4 5

Refer: Print Patterns In Python

Show Solution
print("Second Number Pattern ")
lastNumber = 6
for row in range(1, lastNumber):
    for column in range(1, row + 1):
        print(column, end=' ')
    print("")

Exercise 3: Accept number from user and calculate the sum of all number from 1 to a given number

For example, if user entered 10 the output should be 55.

Show Solution
sum1 = 0
n = int(input("Please enter number "))
for i in range(1, n + 1, 1):
    sum1 += i
print("\n")
print("Sum is: ", sum1)

Exercise 4: Print multiplication table of a given number

For example, num = 2 so the output should be

2
4
6
8
10
12
14
16
18
20
Show Solution
n = 2
for i in range(1, 11, 1):
    product = n*i
    print(product)

Exercise 5: Given a list, iterate it, and display numbers divisible by five, and if you find a number greater than 150, stop the loop iteration.

list1 = [12, 15, 32, 42, 55, 75, 122, 132, 150, 180, 200]

Expected output:

15
55
75
150
Show Solution
list1 = [12, 15, 32, 42, 55, 75, 122, 132, 150, 180, 200]
for item in list1:
    if (item > 150):
        break
    if(item % 5 == 0):
        print(item)

Exercise 6: Given a number count the total number of digits in a number

For example, the number is 75869, so the output should be 5.

Show Solution
num = 75869
count = 0
while num != 0:
    num //= 10
    count+= 1
print("Total digits are: ", count)

Exercise 7: Print the following pattern using for loop

5 4 3 2 1 
4 3 2 1 
3 2 1 
2 1 
1
Show Solution
n = 5
k = 5
for i in range(0,n+1):
    for j in range(k-i,0,-1):
        print(j,end=' ')
    print()

Exercise 8: Reverse the following list using for loop

list1 = [10, 20, 30, 40, 50]

Expected output:

50
40
30
20
10
Show Solution
list1 = [10, 20, 30, 40, 50]
start = len(list1) - 1
stop = -1
step = -1
for i in range(start, stop, step) :
    print(list1[i])

Exercise 9: Display numbers from -10 to -1 using for loop

Expected output:

-10
-9
-8
-7
-6
-5
-4
-3
-2
-1
Show Solution
for num in range(-10, 0, 1):
    print(num)

Exercise 10: Display a message “Done” after successful execution of for loop

For example, the following loop will execute without any error.

for i in range(5):
    print(i)

So the Expected output should be:

0
1
2
3
4
Done!
Show Solution
for i in range(5):
    print(i)
else:
    print("Done!")

Exercise 11: Write a program to display all prime numbers within a range

Note: A Prime Number is a whole number that cannot be made by multiplying other whole numbers

Examples:

  • 6 is not a Prime Number because it can be made by 2×3 = 6
  • 37 is a Prime Number because no other whole numbers multiply together to make it.

Given:

start = 25
end = 50

Expected output:

Prime numbers between 25 and 50 are:
29
31
37
41
43
47
Show Solution
start = 25
end = 50
print("Prime numbers between", start, "and", end, "are:")

for num in range(start, end + 1):
    # all prime numbers are greater than 1
    # if number is less than or equal to 1, it is not prime
    if num > 1:
        for i in range(2, num):
            # check for factors
            if (num % i) == 0:
                # not a prime number so break inner loop and
                # look for next number
                break
        else:
            print(num)

Exercise 12: Display Fibonacci series up to 10 terms

Expected output:

Fibonacci sequence:
0  1  1  2  3  5  8  13  21  34
Show Solution
terms = 10
# first two terms
num1, num2 = 0, 1
count = 0

print("Fibonacci sequence:")
while count < terms:
    print(num1, end="  ")
    temp = num1 + num2
    # update values
    num1 = num2
    num2 = temp
    count += 1

Exercise 13: Write a loop to find the factorial of any number

The factorial (symbol: !) means to multiply all whole numbers from the chosen number down to 1.

For example: calculate the factorial of 5

5! = 5 × 4 × 3 × 2 × 1 = 120

Expected output:

120
Show Solution
num = 5
factorial = 1
if num < 0:
    print("Factorial does not exist for negative numbers")
elif num == 0:
    print("The factorial of 0 is 1")
else:
    for i in range(1, num + 1):
        factorial = factorial * i
    print("The factorial of", num, "is", factorial)

Exercise 14: Reverse a given integer number

Given:

76542

Expected output:

24567

Show Solution
num = 76542
reverse_number = 0
print("Given Number ", num)
while num > 0:
    reminder = num % 10
    reverse_number = (reverse_number * 10) + reminder
    num = num // 10
print("Revered Number ", reverse_number)

Exercise 15: Use a loop to display elements from a given list that are present at even index positions

Given:

my_list = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

Expected output:

20 40 60 80 100
Show Solution
my_list = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
for i in my_list[1::2]:
    print(i, end=" ")

Exercise 16: Display the cube of the number up to a given integer

Given:

input_number = 6

Expected output:

Current Number is : 1  and the cube is 1
Current Number is : 2  and the cube is 8
Current Number is : 3  and the cube is 27
Current Number is : 4  and the cube is 64
Current Number is : 5  and the cube is 125
Current Number is : 6  and the cube is 216
Show Solution
input_number = 6
for i in range(1, input_number + 1):
    print("Current Number is :", i, " and the cube is", (i * i * i))

Exercise 17: Find the sum of the series 2 +22 + 222 + 2222 + .. n terms

Given:

number_of_terms = 5

So series will become 2 + 22 + 222 + 2222 + 22222

Expected output:

24690
Show Solution
number_of_terms = 5
start = 2
sum = 0
for i in range(0, number_of_terms):
    print(start, end=" ")
    sum += start
    start = (start * 10) + 2
print("\nSum of above series is:", sum)

Exercise 18: Print the following pattern

* 
* * 
* * * 
* * * * 
* * * * * 
* * * * 
* * * 
* * 
*

Refer: Print Patterns In Python

Show Solution
rows = 5
for i in range(0, rows):
    for j in range(0, i + 1):
        print("*", end=' ')
    print("\r")

for i in range(rows, 0, -1):
    for j in range(0, i - 1):
        print("*", end=' ')
    print("\r")

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

Founder of PYnative.com I am a Python developer and I love to write articles to help developers. Follow me on Twitter. All the best for your future Python endeavors!

Related Tutorial Topics:

Basics Python Python Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ
Exercises
Quizzes

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your code </pre>

127 Comments

 Python Exercises

  • Python Exercises Home
  • Basic Exercise for Beginners
  • Input and Output Exercise
  • Loop Exercise
  • Functions Exercise
  • String Exercise
  • Data Structure Exercise
  • List Exercise
  • Dictionary Exercise
  • Set Exercise
  • Tuple Exercise
  • Date and Time Exercise
  • OOP Exercise
  • Python JSON Exercise
  • Random Data Generation Exercise
  • NumPy Exercise
  • Pandas Exercise
  • Matplotlib Exercise
  • Python Database Exercise

All Python Topics

Python Basics Python Exercises Python Quizzes Python Regex Python Random Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON
TweetF  sharein  shareP  Pin

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Legal Stuff

  • About Us
  • Privacy Policy
  • Cookie Policy
  • Terms Of Use
  • Contact Us
DMCA.com Protection Status

Copyright © 2018-2021 · [pynative.com]

This website uses cookies to ensure you get the best experience on our website.Privacy PolicyGot it!