Programming Exercises in Python for Beginners

Programming exercises in Python: In this guide, we will solve some necessary programming exercises om python which is important for every beginner to learn and practice by solving.

We are going to cover these topics:

  • List
  • Strings
  • Loops
  • Input-Output
  • Functions (built-in)
  • Flow control statements

python basic exercises for beginners

Exercise 1: Write a program in Python to calculate the volume of a sphere.

Reference articles for help:

Hint
Your function should start with something like def volume(r).  i.e. radius
value of r should be 2

Expected Output
4071.5040790523717

from math import pi

def volume(r):
    v = ((4*pi*r**3)/3)
    return v

print(volume(2))

Program Explanation:

  • We have in-built module math which carries most of the math functions required for mathematical calculations.
  • We used ‘pi’ function here
  • which is already defined in the math module of python. i.e. (pi = 3.14).
  • Hence we have passed the value of radius to calculate the volume of a sphere.

 

Exercise 2: Write a program in Python to display a below-given pattern.

Reference articles for help:

Hint
Input: 6

Expected Output
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5

n = int(input("Enter number: "))
for i in range(n):
    for j in range(i):
        print(i, end=" ")
    print("\n")

Program Explanation:

  • Here in this program, we have used two for loops with range functions.
  • The iteration of the first for loop depends upon the input provided by the user.
  • The iteration of the second for loop depends upon the first loop.
  • Second for loop printing the value of i in the same line. i.e. end=” ” is same
  • In the next line, we are using the ‘\n’ approach for next line.

 

Exercise 3: Range function program to return multiple of 7 within a given range 1,30.

Reference articles for help:

Hint
Use range() function
Start range from 1

Expected Output
7 14 21 28

for i in range(1,30):
    if i%7 == 0:
        print(i, end=" ")

Program Explanation:

  • The modulus operator (%) returns the remainder after division of two operands.
  • So, ‘i%7 == 0’ it only returns True if condition satisfies.
  • If the condition gets false it will not enter to if condition.
  • Hence it only returns the True value divisible by 7.

 

Exercise 4: Write a program in Python to swap between two numbers without using a third variable.

Reference articles for help:

Hint
Input:
a = 4
b = 6

Expected Output
After swapping
a is 6 and b is 4

a = int(input("Enter value of a: "))
b = int(input("Enter value of b: "))
print(f"\na is {a} b is {b}")
a = a + b
b = a - b
a = a - b
print("\nafter swapping")
print(f"a is {a} b is {b}")

Program Explanation:

  • Here we have used some logic and opearators to achieve our goal.

 

Exercise 5: Write a program to check wheteher the given word is vowel or consonent.

Reference articles for help:

Hint 1:
Vowels are ‘a’, ‘e’, ‘i’, ‘o’, ‘u’
Input : a

Expected Output:
a is vowel

Hint 2:
Vowels are ‘a’, ‘e’, ‘i’, ‘o’, ‘u’
Input : d

Expected Output:
d is consonent

val = input("Enter any character: ")
if val in ['a','e','i','o','u']:
    print(f"{val} is vowel")
else:
    print(f"{val} is consonent")

Program Explanation:

  • Here we used the membership operator ‘in’ to check whether the value exists in the list or not.
  • If exist i.e if the entered value by user is exist in the list then It returns true and enters to the if condition and prints value is a vowel.
  • Else if the entered value entered by user does not exist in the list then it enters the else condition and returns value is consonant.

 

Exercise 6: Write a program to swap two numbers without using a third variable.

Reference articles for help:

Hint
Input:
a = 4
b = 6

Expected Output
After swapping
a is 6 and b is 4

a = int(input("Enter value of a: "))
b = int(input("Enter value of b: "))
print(f"\na is {a} b is {b}")
a = a + b
b = a - b
a = a - b
print("\nafter swapping")
print(f"a is {a} b is {b}")

Program Explanation:

  • Here we have used some logic and opearators to achieve our goal.

 

Exercise 7: Write a program to count the occurence of even number and odd number between the range 10 – 55.

Hint
Range 10,55

Expected Output
Even number counts is 23
Odd number counts is 22

num1 = int(input("Enter starting range: "))
num2 = int(input("Enter ending range: "))
eve_count = 0
odd_count = 0
for i in range(num1, num2):
    if i%2 == 0:
        eve_count += 1
    else:
        odd_count += 1
print(f"Even number counts is {eve_count}")
print(f"Odd number counts is {odd_count}")

Program Explanation:

  • Here we are getting two inputs from the user which we will use as a start and end range for our range function.
  • The modulus operator (%) returns the remainder after division.
  • Hence if the number returning 0 after division by 2 means that number is the multiple of 2 and that is an even number.
  • This way we are incrementing the eve_counter by one each time the condition goes true.
  • And else if not, we are entering to else control statement and incrementing the odd_ counter by 1.

 

Exercise 8: Write a program to perform subtract and addition operation using switch.

Reference articles for help:

Hint 1:
Press 1 for Add & 2 for Subtract: 1
Input:
a = 6
b = 4

Expected Output:
Result is 10

Hint 2:
Press 1 for Add & 2 for Subtract: 2
Input:
a = 6
b = 4

Expected Output:
Result is 2

a = int(input("Enter value 1: "))
b = int(input("Enter value 2: "))
choice = {
    '1': a+b,
    '2': a-b
    }
z = input("Press 1 for Add & 2 for Subtract")
print(choice.get(z))

Program Explanation:

  • Like other programming languages, there is no specific switch method in python.
  • We can achieve this by using dictionary mapping.
  • The approach we used is dictionary mapping.
  • Dictionary is the same as an associative array of php, js etc.
  • Here get function is used to get the value at a specific choice.

 

Exercise 9: Write a program in Python to calculates acceleration given initial velocity v1, final velocity v2, start time t1, and end time t2.

Formula: a = (V2 – V1 / t2 – t1)

To test your solution, call the function by inputting values 0, 10, 0, 20 for v1, v2, t1, and t2 respectively, and you should get the expected output.

Hint
Formula : a = (V2 – V1 / t2 – t1)
Formula inside function would look like a = (v2 – v1) / (t2 – t1)

Expected Output
0.5

def acceleration(v1, v2, t1, t2):
    a = (v2 - v1) / (t2 - t1)
    return a

print(acceleration(0,10,0,20))
# 0.5

Program Explanation:

  • The first three lines are where we create the function with three parameters
  • A function definition is like a blueprint.
  • Then in the last line, we are printing out the function output.
  • The output is whatever is returned by the return statement.

 

Exercise 10: Write a program in Python to sort 3 numbers without using loops or conditional statements.

Reference articles for help:

Hint 1
Input:
val1 = 2
val1 = 3
val1 = 4

Expected Output
4  3  2

val1 = int(input("Enter value 1: "))
val2 = int(input("Enter value 2: "))
val3 = int(input("Enter value 3: "))
print("\n before sorting",val1, val2, val3)
s = []
s.append(int(val1))
s.append(int(val2))
s.append(int(val3))
s.sort()
print("\n after sorting",s)

Program Explanation:

  • Here we are getting 3 values from the user and appending them into a list s[] using the append() method.
  • There is an in-built function which sorts the value i.e. sort()
  • Hence we used sort() function i.e sort() to sort values of list s[].
  • Next, in else: part only those numbers will enter which are not multiples of 5. Hence we printed the values.
  • Note: This program is valid only for integer type value.

 


Exercise 11
: Write a program in Python to print number ranging from 1 to 25 but excluding number which is the multiples of 5.

Reference articles for help:

Hint
range = 10, 25

Expected Output
11  12  13  14  16  17  18  19  21  22  23  24

for i in range(10,25):
    if i%5 == 0:
        pass
    else:
        print(i, end=" ")
# 11  12  13  14  16  17  18  19  21  22  23  24

Program Explanation:

  • Here we used the range() function to iterate to a finite specific range from 10, 25.
  • Next, we checked the condition ( if i%5 == 0) if the condition satisfies then it enters to if condition and in the if condition we used the pass keyword to skip that value.
  • It means the number which is the multiple of 5 is skipped.
  • Next, in else: part only those numbers will enter which are not multiples of 5. Hence we printed the values.
  • Here end = ” “ used for blank spaces instead of next line.

 

Exercise 12: Write a program in Python to count the occurrence of a specific value in a list.

Reference articles for help:

Hint 1
a = [1,3,3,4,3,2,3]
Input: 3

Expected Output
3 occurs 4 time

x = int(input("Enter number to check: ")) # 3
a = [1,3,3,4,3,2,3]
count = 0
for i in range(len(a)):
    if a[i] == x:
        count = count+1 
print(f"{x} occurs {count} time")
# 3 occurs 4 time

Program Explanation:

  • First, we took input from the user & stored that input value in x variable (suppose user entered 3).
  • In the very next line, we created a list a[] with some demo elements.
  • For loop is used for iteration. Each time loop executes the value of I increments by 1 and the max time loop iterates are the length of list a[].
  • If the number 3 occurs in the list, the count variable increment by 1.
  • Hence each time for loop executes and during its execution if number 3 occurs then count increments by 1.
  • Hence we got the solution.

 

Exercise 13: Write a program in Python to count the occurrence of a specific word in a string.

Reference articles for help:

Hint
string_ = “adam is a boy and adam loves to play cricket.”
Input: “adam”

Expected Output
adam occurs 2 time

string_ = "adam is a boy and adam loves to play cricket."
x = input("Enter the word you want to check: ")
main = string_.split(" ")
count = 0
for i in range(len(main)):
    if main[i] == x:
        count += 1
print(count)
# adam occurs 2 time

Program Explanation:

  • We split the string from empty space using the split() function of string.
  • It returns the list as output.
  • I.e. string “adam is a boy and adam loves to play cricket.” now converted to [‘adam’, ‘is’, ‘a’, ‘boy’, ‘and’, ‘adam’, ‘loves’, ‘to’, ‘play’, ‘cricket.’].
  • Next, we iterated over each element of the list using for loop.
  • We used a counter to increment the value by one each time value occurs in the list during iteration.

 

Exercise 14: Write a  program in Python to check whether the given number is even or odd.

Reference articles for help:

Hint 1
A number divisible by 2 is even.
Input = 4

Expected Output
4 is even number

Hint 2
A number not divisible by 2 is odd.
Input = 9

Expected Output
9 is odd number

n = int(input("Enter number: "))
if n%2 == 0:
    print(f" {n} is Even number")
else:
    print(f" {n} is Odd number")

Program Explanation:

  • The modulus operator (%) always returns the remainder after division.
  • Hence we checked the condition if the number after division with 2 returns 0.
  • If True means it is an even number else the number is odd.
  • Please visit Operators in Python to learn more about modulus operator.

Exercise 15: Given two integer numbers return their product. If the product is greater than 500, then return their sum.

Reference articles for help:

Hint 1
Number1 = 20
Number2 = 30

Expected Output
The result is 50

Hint 2
Number1 = 20
Number2 = 20

Expected Output
The result is 400

# Procedural approach
num1 = int(input("Enter number one ")) # 20
num2 = int(input("Enter number two ")) # 30
if(num1 * num2 == 500):
    print("The result is ",num1*num2)
else:
    print("The result is ",num1+num2)
# 50
# Functional approach
def exec(x,y):
    if(x*y < 500):
        print(x*y)
    else:
        print("The result is ",x+y)
exec(20,20)
# 400

 

Exercise 16: Write a program to print the greatest of three number.

Reference articles for help:

Hint
Number1 = 10
Number2 = 30
Number3 = 20

Expected Output
30 is greatest

num1 = int(input("Enter value 1: ")) # 10
num2 = int(input("Enter value 2: ")) # 30
num3 = int(input("Enter value 3: ")) # 20
if( num1 > num2 and num1 > num3):
    print(f"{num1} is greatest")
elif( num2 > num1 and num2 > num3):
    print(f"{num2} is greatest")
else:
    print(f"{num3} is greatest")
# 30 is greatest

 

Exercise 17: Write a program to print all numbers multiple of 5 from the range 10 – 50. 

Reference articles for help:

Hint:
Input: 10  50

Expected Output:
10 15 15 20 25 30 35 40 45

# Functional approach
def exec(x,y):
    for i in range(x,y):
        if i%5 == 0:
            print(i, end=" ")
exec(10,50)
# 10 15 20 25 30 35 40 45 

 

Exercise 18: Write a program to check, the first and last elements of the list is same or not. If same print True else False. 

Reference articles for help:

Hint 1:
Input: [1,2,3,4,5,6,7,1]

Expected Output:
True

Hint 2:
Input: [1,2,3,4,5,6,7,8]

Expected Output:
False

# Functional approach
def exec(x):
    if(x[0] == x[len(x)-1]):
        print(True)
    else:
        print(False)

exec([1,2,3,4,5,6,7,1])
exec([1,2,3,4,5,6,7,8])
# True
# False

 

Exercise 19: Write a program to convert, the Fahrenheit value to Celcius. [Formula : F=9/5(c)+32] 

Reference articles for help:

Hint 1:
Formula :- F=9/5(c)+32
Input: 50

Expected Output:
50 Fahrenheit is equal to 10.0 Celcius

# Functional approach
def exec(fh):
    #Formula
    celcius = (fh-32)*5/9
    print(f"{fh} fahrenheit is equal to {celcius} celcius")
exec(50)
# 50 fahrenheit is equal to 10.0 celcius

 

Exercise 20: Write a program to print a right angled triangle pattern,  Please find hint below:-

Reference articles for help:

Hint 1:
Input: 5

Expected Output:

*
* *
* * *
* * * *

# Functional approach
def exec(fh):
    for i in range(fh):
        for j in range(i):
            print("*",end=" ")
        print("\n")
exec(6)