Python Programming

Please leave a remark at the bottom of each page with your useful suggestion.


Table of Contents

  1. Python Introduction
  2. Python Startup
  3. Python Examples Program Collection 1
  4. Python Examples Program Collection 2
  5. Python Examples Program Collection 3
  6. Python Examples Program Collection 4
  7. Python Examples Program Collection 5
  8. Python Examples Program Collection 6
  9. Python Examples Program Collection 7
  10. Python Examples Program Collection 8



Python Program to Add Two Matrices

Source code: Matrix Addition using Nested Loop

# 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]]
# iterate through rows
for i in range(len(X)):
   # iterate through columns
   for j in range(len(X[0])):
       result[i][j] = X[i][j] + Y[i][j]
for r in result:
   print(r)

Python Program to Add Two Matrices

Source Code: Matrix Addition using Nested List Comprehension

# Program to add two matrices using list comprehension
X = [[12,7,3],
    [4 ,5,6],
    [7 ,8,9]]
Y = [[5,8,1],
    [6,7,3],
    [4,5,9]]
result = [[X[i][j] + Y[i][j]  for j in range(len(X[0]))] for i in range(len(X))]
for r in result:
   print(r)

Python Program to Add Two Numbers

Example 1: Add Two Numbers

# This program adds two numbers
num1 = 1.5
num2 = 6.3
# Add two numbers
sum = num1 + num2
# Display the sum
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))

Python Program to Add Two Numbers

Example 2: Add Two Numbers With User Input

# Store input numbers
num1 = input('Enter first number: ')
num2 = input('Enter second number: ')
# Add two numbers
sum = float(num1) + float(num2)
# Display the sum
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))

Python Program to Sort Words in Alphabetic Order

Source Code

# Program to sort alphabetically the words form a string provided by the user
my_str = "Hello this Is an Example With cased letters"
# To take input from the user
#my_str = input("Enter a string: ")
# breakdown the string into a list of words
words = [word.lower() for word in my_str.split()]
# sort the list
words.sort()
# display the sorted words
print("The sorted words are:")
for word in words:
   print(word)

Python Program to Check If Two Strings are Anagram

Python program to check if two strings are anagrams using sorted()

str1 = "Race"
str2 = "Care"
# convert both the strings into lowercase
str1 = str1.lower()
str2 = str2.lower()
# check if length is same
if(len(str1) == len(str2)):
    # sort the strings
    sorted_str1 = sorted(str1)
    sorted_str2 = sorted(str2)
    # if sorted char arrays are same
    if(sorted_str1 == sorted_str2):
        print(str1 + " and " + str2 + " are anagram.")
    else:
        print(str1 + " and " + str2 + " are not anagram.")
else:
    print(str1 + " and " + str2 + " are not anagram.")

Python Program to Calculate the Area of a Triangle

Source Code

# Python Program to find the area of triangle
a = 5
b = 6
c = 7
# Uncomment below to take inputs from the user
# a = float(input('Enter first side: '))
# b = float(input('Enter second side: '))
# c = float(input('Enter third side: '))
# calculate the semi-perimeter
s = (a + b + c) / 2
# calculate the area
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print('The area of the triangle is %0.2f' %area)

Python Program to Find Armstrong Number in an Interval

Source Code

# Program to check Armstrong numbers in a certain interval
lower = 100
upper = 2000
for num in range(lower, upper + 1):
   # 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 Armstrong Number

Source Code: Check Armstrong number (for 3 digits)

# Python program to check if the number is an Armstrong number or not
# take input from the user
num = int(input("Enter a number: "))
# initialize sum
sum = 0
# find the sum of the cube of each digit
temp = num
while temp > 0:
   digit = temp % 10
   sum += digit ** 3
   temp //= 10
# display the result
if num == sum:
   print(num,"is an Armstrong number")
else:
   print(num,"is not an Armstrong number")

Python Program to Check Armstrong Number

Source Code: Check Armstrong number of n digits

num = 1634
# Changed num variable to string, 
# and calculated the length (number of digits)
order = len(str(num))
# initialize sum
sum = 0
# find the sum of the cube of each digit
temp = num
while temp > 0:
   digit = temp % 10
   sum += digit ** order
   temp //= 10
# display the result
if num == sum:
   print(num,"is an Armstrong number")
else:
   print(num,"is not an Armstrong number")

Python Program to Find ASCII Value of Character

Source Code

# Program to find the ASCII value of the given character
c = 'p'
print("The ASCII value of '" + c + "' is", ord(c))

Python Program to Convert Bytes to a String

Using decode()

print(b'Easy \xE2\x9C\x85'.decode("utf-8"))

Python Program to Make a Simple Calculator

Example: Simple Calculator by Using Functions

# Program make a simple calculator
# This function adds two numbers
def add(x, y):
    return x + y
# This function subtracts two numbers
def subtract(x, y):
    return x - y
# This function multiplies two numbers
def multiply(x, y):
    return x * y
# This function divides two numbers
def divide(x, y):
    return x / y
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): ")
    # check if choice is one of the four options
    if choice in ('1', '2', '3', '4'):
        num1 = float(input("Enter first number: "))
        num2 = float(input("Enter second number: "))
        if choice == '1':
            print(num1, "+", num2, "=", add(num1, num2))
        elif choice == '2':
            print(num1, "-", num2, "=", subtract(num1, num2))
        elif choice == '3':
            print(num1, "*", num2, "=", multiply(num1, num2))
        elif choice == '4':
            print(num1, "/", num2, "=", divide(num1, num2))
        
        # check if user wants another calculation
        # break the while loop if answer is no
        next_calculation = input("Let's do next calculation? (yes/no): ")
        if next_calculation == "no":
          break
    
    else:
        print("Invalid Input")

Python Program to Capitalize the First Character of a String

Example 1: Using list slicing

my_string = "programiz is Lit"
print(my_string[0].upper() + my_string[1:])

Python Program to Capitalize the First Character of a String

Example 2: Using inbuilt method capitalize()

my_string = "programiz is Lit"
cap_string = my_string.capitalize()
print(cap_string)

Python Program to Catch Multiple Exceptions in One Line

Multiple exceptions as a parenthesized tuple

string = input()
try:
    num = int(input())
    print(string+num)
except (TypeError, ValueError) as e:
    print(e)

Python Program to Convert Celsius To Fahrenheit

Source Code

# Python Program to convert temperature in celsius to fahrenheit
# change this value for a different result
celsius = 37.5
# 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 List is Empty

Example 1: Using Boolean operation

my_list = []
if not my_list:
    print("the list is empty")

Python Program to Check If a List is Empty

Example 2: Using len()

my_list = []
if not len(my_list):
    print("the list is empty")

Python Program to Check If a List is Empty

Example 3: Comparing with []

my_list = []
if my_list == []:
    print("The list is empty")

Python Program to Check the File Size

Example 1: Using os module

import os
file_stat = os.stat('my_file.txt')
print(file_stat.st_size)

Python Program to Check the File Size

Example 2: Using pathlib module

from pathlib import Path
file = Path('my_file.txt')
print(file.stat().st_size)

Python Program to Check If a String Is a Number (Float)

Using float()

def isfloat(num):
    try:
        float(num)
        return True
    except ValueError:
        return False
print(isfloat('s12'))
print(isfloat('1.123'))

Python Program to Get the Class Name of an Instance

Example 1: Using __class__.__name__

class Vehicle:
    def name(self, name):
        return name
v = Vehicle()
print(v.__class__.__name__)

Python Program to Get the Class Name of an Instance

Example 2: Using type() and __name__ attribute

class Vehicle:
    def name(self, name):
        return name
v = Vehicle()
print(type(v).__name__)

Python Program to Print Colored Text to the Terminal

Example 1: Using ANSI escape sequences

print('\x1b[38;2;5;86;243m' + 'Programiz' + '\x1b[0m')

Python Program to Print Colored Text to the Terminal

Example 2: Using python module termcolor

from termcolor import colored
print(colored('Programiz', 'blue'))

Python Program to Concatenate Two Lists

Example 1: Using + operator

list_1 = [1, 'a']
list_2 = [3, 4, 5]
list_joined = list_1 + list_2
print(list_joined)

Python Program to Concatenate Two Lists

Example 2: Using iterable unpacking operator *

list_1 = [1, 'a']
list_2 = range(2, 4)
list_joined = [*list_1, *list_2]
print(list_joined)

Python Program to Concatenate Two Lists

Example 3: With unique values

list_1 = [1, 'a']
list_2 = [1, 2, 3]
list_joined = list(set(list_1 + list_2))
print(list_joined)

Python Program to Concatenate Two Lists

Example 4: Using extend()

list_1 = [1, 'a']
list_2 = [1, 2, 3]
list_2.extend(list_1)
print(list_2)

Python Program to Convert Decimal to Binary, Octal and Hexadecimal

Source Code

# Python program to convert decimal into other number systems
dec = 344
print("The decimal value of", dec, "is:")
print(bin(dec), "in binary.")
print(oct(dec), "in octal.")
print(hex(dec), "in hexadecimal.")

Python Program to Copy a File

Using shutil module

from shutil import copyfile
copyfile("/root/a.txt", "/root/b.txt")

Python Program to Count the Number of Each Vowel

Source Code: Using Dictionary

# Program to count the number of each vowels
# string of vowels
vowels = 'aeiou'
ip_str = 'Hello, have you tried our tutorial section yet?'
# make it suitable for caseless comparisions
ip_str = ip_str.casefold()
# make a dictionary with each vowel a key and value 0
count = {}.fromkeys(vowels,0)
# count the vowels
for char in ip_str:
   if char in count:
       count[char] += 1
print(count)

Python Program to Count the Number of Each Vowel

Source Code: Using a list and a dictionary comprehension

# Using dictionary and list comprehension
ip_str = 'Hello, have you tried our tutorial section yet?'
# make it suitable for caseless comparisions
ip_str = ip_str.casefold()
# count the vowels
count = {x:sum([1 for char in ip_str if char == x]) for x in 'aeiou'}
print(count)

Python Program to Create a Countdown Timer

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)

Python Program to Safely Create a Nested Directory

Example 3: Using distutils.dir_util

import distutils.dir_util
distutils.dir_util.mkpath("/root/dirA/dirB")

Python Program to Safely Create a Nested Directory

Example 4: Raising an exception if directory already exists

import os
try:
    os.makedirs("/dirA/dirB")
except FileExistsError:
    print("File already exists")

Python Program to Get the Full Path of the Current Working Directory

Example 1: Using pathlib module

import pathlib
# path of the given file
print(pathlib.Path("my_file.txt").parent.absolute())
# current working directory
print(pathlib.Path().absolute())

Python Program to Get the Full Path of the Current Working Directory

Example 2: Using os module

import os
# path of the given file
print(os.path.dirname(os.path.abspath("my_file.txt")))
# current working directory
print(os.path.abspath(os.getcwd()))

Python Program to Convert Decimal to Binary Using Recursion

Source Code

# Function to print binary number using recursion
def convertToBinary(n):
   if n > 1:
       convertToBinary(n//2)
   print(n % 2,end = '')
# decimal number
dec = 34
convertToBinary(dec)
print()

Python Program to Delete an Element From a Dictionary

Example 1: Using del keyword

my_dict = {31: 'a', 21: 'b', 14: 'c'}
del my_dict[31]
print(my_dict)

Python Program to Delete an Element From a Dictionary

Example 2: Using pop()

my_dict = {31: 'a', 21: 'b', 14: 'c'}
print(my_dict.pop(31))
print(my_dict)

Python Program to Display Calendar

Source Code

# Program to display calendar of the given month and year
# importing calendar module
import calendar
yy = 2014  # year
mm = 11    # month
# To take month and year input from the user
# yy = int(input("Enter year: "))
# mm = int(input("Enter month: "))
# display the calendar
print(calendar.month(yy, mm))

Python Program to Measure the Elapsed Time in Python

Example 1: Using time module

import time
start = time.time()
print(23*2.3)
end = time.time()
print(end - start)

Python Program to Measure the Elapsed Time in Python

Example 2: Using timeit module

from timeit import default_timer as timer
start = timer()
print(23*2.3)
end = timer()
print(end - start)

Python Program to Extract Extension From the File Name

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])

Python Program to Extract Extension From the File Name

Example 2: Using pathlib module

import pathlib
print(pathlib.Path('/path/file.ext').suffix)

Python Program to Find the Factors of a Number

Source Code

# Python Program to find the factors of a number
# This function computes the factor of the argument passed
def print_factors(x):
   print("The factors of",x,"are:")
   for i in range(1, x + 1):
       if x % i == 0:
           print(i)
num = 320
print_factors(num)

Python Program to Find Factorial of Number Using Recursion

Source Code

# Factorial of a number using recursion
def recur_factorial(n):
   if n == 1:
       return n
   else:
       return n*recur_factorial(n-1)
num = 7
# check if the number is negative
if num < 0:
   print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
   print("The factorial of 0 is 1")
else:
   print("The factorial of", num, "is", recur_factorial(num))

Python Program to Find the Factorial of a Number

Factorial of a Number using Loop

# Python program to find the factorial of a number provided by the user.
# change the value for a different result
num = 7
# To take input from the user
#num = int(input("Enter a number: "))
factorial = 1
# check if the number is negative, positive or zero
if num < 0:
   print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
   print("The factorial of 0 is 1")
else:
   for i in range(1,num + 1):
       factorial = factorial*i
   print("The factorial of",num,"is",factorial)

Python Program to Find the Factorial of a Number

Factorial of a Number using Recursion

# Python program to find the factorial of a number provided by the user
# using recursion
def factorial(x):
    """This is a recursive function
    to find the factorial of an integer"""
    if x == 1:
        return 1
    else:
        # recursive call to the function
        return (x * factorial(x-1))
# change the value for a different result
num = 7
# to take input from the user
# num = int(input("Enter a number: "))
# call the factorial function
result = factorial(num)
print("The factorial of", num, "is", result)

Python Program to Display Fibonacci Sequence Using Recursion

Source Code

# Python program to display the Fibonacci sequence
def recur_fibo(n):
   if n <= 1:
       return n
   else:
       return(recur_fibo(n-1) + recur_fibo(n-2))
nterms = 10
# check if the number of terms is valid
if nterms <= 0:
   print("Plese enter a positive integer")
else:
   print("Fibonacci sequence:")
   for i in range(nterms):
       print(recur_fibo(i))

Python Program to Print the Fibonacci sequence

Source Code

# Program to display the Fibonacci sequence up to n-th term
nterms = int(input("How many terms? "))
# first two terms
n1, n2 = 0, 1
count = 0
# check if the number of terms is valid
if nterms <= 0:
   print("Please enter a positive integer")
# if there is only one term, return n1
elif nterms == 1:
   print("Fibonacci sequence upto",nterms,":")
   print(n1)
# generate fibonacci sequence
else:
   print("Fibonacci sequence:")
   while count < nterms:
       print(n1)
       nth = n1 + n2
       # update values
       n1 = n2
       n2 = nth
       count += 1

Python Program to Get File Creation and Modification Date

Example 1: Using os module

import os.path, time
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)))

Python Program to Get File Creation and Modification Date

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))

Python Program to Get the File Name From the File Path

Example 1: Using os module

import os
# file name with extension
file_name = os.path.basename('/root/file.ext')
# file name without extension
print(os.path.splitext(file_name)[0])

Python Program to Get the File Name From the File Path

Example 2: Using Path module

from pathlib import Path
print(Path('/root/file.ext').stem)

Python Program to Find All File with .txt Extension Present Inside a Directory

Example 1: Using glob

import glob, os
os.chdir("my_dir")
for file in glob.glob("*.txt"):
    print(file)

Python Program to Find All File with .txt Extension Present Inside a Directory

Example 2: Using os

import os
for file in os.listdir("my_dir"):
    if file.endswith(".txt"):
        print(file)

Python Program to Find All File with .txt Extension Present Inside a Directory

Using os.walk

import os
for root, dirs, files in os.walk("my_dir"):
    for file in files:
        if file.endswith(".txt"):
            print(file)

Python Program to Flatten a Nested List

Example 1: Using List Comprehension

my_list = [[1], [2, 3], [4, 5, 6, 7]]
flat_list = [num for sublist in my_list for num in sublist]
print(flat_list)

Python Program to Flatten a Nested List

Example 2: Using Nested for Loops (non pythonic way)

my_list = [[1], [2, 3], [4, 5, 6, 7]]
flat_list = []
for sublist in my_list:
    for num in sublist:
        flat_list.append(num)
print(flat_list)

Python Program to Flatten a Nested List

Example 3: Using itertools package

import itertools
my_list = [[1], [2, 3], [4, 5, 6, 7]]
flat_list = list(itertools.chain(*my_list))
print(flat_list)

Python Program to Flatten a Nested List

Example 4: Using sum()

my_list = [[1], [2, 3], [4, 5, 6, 7]]
flat_list = sum(my_list, [])
print(flat_list)

Python Program to Flatten a Nested List

Example 5: Using lambda and reduce()

from functools import reduce
my_list = [[1], [2, 3], [4, 5, 6, 7]]
print(reduce(lambda x, y: x+y, my_list))

Python Program to Find Hash of File

Source Code to Find Hash

# Python program to find the SHA-1 message digest of a file
# importing the hashlib module
import hashlib
def hash_file(filename):
   """"This function returns the SHA-1 hash
   of the file passed into it"""
   # make a hash object
   h = hashlib.sha1()
   # open file for reading in binary mode
   with open(filename,'rb') as file:
       # loop till the end of the file
       chunk = 0
       while chunk != b'':
           # read only 1024 bytes at a time
           chunk = file.read(1024)
           h.update(chunk)
   # return the hex representation of digest
   return h.hexdigest()
message = hash_file("track1.mp3")
print(message)

Python Program to Find HCF or GCD

Source Code: Using Loops

# 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
print("The H.C.F. is", compute_hcf(num1, num2))

Python Program to Find HCF or GCD

Source Code: Using the Euclidean Algorithm

# Function to find HCF the Using Euclidian algorithm
def compute_hcf(x, y):
   while(y):
       x, y = y, x % y
   return x
hcf = compute_hcf(300, 400)
print("The HCF is", hcf)

Python Program to Print Hello world!

Source Code

# This program prints Hello, world!
print('Hello, world!')

Python Program to Access Index of a List Using for Loop

Example 1: Using enumerate

my_list = [21, 44, 35, 11]
for index, val in enumerate(my_list):
    print(index, val)

Python Program to Access Index of a List Using for Loop

Example 2: Start the indexing with non zero value

my_list = [21, 44, 35, 11]
for index, val in enumerate(my_list, start=1):
    print(index, val)

Python Program to Access Index of a List Using for Loop

Example 3: Without using enumerate()

my_list = [21, 44, 35, 11]
for index in range(len(my_list)):
    value = my_list[index]
    print(index, value)

Python Program to Iterate Over Dictionaries Using for Loop

Example 1: Access both key and value using items()

dt = {'a': 'juice', 'b': 'grill', 'c': 'corn'}
for key, value in dt.items():
    print(key, value)

Python Program to Iterate Over Dictionaries Using for Loop

Example 2: Access both key and value without using items()

dt = {'a': 'juice', 'b': 'grill', 'c': 'corn'}
for key in dt:
    print(key, dt[key])

Python Program to Iterate Over Dictionaries Using for Loop

Example 3: Access both key and value using iteritems()

dt = {'a': 'juice', 'b': 'grill', 'c': 'corn'}
for key, value in dt.iteritems():
    print(key, value)

Python Program to Iterate Over Dictionaries Using for Loop

Example 4: Return keys or values explicitly

dt = {'a': 'juice', 'b': 'grill', 'c': 'corn'}
for key in dt.keys():
    print(key)
for value in dt.values():
    print(value)

Python Program to Iterate Through Two Lists in Parallel

Example 1: Using zip (Python 3+)

list_1 = [1, 2, 3, 4]
list_2 = ['a', 'b', 'c']
for i, j in zip(list_1, list_2):
    print(i, j)

Python Program to Iterate Through Two Lists in Parallel

Example 2: Using itertools (Python 2+)

import itertools
list_1 = [1, 2, 3, 4]
list_2 = ['a', 'b', 'c']
# loop until the short loop stops
for i,j in zip(list_1,list_2):
    print(i,j)
print("\n")
# loop until the longer list stops
for i,j in itertools.zip_longest(list_1,list_2):
    print(i,j)

Python Program to Check if a Key is Already Present in a Dictionary

Using in keyword

my_dict = {1: 'a', 2: 'b', 3: 'c'}
if 2 in my_dict:
    print("present")

Python Program to Convert Kilometers to Miles

Example: Kilometers to Miles

# 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 Find the Largest Among Three Numbers

Source Code

# Python program to find the largest number among the three input numbers
# change the values of num1, num2 and num3
# for a different result
num1 = 10
num2 = 14
num3 = 12
# uncomment following lines to take three numbers from user
#num1 = float(input("Enter first number: "))
#num2 = float(input("Enter second number: "))
#num3 = float(input("Enter third number: "))
if (num1 >= num2) and (num1 >= num3):
   largest = num1
elif (num2 >= num1) and (num2 >= num3):
   largest = num2
else:
   largest = num3
print("The largest number is", largest)

Python Program to Find LCM

Program to Compute LCM

# Python Program to find the L.C.M. of two input number
def compute_lcm(x, y):
   # choose the greater number
   if x > y:
       greater = x
   else:
       greater = y
   while(True):
       if((greater % x == 0) and (greater % y == 0)):
           lcm = greater
           break
       greater += 1
   return lcm
num1 = 54
num2 = 24
print("The L.C.M. is", compute_lcm(num1, num2))

Python Program to Find LCM

Program to Compute LCM Using GCD

# Python program to find the L.C.M. of two input number
# This function computes GCD 
def compute_gcd(x, y):
   while(y):
       x, y = y, x % y
   return x
# This function computes LCM
def compute_lcm(x, y):
   lcm = (x*y)//compute_gcd(x,y)
   return lcm
num1 = 54
num2 = 24 
print("The L.C.M. is", compute_lcm(num1, num2))

Python Program to Check Leap Year

Source Code

# Python program to check if year is a leap year or not
year = 2000
# To get year (integer input) from the user
# year = int(input("Enter a year: "))
# divided by 100 means century year (ending with 00)
# century year divided by 400 is leap year
if (year % 400 == 0) and (year % 100 == 0):
    print("{0} is a leap year".format(year))
# not divided by 100 means not a century year
# year divided by 4 is a leap year
elif (year % 4 ==0) and (year % 100 != 0):
    print("{0} is a leap year".format(year))
# if not divided by both 400 (century year) and 4 (not century year)
# year is not leap year
else:
    print("{0} is not a leap year".format(year))

Python Program to Get Line Count of a File

Example 2: Using list comprehension

num_of_lines = sum(1 for l in open('my_file.txt'))
print(num_of_lines)

Python Program to Split a List Into Evenly Sized Chunks

Example 1: Using yield

def split(list_a, chunk_size):
  for i in range(0, len(list_a), chunk_size):
    yield list_a[i:i + chunk_size]
chunk_size = 2
my_list = [1,2,3,4,5,6,7,8,9]
print(list(split(my_list, chunk_size)))

Python Program to Split a List Into Evenly Sized Chunks

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))

Python Program to Get the Last Element of the List

Using negative indexing

my_list = ['a', 'b', 'c', 'd', 'e']
# print the last element
print(my_list[-1])

Python Program to Slice Lists

Get all the Items

my_list = [1, 2, 3, 4, 5]
print(my_list[:])

Python Program to Slice Lists

Get all the Items After a Specific Position

my_list = [1, 2, 3, 4, 5]
print(my_list[2:])

Python Program to Slice Lists

Get all the Items Before a Specific Position

my_list = [1, 2, 3, 4, 5]
print(my_list[:2])

Python Program to Slice Lists

Get all the Items from One Position to Another Position

my_list = [1, 2, 3, 4, 5]
print(my_list[2:4])

Python Program to Slice Lists

Get the Items at Specified Intervals

my_list = [1, 2, 3, 4, 5]
print(my_list[::2])

Python Program to Convert Two Lists Into a Dictionary

Example 1: Using zip and dict methods

index = [1, 2, 3]
languages = ['python', 'c', 'c++']
dictionary = dict(zip(index, languages))
print(dictionary)

Python Program to Convert Two Lists Into a Dictionary

Example 2: Using list comprehension

index = [1, 2, 3]
languages = ['python', 'c', 'c++']
dictionary = {k: v for k, v in zip(index, languages)}
print(dictionary)

Python Program to Merge Two Dictionaries

Example 1: Using the | Operator

dict_1 = {1: 'a', 2: 'b'}
dict_2 = {2: 'c', 4: 'd'}
print(dict_1 | dict_2)

Python Program to Merge Two Dictionaries

Example 2: Using the ** Operator

dict_1 = {1: 'a', 2: 'b'}
dict_2 = {2: 'c', 4: 'd'}
print({**dict_1, **dict_2})

Python Program to Merge Two Dictionaries

Example 3: Using copy() and update()

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)

Python Program to Merge Mails

Source Code to Merge Mails

# Python program to mail merger
# Names are in the file names.txt
# Body of the mail is in body.txt
# open names.txt for reading
with open("names.txt", 'r', encoding='utf-8') as names_file:
    # open body.txt for reading
    with open("body.txt", 'r', encoding='utf-8') as body_file:
        # read entire content of the body
        body = body_file.read()
        # iterate over names
        for name in names_file:
            mail = "Hello " + name.strip() + "\n" + body
            # write the mails to individual files
            with open(name.strip()+".txt", 'w', encoding='utf-8') as mail_file:
                mail_file.write(mail)

Python Program to Create a Long Multiline String

Example 1: Using triple quotes

my_string = '''The only way to
learn to program is
by writing code.'''
print(my_string)

Python Program to Create a Long Multiline 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)

Python Program to Create a Long Multiline String

Example 3: Using \

my_string = "The only way to \n" \
        	"learn to program is \n" \
        	"by writing code."
print(my_string)



Write Your Comments or Suggestion...