Python Basic Exercises for Beginners


Combining most of python feature and what python do. make sure to run each exercise to practice and check output

Print a String in a Specific Format

sample_string = ("Twinkle, twinkle, little star, How I wonder what you are! "
                 "Up above the world so high, Like a diamond in the sky. "
                 "Twinkle, twinkle, little star, How I wonder what you are")

formatted_string = (f"Twinkle, twinkle, little star,\n"
                    f"\tHow I wonder what you are! \n"
                    f"\t\tUp above the world so high, \n"
                    f"\t\tLike a diamond in the sky. \n"
                    f"Twinkle, twinkle, little star, \n"
                    f"\tHow I wonder what you are")

print(formatted_string)

Formats and prints the string with specific indentation and newlines.


Find Python Version

import sys
print("Python version")
print(sys.version)

Displays the current Python version using the sys module.


Display Current Date and Time

from datetime import datetime
now = datetime.now()
print("Current date and time:", now.strftime("%Y-%m-%d %H:%M:%S"))

Prints the current date and time in the specified format.


Calculate Area of a Circle

import math
radius = 1.1
area = math.pi * (radius ** 2)
print("r =", radius)
print("Area =", area)

Calculates and prints the area of a circle with a given radius.


Reverse Name

first_name = "John"
last_name = "Doe"
print(last_name, first_name)

Prints the first and last names in reverse order.


Generate List and Tuple

values = "3, 5, 7, 23"
num_list = values.split(',')
num_tuple = tuple(num_list)
print("List:", num_list)
print("Tuple:", num_tuple)

Converts a comma-separated string into a list and tuple.


Print File Extension

filename = "abc.java"
extension = filename.split('.')[-1]
print("Extension:", extension)

Extracts and prints the file extension from the filename.


Display First and Last Colors

color_list = ["Red", "Green", "White", "Black"]
print("First color:", color_list[0])
print("Last color:", color_list[-1])

Displays the first and last colors from the list.


Display Examination Schedule

exam_st_date = (11, 12, 2024)
print(f"The examination will start from: {exam_st_date[0]} / {exam_st_date[1]} / {exam_st_date[2]}")

Prints the examination start date in the specified format.


Compute n+nn+nnn

n = 5
result = n + int(f"{n}{n}") + int(f"{n}{n}{n}")
print("Result:", result)

Calculates the value of n + nn + nnn for a given n.


Print Built-in Function Documentation

print(abs.__doc__)

Prints the documentation for the built-in abs() function.


Print Calendar

import calendar
print(calendar.month(2024, 8))

Prints the calendar for August 2024.


Print a 'Here Document'

print("""a string that you "don't" have to escape
This
is a ....... multi-line
heredoc string --------> example""")

Prints a multi-line string with embedded quotes.


Calculate Days Between Two Dates

from datetime import date
date1 = date(2014, 7, 2)
date2 = date(2014, 7, 11)
delta = date2 - date1
print(f"{delta.days} days")

Calculates and prints the number of days between two dates.


Get Volume of a Sphere

import math
radius = 6
volume = (4/3) * math.pi * (radius ** 3)
print("Volume =", volume)

Computes and prints the volume of a sphere with radius 6.


Calculate Difference from 17

def difference(n):
    return 2 * abs(n - 17) if n > 17 else 17 - n

print(difference(20))

Calculates the difference between n and 17, doubling it if n is greater than 17.


Check Number Proximity

def within_100(x):
    return abs(1000 - x) <= 100 or abs(2000 - x) <= 100

print(within_100(950))

Checks if a number is within 100 units of 1000 or 2000.


Sum of Three Numbers

def sum_of_three(a, b, c):
    return 3 * (a + b + c) if a == b == c else a + b + c

print(sum_of_three(2, 2, 2))

Computes the sum of three numbers, tripling it if all are equal.


Add 'Is' to String

def add_is(string):
    return string if string.startswith("Is") else "Is" + string

print(add_is("Check"))

Adds "Is" to the beginning of the string if it does not already start with "Is".


Repeat String n Times

def repeat_string(string, n):
    return string * n

print(repeat_string("Hello", 3))

Returns a string repeated n times.


Check Even or Odd

number = 42
print("Even" if number % 2 == 0 else "Odd")

Determines if a number is even or odd.


Count Number 4

numbers = [1, 4, 3, 4, 5, 4]
print(numbers.count(4))

Counts occurrences of the number 4 in the list.


Get Copies of First Two Characters

def repeat_first_two(s, n):
    return s[:2] * n if len(s) >= 2 else s * n

print(repeat_first_two("Python", 3))

Returns n copies of the first two characters of a string.


Test if Letter is Vowel

def is_vowel(letter):
    return letter.lower() in 'aeiou'

print(is_vowel('a'))

Checks if a letter is a vowel.


Check if Value is in List

value = 3
group = [1, 5, 8, 3]
print(value in group)

Checks if a specified value is contained within a list.


Concatenate List Elements

words = ["Hello", "world", "Python"]
result = ''.join(words)
print(result)

Concatenates all elements of a list into a single string.


Print Even Numbers until 237

numbers = [386, 462, 47, 418, 907, 344, 236, 375, 823, 566, 597, 978, 328, 615, 953, 345,
           399, 162, 758, 219, 918, 237, 412, 566, 826, 248, 866, 950, 626, 949, 687, 217,
           815, 67, 104, 58, 512, 24, 892, 894, 767, 553, 81, 379, 843, 831, 445, 742, 717,
           958, 743, 527]

for num in numbers:
    if num % 2 == 0:
        if num > 237:
            break
        print(num)

Prints even numbers from a list until encountering a number greater than 237.


Colors in First List but Not in Second

color_list_1 = {"White", "Black", "Red"}
color_list_2 = {"Red", "Green"}
print(color_list_1 - color_list_2)

Finds and prints colors in color_list_1 that are not in color_list_2.


Compute Triangle Area

def triangle_area(base, height):
    return 0.5 * base * height

print(triangle_area(5, 10))

 Calculates and prints the area of a triangle given its base and height.