Python 3 exercises (with solution) – Control Flow

This post is part of the series on Python For Beginners (Learning-by-doing). We will be posting exercises (with and without solutions) which you can practice on your own. A great way to learn a new programming language is writing programs instead of just memorizing theory.

What is Control Flow?

Programs are set of instructions which are execute by the computer. Control flow governs the order of execution of the instructions. It introduces decision making, loops and branching in code.

Below are few exercise to practice control flow in Python:

Write a program which asks the user for a number. If number is even print ‘Even’, else print ‘Odd’.

1
2
3
4
5
6
num = int(input("Enter number: "))

if num % 2 == 0:
    print("Even")
else:
    print("Odd")

Write a program to print counting from 1 to 10.

1
2
for i in range(1,11):
    print(i)

Write a program which prints all the divisors of a number.

1
2
3
4
5
num = int(input("Enter number: "))

for i in range(2, num):
    if num % i == 0:
        print(i)

Write a program to check if input number is a prime number.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
num = int(input("Enter number: "))

is_prime = True

for i in range(2, num):
    if num % i == 0:
        is_prime = False
        break

if is_prime:
    print("%d is prime number" % num)
else:
    print("%d is not a prime number" % num)

Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.

1
2
3
4
5
6
7
8
9
for num in range(1, 101):
    if num % 3 == 0 and num % 5 == 0:
        print("FizzBuzz")
    elif num % 3 == 0:
        print("Fizz")
    elif num % 5 == 0:
        print("Buzz")
    else:
        print(num)

Write a program to print all the numbers between 1000 and 2000 which are divisible by 7 but are not a multiple of 5.

1
2
3
for num in range(1000, 2000):
    if num % 7 == 0 and num % 5 != 0:
        print(num)

Write a program to calculate factorial of a number.

1
2
3
4
5
6
num = int(input("Enter number: "))
result = 1
for i in range(1, num + 1):
    result = result * i

print(result)
  • metadata:
    • [[Python]]