https://www.w3resource.
com/python-exercises/python-basic-
exercises.php#EDITOR
2. Write a Python program to get the Python version you are using.
import sys as s
print(s.version())
print(s.version_info())
Write a Python program to display the current date and time.
Sample Output :
Current date and time :
2014-07-05 14:34:14
import datatime as dt
t = dt.datetime.now()
a = t.strftime("%Y-%M-%D")
print(a)
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. Go
to the editor
Sample data : 3, 5, 7, 23
Output :
List : ['3', ' 5', ' 7', ' 23']
Tuple : ('3', ' 5', ' 7', ' 23')
u = input('yournumber :')
list1 = u.split(',')
tuple = tuple(list1)
print(list1)
print(tuple)
Write a Python program to accept a filename from the user and print the
extension of that. Go to the editor
Sample filename : abc.java
Output : java
i = input()
p = i.split('
print(p[-1])
8. Write a Python program to display the first and last colors from the
following list. Go to the editor
color_list = ["Red","Green","White" ,"Black"]
i = ["Red","Green","White" ,"Black"]
print(i[0],i[-1])
Write a Python program that accepts an integer (n) and computes the value
of n+nn+nnn. Go to the editor
Sample value of n is 5
Expected Result : 615
i = input()
z = int(i)
p = z + int(i+i) + int(i+i+i)
print(p)
1 a = int(input("Input an integer : "))
2 n1 = int( "%s" % a )
3 n2 = int( "%s%s" % (a,a) )
n3 = int( "%s%s%s" % (a,a,a) )
print (n1+n2+n3
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(abs.__doc__)
12. Write a Python program to print the calendar of a given month and
year.
Note : Use 'calendar' module.
import calendar
i = input()
j = input()
i = int(i)
j = int(j)
z = calendar.month(i,j)
print(z)
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 date
f_date = date(2014, 7, 2)
l_date = date(2014, 7, 11)
delta = l_date - f_date
print(delta.days)
a = (2014, 7, 2)
b = (2014, 7, 11)
print("no. of days between {0} {1} is {2} :".format(a,b,b[-1]-a[-1]))
a = input("enter your first date AS YYYY-MM-DD: ")#(2014, 7, 2)
b = input("enter your second date AS YYYY-MM-DD: ")#(2014, 7, 11)
c = tuple(a.split('-'))
d = tuple(b.split('-'))
print("no. of days between {0} {1} is {2} :".format(c,d,int(d[-1])-
int(c[-1])))
Write a Python program to get the volume of a sphere with radius 6.
from math import pi
r = 6
print((4/3)*(pi)*r**3)
. 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.
give = int(input())
num = 17
diff = num - give
if num < give:
print(abs(diff)*2)
else:
print(diff)
def difference(n):
if n <= 17:
return 17 - n
else:
return (n - 17) * 2
print(difference(22))
print(difference(14))
Write a Python program to test whether a number is within 100 of 1000 or
2000.
def near_thousand(n):
return ((abs(1000 - n) <= 100) or (abs(2000 - n) <= 100))
print(near_thousand(1000))
print(near_thousand(900))
print(near_thousand(800))
print(near_thousand(2200))
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.
def sum_of(givennumber):
asd = str(givennumber)
b = int(asd[0])+ int(asd[1]) + int(asd[2])
if asd[0] == asd[1] == asd[2]:
return b*3
else:
return b
print(sum_of(333))
def sum_thrice(x, y, z):
sum = x + y + z
if x == y == z:
sum = sum * 3
return sum
print(sum_thrice(1, 2, 3))
print(sum_thrice(3, 3, 3))
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
i = "Isasdl asdlfjIsasdlf"
j = "Is"
if i.startswith(j):
print(i)
else:
print('%s %s'%(j,i))
def new_string(str):
if len(str) >= 2 and str[:2] == "Is":
return str
return "Is" + str
print(new_string("Array"))
print(new_string("IsEmpty"))
Write a Python program to get a string which is n (non-negative integer)
copies of a given string.
e = input("enter your string babu :")
e1 = int(input("enter how many copies do you want :"))
while e1 > 0:
print(e,end='')
e1 = e1 -1
def larger_string(str, n):
result = ""
for i in range(n):
result = result + str
return result
print(larger_string('abc', 2))
print(larger_string('.py', 3))
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.
e1 = int(input("enter number ra :"))
print("""Thanks for entering....your number is %i
Please wait while we confirm whether your number is EVEN or ODD
"""%e1)
if e1 == 0:
print("""you have entered zero...........we cant defined it
please renter your number buddy""")
elif e1%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.
def mainstr(list1):
z = 0
i = int(input('give a no. that you need count'))
for j in list1:
if i != j:
pass
else:
z = z + 1
return z
print(mainstr((1,2,3,4,5,4)))
def list_count_4(nums):
count = 0
for num in nums:
if num == 4:
count = count + 1
return count
print(list_count_4([1, 4, 6, 7, 4]))
print(list_count_4([1, 4, 6, 4, 7, 4]))
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.
e = input("enter your string babu :")
e1 = int(input("enter how many copies do you want :"))
if len(e) < 2:
while e1 > 0:
print(e,end='')
e1 = e1 -1
else:
while e1 > 0:
print(e[0:2],end='')
e1 = e1 -1
def substring_copy(str, n):
flen = 2
if flen > len(str):
flen = len(str)
substr = str[:flen]
result = ""
for i in range(n):
result = result + substr
return result
print(substring_copy('abcdef', 2))
print(substring_copy('p', 3));
Write a Python program to test whether a passed letter is a vowel or not.
def vovel(char):
vovels = 'aeiou'
vovelss = vovels.upper()
if char in vovels or char in vovelss:
return True
else:
return False
print(vovel('E'))
def is_vowel(char):
all_vowels = 'aeiou'
return char in all_vowels
print(is_vowel('c'))
print(is_vowel('e'))
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
def vovel(list1,x):
for i in list1:
if x == i:
return True
else:
return False
print(vovel([1, 5, 8, 3],-1))
. Write a Python program to create a histogram from a given list of
integers.
def values(list1):
sum = 0
for i in list1:
if i > sum:
sum = sum + i
makkalu = sum * '*'
print(makkalu)
sum = 0
print(values([10,2,35,1,]))
def histogram( items ):
for n in items:
output = ''
times = n
while( times > 0 ):
output += '*'
times = times - 1
print(output)
histogram([2, 3, 6, 5])
. Write a Python program to concatenate all elements in a list into a
string and return it.
def values(list1):
stp = ""
for i in list1:
i = str(i)
stp = stp + i
return stp
print(values([10,2,35,1,]))
def concatenate_list_data(list):
result= ''
for element in list:
result += str(element)
return result
print(concatenate_list_data([1, 5, 12, 2]))
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. Go to the editor
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 values(list1):
stp = []
for i in list1:
if i%2 == 0:
stp.append(i)
elif i == 237:
break
else:
pass
return stp
print(values([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]))
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 x in numbers:
if x == 237:
print(x)
break;
elif x % 2 == 0:
print(x)
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. Go to the editor
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"])
print("Original set elements:")
print(color_list_1)
print(color_list_2)
print("\nDifferenct of color_list_1 and color_list_2:")
print(color_list_1.difference(color_list_2))
print("\nDifferenct of color_list_2 and color_list_1:")
print(color_list_2.difference(color_list_1))
color_list_1 = set(["White", "Black", "Red"])
color_list_2 = set(["Red", "Green"])
#print(color_list_1)
seet = {}
seet = set(seet)
for i in color_list_1:
for j in color_list_2:
if i == j:
break
else:
for z in color_list_2:
if z == j:
break
else:
if i not in seet:
seet.add(i)
else:
if i in seet:
break
else:
seet.add(i)
continue
print(seet)
0. Write a Python program that will accept the base and height of a
triangle and compute the area. Go to the editor
a = int(input())
b = int(input())
print(a*b/2)
31. Write a Python program to compute the greatest common divisor (GCD)
of two positive integers.
import math as m
a = abs(int(input()))
b = abs(int(input()))
print(m.gcd(a,b))
def gcd(x, y):
gcd = 1
if x % y == 0:
return y
for k in range(int(y / 2), 0, -1):
if x % k == 0 and y % k == 0:
gcd = k
break
return gcd
print("GCD of 12 & 17 =",gcd(12, 17))
print("GCD of 4 & 6 =",gcd(4, 6))
print("GCD of 336 & 360 =",gcd(336, 360))
32. Write a Python program to get the least common multiple (LCM) of two
positive integers
import math as m
a = abs(int(input()))
b = abs(int(input()))
print(m.lcm(a,b))
def lcm(x, y):
if x > y:
z = x
else:
z = y
while(True):
if((z % x == 0) and (z % y == 0)):
lcm = z
break
z += 1
return lcm
print(lcm(4, 6))
print(lcm(15, 17))
33. Write a Python program to sum of three given integers. However, if
two values are equal sum will be zero. Go to the editor
a,b,c = [int(i) for i in input('enter your numbers').split()]
if a == b or a == c or b == c:
print('sum is zero')
else:
print(a+b+c)
def sum_three(x, y, z):
if x == y or y == z or x==z:
sum = 0
else:
sum = x + y + z
return sum
print(sum_three(2, 1, 2))
print(sum_three(3, 2, 2))
print(sum_three(2, 2, 2))
print(sum_three(1, 2, 3))
34. Write a Python program to sum of two given integers. However, if the
sum is between 15 to 20 it will return 20.
def sum(x,y):
a = x + y
if a in range(15,21):
return 20
else:
return a
print(sum(2,11))
def sum(x, y):
sum = x + y
if sum in range(15, 20):
return 20
else:
return sum
print(sum(10, 6))
print(sum(10, 2))
print(sum(10, 12))
35. Write a Python program that will return true if the two given integer
values are equal or their sum or difference is 5.
def sum_three(x, y):
a = x + y
b = abs(x -y)
if x == y or a == 5 or b == 5:
return True
else:
return False
print(sum_three(2, 7))
def test_number5(x, y):
if x == y or abs(x-y) == 5 or (x+y) == 5:
return True
else:
return False
print(test_number5(7, 2))
6. Write a Python program to add two objects if both objects are an
integer type.
def add_numbers(a, b):
if not (isinstance(a, int) and isinstance(b, int)):
return "Inputs must be integers!"
return a + b
print(add_numbers(10, 20))
print(add_numbers(10, 20.23))
print(add_numbers('5', 6))
print(add_numbers('5', '6'))
def sum_three(x, y):
if type(x) ==type(y) == int:
return x + y
else:
return "provide int value"
print(sum_three(27, '234'))
39. Write a Python program
to compute the future value of a specified principal amount, rate of
interest, and a number of years. Go to the editor
Test Data : amt = 10000, int = 3.5, years = 7
Expected Output : 12722.79
The formula for future value with compound interest is FV = P(1 +
r/n)^nt.
FV = the future value;
P = the principal;
r = the annual interest rate expressed as a decimal;
n = the number of times interest is paid each year;
t = time in years.
Test Data : amt = 10000, int = 3.5, years = 7
Expected Output : 12722.79
Sample Solution:
Python Code:
amt = 10000
int = 3.5
years = 7
future_value = amt*((1+(0.01*int)) ** years)
print(round(future_value,2))
40. Write a Python program to compute the distance between the points
(x1, y1) and (x2, y2)
from math import sqrt
def points(a,b):
x1 = a[0]
y1 = a[1]
x2 = b[0]
y2 = b[1]
return (sqrt((x2-x1)**2 +(y2-y1)**2))
print(points((4,0),(6,6)))
41. Write a Python program to check whether a file exists.
import os.path
print(os.path.isfile('main.txt'))
print(os.path.isfile('main.py'))
Write a Python program to determine if a Python shell is executing in
32bit or 64bit mode on OS.
import platform, struct
print(platform.architecture()[0])
print(struct.calcsize("P") * 8)
Write a Python program to get OS name, platform and release information.
import platform
import os
print("Name of the operating system:",os.name)
print("\nName of the OS system:",platform.system())
print("\nVersion of the operating system:",platform.release())
import os
import sys
import platform
import sysconfig
print("os.name ", os.name)
print("sys.platform ", sys.platform)
print("platform.system() ", platform.system())
print("sysconfig.get_platform() ", sysconfig.get_platform())
print("platform.machine() ", platform.machine())
print("platform.architecture() ", platform.architecture())
Write a Python program to locate Python site-packages.
import site;
print(site.getsitepackages())
Write a python program to get the path and name of the file that is
currently executing.
import os
print("Current File Name : ",os.path.realpath(__file__))
Write a Python program to find out the number of CPUs using.
Sample Solution:-
Python Code:
import multiprocessing
print(multiprocessing.cpu_count())
Write a Python program to list all files in a directory in Python.
from os import listdir
from os.path import isfile, join
files_list = [f for f in listdir('/home/students') if
isfile(join('/home/students', f))]
print(files_list);