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 memoizing 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’.

num = int(input("Enter number: "))

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

 

Write a program to print counting from 1 to 10.

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

 

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

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.

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”.

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.

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.

num = int(input("Enter number: "))
result = 1
for i in range(1, num + 1):
    result = result * i

print(result)

Leave a Comment