Python Practice Examples
Python Practice Examples
print('Hello, world!')
******************************
# This program adds two numbers
num1 = 1.5
num2 = 6.3
**************************************
# Python Program to calculate the square root
a=5
b=6
c=7
a=1
b=5
c=6
print(random.randint(0,9))
***********************************************
***
# Taking kilometers input from the user
kilometers = float(input("Enter value in kilometers: "))
# conversion factor
conv_fac = 0.621371
# calculate miles
miles = kilometers * conv_fac
print('%0.2f kilometers is equal to %0.2f miles'
%(kilometers,miles))
***********************************************
*******
# Python Program to convert temperature in celsius to
fahrenheit
# calculate fahrenheit
fahrenheit = (celsius * 1.8) + 32
print('%0.1f degree Celsius is equal to %0.1f degree
Fahrenheit' %(celsius,fahrenheit))
***********************************************
*
#Python Program to Check if a Number is Positive,
Negative or 0
num = float(input("Enter a number: "))
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
***********************************************
*****
# Python program to check if year is a leap year or not
year = 2000
if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
else:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
***********************************************
# Python program to find the largest number among the
three input numbers
num = 29
num = 407
lower = 900
upper = 1000
factorial = 1
num = 12
# initialize sum
sum = 0
# initialize sum
sum = 0
lower = 100
upper = 2000
# order of number
order = len(str(num))
# initialize sum
sum = 0
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** order
temp //= 10
if num == sum:
print(num)
******************************************
# Python program to check if the input number is odd or
even.
# A number is even if division by 2 gives a remainder of 0.
# If the remainder is 1, it is an odd number.
num = 16
if num < 0:
print("Enter a positive number")
else:
sum = 0
# use while loop to iterate until zero
while(num > 0):
sum += num
num -= 1
print("The sum is", sum)
***********************************************
**
# Display the powers of 2 using anonymous function
terms = 10
c = 'p'
print("The ASCII value of '" + c + "' is", ord(c))
******************************************
# Python program to find H.C.F of two numbers
# define a function
def compute_hcf(x, y):
# choose the smaller number
if x > y:
smaller = y
else:
smaller = x
for i in range(1, smaller+1):
if((x % i == 0) and (y % i == 0)):
hcf = i
return hcf
num1 = 54
num2 = 24
return lcm
num1 = 54
num2 = 24
print_factors(num)
**********************************
# Program make a simple calculator
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
while True:
# take input from the user
choice = input("Enter choice(1/2/3/4): ")
if choice == '1':
print(num1, "+", num2, "=", add(num1, num2))
else:
print("Invalid Input")
***********************************************
# Python program to shuffle a deck of card
# importing modules
import itertools, random
yy = 2014 # year
mm = 11 # month
nterms = 10
def recur_sum(n):
if n <= 1:
return n
else:
return n + recur_sum(n-1)
# change this value for a different result
num = 16
if num < 0:
print("Enter a positive number")
else:
print("The sum is",recur_sum(num))
***********************************************
# Factorial of a number using recursion
def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)
num = 7
# decimal number
dec = 34
convertToBinary(dec)
print()
*************************************
# Program to add two matrices using nested loop
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
Y = [[5,8,1],
[6,7,3],
[4,5,9]]
result = [[0,0,0],
[0,0,0],
[0,0,0]]
for r in result:
print(r)
*******************************
# Program to transpose a matrix using a nested loop
X = [[12,7],
[4 ,5],
[3 ,8]]
result = [[0,0,0],
[0,0,0]]
# iterate through rows
for i in range(len(X)):
# iterate through columns
for j in range(len(X[0])):
result[j][i] = X[i][j]
for r in result:
print(r)
***************************************
# Program to multiply two matrices using nested loops
# 3x3 matrix
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
# 3x4 matrix
Y = [[5,8,1,2],
[6,7,3,0],
[4,5,9,1]]
# result is 3x4
result = [[0,0,0,0],
[0,0,0,0],
[0,0,0,0]]
# iterate through rows of X
for i in range(len(X)):
# iterate through columns of Y
for j in range(len(Y[0])):
# iterate through rows of Y
for k in range(len(Y)):
result[i][j] += X[i][k] * Y[k][j]
for r in result:
print(r)
**************************************
# Program to check if a string is palindrome or not
my_str = 'aIbohPhoBiA'
# set union
print("Union of E and N is",E | N)
# set intersection
print("Intersection of E and N is",E & N)
# set difference
print("Difference of E and N is",E - N)
# string of vowels
vowels = 'aeiou'
print(count)
*****************************
# Python rogram to find the SHA-1 message digest of a
file
def hash_file(filename):
""""This function returns the SHA-1 hash
of the file passed into it"""
message = hash_file("track1.mp3")
print(message)
*******************************************
Example 1: Program to print half pyramid using *
*
**
***
****
*****
Source Code
rows = int(input("Enter number of rows: "))
for i in range(rows):
for j in range(i+1):
print("* ", end="")
print("\n")
*****************************
Example 2: Program to print half pyramid a using numbers
1
12
123
1234
12345
Source Code
rows = int(input("Enter number of rows: "))
for i in range(rows):
for j in range(i+1):
print(j+1, end=" ")
print("\n")
******************************************
Example 3: Program to print half pyramid using alphabets
A
BB
CCC
DDDD
EEEEE
Source Code
rows = int(input("Enter number of rows: "))
ascii_value = 65
for i in range(rows):
for j in range(i+1):
alphabet = chr(ascii_value)
print(alphabet, end=" ")
ascii_value += 1
print("\n")
*********************************************
Example 4: Inverted half pyramid using *
*****
****
***
**
*
Source Code
rows = int(input("Enter number of rows: "))
print("\n")
****************************************
Example 6: Program to print full pyramid using *
*
***
*****
*******
*********
Source Code
rows = int(input("Enter number of rows: "))
k=0
while k!=(2*i-1):
print("* ", end="")
k += 1
k=0
print()
***********************************
Example 7: Full Pyramid of Numbers
1
232
34543
4567654
567898765
Source Code
rows = int(input("Enter number of rows: "))
k=0
count=0
count1=0
while k!=((2*i)-1):
if count<=rows-1:
print(i+k, end=" ")
count+=1
else:
count1+=1
print(i+k-(2*count1), end=" ")
k += 1
count1 = count = k = 0
print()
*******************************************
Example 8: Inverted full pyramid of *
*********
*******
*****
***
*
Source Code
rows = int(input("Enter number of rows: "))
print(dict_1 | dict_2)
**************************************
dict_1 = {1: 'a', 2: 'b'}
dict_2 = {2: 'c', 4: 'd'}
print({**dict_1, **dict_2})
***********************************
dict_1 = {1: 'a', 2: 'b'}
dict_2 = {2: 'c', 4: 'd'}
dict_3 = dict_2.copy()
dict_3.update(dict_1)
print(dict_3)
************************************
my_list = [21, 44, 35, 11]
for index, val in enumerate(my_list):
print(index, val)
***************************************
my_list = [21, 44, 35, 11]
print(flat_list)
***********************************************
**
flat_list = []
for sublist in my_list:
for num in sublist:
flat_list.append(num)
print(flat_list)
Output
[1, 2, 3, 4, 5, 6, 7]
Create an empty list flat_list.
Access each element of the sublist using a nested loop and
append that element to flat_list.
***********************************
Example 3: Using itertools package
import itertools
flat_list = list(itertools.chain(*my_list))
print(flat_list)
**************************************
Example 4: Using sum()
my_list = [[1], [2, 3], [4, 5, 6, 7]]
print(my_list[:])
********************************
Get all the Items After a Specific Position
my_list = [1, 2, 3, 4, 5]
print(my_list[2:])
**********************************
Get all the Items Before a Specific Position
my_list = [1, 2, 3, 4, 5]
print(my_list[:2])
*********************************
Get all the Items from One Position to Another Position
my_list = [1, 2, 3, 4, 5]
print(my_list[2:4])
************************************
Get the Items at Specified Intervals
my_list = [1, 2, 3, 4, 5]
print(my_list[::2])
************************************
Example 1: Access both key and value using items()
dt = {'a': 'juice', 'b': 'grill', 'c': 'corn'}
print(sorted_dt)
*********************************
Example 2: Sort only the values
dt = {5:4, 1:6, 6:3}
sorted_dt_value = sorted(dt.values())
print(sorted_dt_value)
************************************
Example 1: Using Boolean operation
my_list = []
if not my_list:
print("the list is empty")
***************************************
Example 2: Using len()
my_list = []
if not len(my_list):
print("the list is empty")
***************************************
Example 3: Comparing with []
my_list = []
if my_list == []:
print("The list is empty")
*****************************************
Multiple exceptions as a parenthesized tuple
string = input()
try:
num = int(input())
print(string+num)
except (TypeError, ValueError) as e:
print(e)
********************************************
Example 1: Using + operator
list_1 = [1, 'a']
list_2 = [3, 4, 5]
list_2.extend(list_1)
print(list_2)
*****************************
Using in keyword
my_dict = {1: 'a', 2: 'b', 3: 'c'}
if 2 in my_dict:
print("present")
*******************************
Example 1: Using yield
def split(list_a, chunk_size):
chunk_size = 2
my_list = [1,2,3,4,5,6,7,8,9]
print(list(split(my_list, chunk_size)))
**************************************
Example 2: Using numpy
import numpy as np
my_list = [1,2,3,4,5,6,7,8,9]
print(np.array_split(my_list, 5))
******************************
Example 1: Parse string into integer
balance_str = "1500"
balance_int = int(balance_str)
# print the type
print(type(balance_int))
print(type(datetime_object))
print(datetime_object)
**************************************
Example 2: Using dateutil module
from dateutil import parser
print(date_time)
print(type(date_time))
****************************************
Using negative indexing
my_list = ['a', 'b', 'c', 'd', 'e']
# print the last element
print(my_list[-1])
************************************
Using String slicing
my_string = "I love python."
# prints "love"
print(my_string[2:6])
# new line
print()
honda 1948
mercedes 1926
ford 1903
Source Code
with open("data_file.txt") as f:
content_list = f.readlines()
print(content_list)
******************************************
Example 1: Using random module
import random
print(isfloat('s12'))
print(isfloat('1.123'))
************************************
Using count() method
freq = ['a', 1, 'a', 4, 3, 2, 'a'].count('a')
print(freq)
*********************************
Open file in append mode and write to it
The content of the file my_file.txt is
honda 1948
mercedes 1926
ford 1903
The source code to write to a file in append mode is:
del my_dict[31]
print(my_dict)
*********************************
Example 2: Using pop()
my_dict = {31: 'a', 21: 'b', 14: 'c'}
print(my_dict.pop(31))
print(my_dict)
*********************************
Example 1: Using triple quotes
my_string = '''The only way to
learn to program is
by writing code.'''
print(my_string)
***********************************
Example 2: Using parentheses and a single/double quotes
my_string = ("The only way to \n"
"learn to program is \n"
"by writing code.")
print(my_string)
*********************************
Example 3: Using \
my_string = "The only way to \n" \
"learn to program is \n" \
"by writing code."
print(my_string)
*********************************
Example 1: Using splitext() method from os module
import os
file_details = os.path.splitext('/path/file.ext')
print(file_details)
print(file_details[1])
**************************************
Example 2: Using pathlib module
import pathlib
print(pathlib.Path('/path/file.ext').suffix)
**************************************
Example 1: Using time module
import time
start = time.time()
print(23*2.3)
end = time.time()
print(end - start)
***********************************
Example 2: Using timeit module
from timeit import default_timer as timer
start = timer()
print(23*2.3)
end = timer()
print(end - start)
**********************************
Example 1: Using __class__.__name__
class Vehicle:
def name(self, name):
return name
v = Vehicle()
print(v.__class__.__name__)
**************************************
Example 1: Using type() and __name__ attribute
class Vehicle:
def name(self, name):
return name
v = Vehicle()
print(type(v).__name__)
**************************************
Example 1: Using zip and dict methods
index = [1, 2, 3]
languages = ['python', 'c', 'c++']
class Polygon:
def sides_no(self):
pass
class Triangle(Polygon):
def area(self):
pass
obj_polygon = Polygon()
obj_triangle = Triangle()
print(my_string.strip())
*************************************
Example 2: Using regular expression
import re
print(output)
**********************************
Example 1: Using os module
import os
***********************************
Example 2: Using Path module
from pathlib import Path
print(Path('/root/file.ext').stem)
***********************************
Using enum module
from enum import Enum
class Day(Enum):
MONDAY = 1
TUESDAY = 2
WEDNESDAY = 3
names = name()
print(names)
*********************************
Example 1: Using a for loop
The content of the file my_file.txt is
honda 1948
mercedes 1926
ford 1903
Source Code
def file_len(fname):
with open(fname) as f:
for i, l in enumerate(f):
pass
return i + 1
print(file_len("my_file.txt"))
***************************************
Example 2: Using list comprehension
num_of_lines = sum(1 for l in open('my_file.txt'))
print(num_of_lines)
***********************************
Use of del
del deletes items at a specified position.
my_list = [1, 2, 3, 4]
del my_list[1]
print(my_list)
********************************
Use of remove
remove() deletes the specified item.
my_list = [1, 2, 3, 4]
my_list.remove(2)
print(my_list)
***********************************
Use of pop
pop() removes the item at a specified position and returns
it.
my_list = [1, 2, 3, 4]
print(my_list.pop(1))
print(my_list)
*************************************
Example 1: Using glob
import glob, os
os.chdir("my_dir")
file = pathlib.Path('abc.py')
print("Last modification time: %s" %
time.ctime(os.path.getmtime(file)))
print("Last metadata change time or path creation time:
%s" % time.ctime(os.path.getctime(file)))
***********************************************
*****
Example 2: Using stat() method
import datetime
import pathlib
fname = pathlib.Path('abc.py')
print("Last modification time: %s" %
datetime.datetime.fromtimestamp(fname.stat().st_mtime)
)
print("Last metadata change time or path creation time:
%s" %
datetime.datetime.fromtimestamp(fname.stat().st_ctime))
***********************************************
Example 1: Using pathlib module
import pathlib
list_1 = [1, 2, 3, 4]
list_2 = ['a', 'b', 'c']
print("\n")
# loop until the longer list stops
for i,j in itertools.izip_longest(list_1,list_2):
print i,j
*************************************
Example 1: Using os module
import os
file_stat = os.stat('my_file.txt')
print(file_stat.st_size)
***************************************
Example 2: Using pathlib module
from pathlib import Path
file = Path('my_file.txt')
print(file.stat().st_size)
******************************
Example 1: Reverse a Number using a while loop
num = 1234
reversed_num = 0
while num != 0:
digit = num % 10
reversed_num = reversed_num * 10 + digit
num //= 10
print("Reversed Number: " + str(reversed_num))
*************************************
Example 2: Using String slicing
num = 123456
print(str(num)[::-1])
***********************************
Example 1: Calculate power of a number using a while
loop
base = 3
exponent = 4
result = 1
while exponent != 0:
result *= base
exponent-=1
while num != 0:
num //= 10
count += 1
print("Number of digits: " + str(count))
*************************************
else:
print(str1 + " and " + str2 + " are not anagram.")
********************************************
Example 1: Using list slicing
my_string = "talent battle is Lit"
print(my_string[0].upper() + my_string[1:])
***********************************************
**
Example 2: Using inbuilt method capitalize()
my_string = "talent battle is Lit"
cap_string = my_string.capitalize()
print(cap_string)
**************************************
Example 1: Using recursion
def get_permutation(string, i=0):
if i == len(string):
print("".join(string))
# swap
words[i], words[j] = words[j], words[i]
get_permutation(words, i + 1)
print(get_permutation('yup'))
****************************************
Example 2: Using itertools
from itertools import permutations
print(words)
*****************************************
Countdown time in Python
import time
def countdown(time_sec):
while time_sec:
mins, secs = divmod(time_sec, 60)
timeformat = '{:02d}:{:02d}'.format(mins, secs)
print(timeformat, end='\r')
time.sleep(1)
time_sec -= 1
print("stop")
countdown(5)
******************************************
Example 1: Using a for loop
count = 0
for i in my_string:
if i == my_char:
count += 1
print(count)
*******************************************
Example 2: Using method count()
my_string = "Talent battle"
my_char = "r"
print(my_string.count(my_char))
**********************************
Example 1: Using set()
list_1 = [1, 2, 1, 4, 6]
print(list(set(list_1)))
**************************************
Example 2: Remove the items that are duplicated in two
lists
list_1 = [1, 2, 1, 4, 6]
list_2 = [7, 8, 2, 1]
print(list(set(list_1) ^ set(list_2)))
*****************************************
Using decode()
print(b'Easy \xE2\x9C\x85'.decode("utf-8"))
***************************************