Python Exercises 1 — Basic
1. Write a Python program to print the following string in a specific format (see the output).
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” Output :
print(“Twinkle, twinkle, little star, \n\tHow I wonder what you are! \n\t\tUp above the world so high, \n\t\tLike a diamond in the sky. \nTwinkle, twinkle, little star, \n\tHow I wonder what you are”)
2. Write a Python program to get the Python version you are using.
from platform import python_version
print(python_version())
3. Write a Python program to display the current date and time.
Sample Output :
Current date and time :
2014–07–05 14:34:14
from datetime import datetimenow = datetime.now() # Current date and timedate_time = now.strftime(“%Y-%m-%d %H:%M:%S”)print(“Current date and time :\n”, date_time)
4. Write a Python program which accepts the radius of a circle from the user and compute the area.
Sample Output :
r = 1.1
Area = 3.8013271108436504
import mathprint(“Enter the radius:”)
r = float(input())
a = math.pi * (r ** 2.0)
print(“r = “, (r))
print(“Area = “, (a))
5. Write a Python program which accepts the user’s first and last name and print them in reverse order with a space between them.
print(“Enter your first name:”)
fn = input()
print(“Enter your last name:”)
ln = input()rfname = ln + “ “ + fn
print(“Your full name in reverse order is “, rfname)
6. Write a Python program which accepts a sequence of comma-separated numbers from user and generate a list and a tuple with those numbers.
Sample data : 3, 5, 7, 23
Output :
List : [‘3’, ‘ 5’, ‘ 7’, ‘ 23’]
Tuple : (‘3’, ‘ 5’, ‘ 7’, ‘ 23’)
print(“Enter a sequence of comma-separated numbers:”)
i = input().replace(“ “, “”).split(“,”)
il = list(i)
it = tuple(i)print(“List : “, il)
print(“Tuple : “, it)
7. Write a Python program to accept a filename from the user and print the extension of that.
Sample filename : abc.java
Output : java
print(“Input filename:”)
fn = input()print(fn.split(“.”)[-1])
8. Write a Python program to display the first and last colors from the following list.
color_list = [“Red”,”Green”,”White” ,”Black”]
color_list = [“Red”,”Green”,”White” ,”Black”]print(color_list[0])
print(color_list[-1])
9. Write a Python program to display the examination schedule. (extract the date from exam_st_date).
exam_st_date = (11, 12, 2014)
Sample Output : The examination will start from : 11 / 12 / 2014
exam_st_date = (11, 12, 2014)print(“The examination will start from : “ + str(exam_st_date[0]) + “ / “ + str(exam_st_date[1]) + “ / “ + str(exam_st_date[2]))
10. Write a Python program that accepts an integer (n) and computes the value of n+nn+nnn.
Sample value of n is 5
Expected Result : 615
print(“Enter an integer: “)
n = input()
r = int(n) + int(n + n) + int(n + n + n)print(“Expected Result : “, r)
11. Write a Python program to print the documents (syntax, description etc.) of Python built-in function(s).
Sample function : abs()
Expected Result :
abs(number) -> number
Return the absolute value of the argument.
print(“Enter a built-in function(s)”)
x = input()help(x)
12. Write a Python program to print the calendar of a given month and year.
Note : Use ‘calendar’ module.
import calendar
from time import strftimeyy = int(strftime(“%Y”))
mm = int(strftime(“%m”))print(calendar.month(yy, mm))
13. Write a Python program to print the following ‘here document’.
Sample string :
a string that you “don’t” have to escape
This
is a ……. multi-line
heredoc string — — — → example
print(“””a string that you “don’t” have to escape\nThis\nis a ……. multi-line\nheredoc string — — — → example”””)
14. Write a Python program to calculate number of days between two dates.
Sample dates : (2014, 7, 2), (2014, 7, 11)
Expected output : 9 days
from datetime import dated0 = date(2014, 7, 2)
d1 = date(2014, 7, 11)
delta = d1 — d0
print(str(delta.days) + “ days”)
15. Write a Python program to get the volume of a sphere with radius 6.
import mathrad = 6
v = (4/3) * math.pi * (math.pow(rad, 3))print(“Volume: “, v)
16. Write a Python program to get the difference between a given number and 17, if the number is greater than 17 return double the absolute difference.
print(“Enter a number: “)
n = float(input())if n > 17:
print(abs(n — 17) * 2)
else:
print(n — 17)
17. Write a Python program to test whether a number is within 100 of 1000 or 2000.
def near_thousand(n):
return (abs(n — 1000) <= 100) or (abs(n — 2000) <= 100)print(near_thousand(905))
print(near_thousand(1095))
print(near_thousand(1889))
print(near_thousand(878))
18. Write a Python program to calculate the sum of three given numbers, if the values are equal then return three times of their sum.
print(“Enter first number: “)
n1 = float(input())
print(“Enter second number: “)
n2 = float(input())
print(“Enter third number: “)
n3 = float(input())if n1 == n2 == n3:
print(3 * (n1 + n2 + n3))
else:
print(n1 + n2 + n3)
19. Write a Python program to get a new string from a given string where “Is” has been added to the front. If the given string already begins with “Is” then return the string unchanged.
def isitthere(s):
w = str.split(s)
if w[0] == “Is”:
return s
else:
return “Is “ + sprint(isitthere(“Time to take a bath!”))
print(isitthere(“Is it time to buy a new bike?”))
20. Write a Python program to get a string which is n (non-negative integer) copies of a given string.
print(“Enter a string: “)
s = input()
print(“How many copies of the string do you want?”)
n = int(input())xs = (s + “\n”) * n
print(xs)
21. Write a Python program to find whether a given number (accept from the user) is even or odd, print out an appropriate message to the user.
print(“Enter a number: “)
n = float(input())if n % 2 == 0:
print(“Your number is even.”)
else:
print(“Your number is odd.”)
22. Write a Python program to count the number 4 in a given list.
import numpy as npsample_list = list(np.random.randint(low = 0, high = 10, size = 20))
print(sample_list)def count_four(list):
x = 0
for i in list:
if i == 4:
x += 1
return xprint(count_four(sample_list))
23. Write a Python program to get the n (non-negative integer) copies of the first 2 characters of a given string. Return the n copies of the whole string if the length is less than 2.
print(“Enter a string: “)
s = input()
print(“How many copies do we want?”)
n = int(input())def getcopy(s, n):
x = []
if n >= 2:
x.append(s[0])
x.append(s[1])
print(((x[0] + “ “ + x[1] + “\n”) * (n — 1)) + (x[0] + “ “ + x[1]))
else:
print(s * n)getcopy(s, n)
24. Write a Python program to test whether a passed letter is a vowel or not.
print(“Enter a letter: “)
x = input()def vowelornot(x):
vowel = [“a”, “e”, “i”, “o”, “u”]
if (x in vowel):
print(“Our letter is a vowel.”)
else:
print(“Our letter is not a consonant.”)vowelornot(x)
25. Write a Python program to check whether a specified value is contained in a group of values.
Test Data :
3 -> [1, 5, 8, 3] : True
-1 -> [1, 5, 8, 3] : False
test_data = [1, 5, 8, 3]print(“Enter a number: “)
x = int(input())def check_value(x):
if(x in test_data):
return True
else:
return Falsecheck_value(x)
26. Write a Python program to create a histogram from a given list of integers.
import matplotlib.pyplot as plt
import numpy as npsample_list = list(np.random.randint(low = 0, high = 100, size = 10))
print(“Sample list:\n”, sample_list)plt.hist(sample_list)
plt.show()
27. Write a Python program to concatenate all elements in a list into a string.
from urllib.request import Request, urlopen
import randomurl = “https://svnweb.freebsd.org/csrg/share/dict/words?revision=61569&view=co"
req = Request(url, headers={‘User-Agent’: ‘Mozilla/5.0’})web_byte = urlopen(req).read()webpage = web_byte.decode(‘utf-8’)
words = webpage[:100000].split(“\n”)
random.shuffle(words)
sample_words = words[:10]print(“Sample elements:\n”, sample_words)
print(“String:”)
‘ ‘.join(sample_words)
28. Write a Python program to print all even numbers from a given numbers list in the same order and stop the printing if any numbers that come after 237 in the sequence.
Sample numbers list :
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
]def no28(nums):
for i in nums:
if i == 237:
break
if i % 2 == 0:
print(i)no28(numbers)
29. Write a Python program to print out a set containing all the colors from color_list_1 which are not present in color_list_2.
Test Data :
color_list_1 = set([“White”, “Black”, “Red”])
color_list_2 = set([“Red”, “Green”])
Expected Output :
{‘Black’, ‘White’}
color_list_1 = set([“White”, “Black”, “Red”])
color_list_2 = set([“Red”, “Green”])def notin2(list1, list2):
s = set()
for i in list1:
if i not in list2:
s.add(i)
else:
continue
print(s)notin2(color_list_1, color_list_2)
30. Write a Python program that will accept the base and height of a triangle and compute the area.
print(“Input triangle base: “)
b = float(input())
print(“Input triangle height: “)
h = float(input())a = (h * b) / 2
print(“Triangle area: “, a)
31. Write a Python program to compute the greatest common divisor (GCD) of two positive integers.
import mathprint(“Input first integer: “)
first = int(input())
print(“Input second integer: “)
second = int(input())gcd = math.gcd(first, second)
print(“The GCD of the two integers is: “, gcd)
32. Write a Python program to get the least common multiple (LCM) of two positive integers.
import mathprint(“Input first integer: “)
first = int(input())
print(“Input second integer: “)
second = int(input())# For Python 3.9.0 and higher
# gcd = math.lcm(first, second)lcm = int((first * second) / math.gcd(first, second))
print(“The LCM of the two integers is: “, lcm)
33. Write a Python program to sum of three given integers. However, if two values are equal sum will be zero.
print(“Input first integer: “)
first = int(input())
print(“Input second integer: “)
second = int(input())
print(“Input third integer: “)
third = int(input())if first == second:
sum = 0
elif first == third:
sum = 0
elif second == third:
sum = 0
else:
sum = first + second + thirdprint(“Output: “, sum)
34. Write a Python program to sum of two given integers. However, if the sum is between 15 to 20 it will return 20.
print(“Input first integer: “)
first = int(input())
print(“Input second integer: “)
second = int(input())if first + second in range(15, 20):
sum = 20
else:
sum = first + secondprint(“Output: “, sum)
35. Write a Python program that will return true if the two given integer values are equal or their sum or difference is 5.
print(“Input first integer: “)
first = int(input())
print(“Input second integer: “)
second = int(input())def tru(first, second):
if first == second or first + second == 5 or abs(first — second) == 5:
return Truetru(first, second)
36. Write a Python program to add two objects if both objects are an integer type.
int_a = 7
int_b = 43
not_int = “o”def bothint(a, b):
if isinstance(a, int) and isinstance(b, int):
print(a + b)bothint(int_a, int_b)
37. Write a Python program to display your details like name, age, address in three different lines.
print(“Input your name: “)
name = input()
print(“Input your age: “)
age = input()
print(“Input your address: “)
address = input()print(“Output:\n” + name + “\n” + age + “\n” + address)
8. Write a Python program to solve (x + y) * (x + y).
Test Data : x = 4, y = 3
Expected Output : (4 + 3) ^ 2) = 49
x = 4
y = 3def solver(x, y):
o = (x + y) ** 2
return “(“ + str(x) + “ + “ + str(y) + “) ^ 2 = “ + str(o)solver(x, y)
39. Write a Python program to compute the future value of a specified principal amount, rate of interest, and a number of years.
Test Data : amt = 10000, int = 3.5, years = 7
Expected Output : 12722.79
amt = 10000
interest = 3.5
years = 7# compound interest
# Principal × (1 + Rate)Time − Principal
compound = amt + (amt * ((1 + interest / 100) ** years) — amt)print(round(compound, 2))
40. Write a Python program to compute the distance between the points (x1, y1) and (x2, y2).
import mathprint(“Enter x1: “)
x1 = int(input())
print(“Enter y1: “)
y1 = int(input())
print(“Enter x2: “)
x2 = int(input())
print(“Enter y2: “)
y2 = int(input())# d=√((x_2-x_1)²+(y_2-y_1)²
d = math.sqrt(math.pow((x2 — x1), 2) + math.pow((y2 — y1), 2))print(d)
41. Write a Python program to check whether a file exists.
from os.path import exists as file_existsfile_exists(‘/content/sample_data/anscombe.json’)
42. Write a Python program to determine if a Python shell is executing in 32bit or 64bit mode on OS.
***
more exercises coming ..