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 Return Multiple Values From a Function

Example 1: Return values using comma

def name():
    return "John","Armin"
# print the tuple with the returned values
print(name())
# get the individual items
name_1, name_2 = name()
print(name_1, name_2)

Python Program to Return Multiple Values From a Function

Example 2: Using a dictionary

def name():
    n1 = "John"
    n2 = "Armin"
    return {1:n1, 2:n2}
names = name()
print(names)

Python Program to Display the multiplication Table

Source Code

# Multiplication table (from 1 to 10) in Python
num = 12
# To take input from the user
# num = int(input("Display multiplication table of? "))
# Iterate 10 times from i = 1 to 10
for i in range(1, 11):
   print(num, 'x', i, '=', num*i)

Python Program to Multiply Two Matrices

Source Code: Matrix Multiplication using Nested Loop

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

Python Program to Multiply Two Matrices

Source Code: Matrix Multiplication Using Nested List Comprehension

# Program to multiply two matrices using list comprehension
# 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 = [[sum(a*b for a,b in zip(X_row,Y_col)) for Y_col in zip(*Y)] for X_row in X]
for r in result:
   print(r)

Python Program to Find Sum of Natural Numbers Using Recursion

Source Code

# Python program to find the sum of natural using recursive function
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))

Python Program to Find Numbers Divisible by Another Number

Source Code

# Take a list of numbers
my_list = [12, 65, 54, 39, 102, 339, 221,]
# use anonymous function to filter
result = list(filter(lambda x: (x % 13 == 0), my_list))
# display the result
print("Numbers divisible by 13 are",result)

Python Program to Count the Number of Occurrence of a Character in String

Example 1: Using a for loop

count = 0
my_string = "Programiz"
my_char = "r"
for i in my_string:
    if i == my_char:
        count += 1
print(count)

Python Program to Count the Number of Occurrence of a Character in String

Example 2: Using method count()

my_string = "Programiz"
my_char = "r"
print(my_string.count(my_char))

Python Program to Count the Number of Digits Present In a Number

Example 1: Count Number of Digits in an Integer using while loop

num = 3452
count = 0
while num != 0:
    num //= 10
    count += 1
print("Number of digits: " + str(count))

Python Program to Count the Number of Digits Present In a Number

Example 2: Using inbuilt methods

num = 123456
print(len(str(num)))

Python Program to Count the Occurrence of an Item in a List

Using count() method

freq = ['a', 1, 'a', 4, 3, 2, 'a'].count('a')
print(freq)

Python Program to Check if a Number is Odd or Even

Source Code

# 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 = int(input("Enter a number: "))
if (num % 2) == 0:
   print("{0} is Even".format(num))
else:
   print("{0} is Odd".format(num))

Python Program to Check Whether a String is Palindrome or Not

Source Code

# Program to check if a string is palindrome or not
my_str = 'aIbohPhoBiA'
# make it suitable for caseless comparison
my_str = my_str.casefold()
# reverse the string
rev_str = reversed(my_str)
# check if the string is equal to its reverse
if list(my_str) == list(rev_str):
   print("The string is a palindrome.")
else:
   print("The string is not a palindrome.")

Python Program to Compute all the Permutation of the String

Example 1: Using recursion

def get_permutation(string, i=0):
    if i == len(string):   	 
        print("".join(string))
    for j in range(i, len(string)):
        words = [c for c in string]
   
        # swap
        words[i], words[j] = words[j], words[i]
   	 
        get_permutation(words, i + 1)
print(get_permutation('yup'))

Python Program to Compute all the Permutation of the String

Example 2: Using itertools

from itertools import permutations
words = [''.join(p) for p in permutations('pro')]
print(words)

Python Program to Check if a Number is Positive, Negative or 0

Source Code: Using if...elif...else

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 a Number is Positive, Negative or 0

Source Code: Using Nested if

num = float(input("Enter a number: "))
if num >= 0:
   if num == 0:
       print("Zero")
   else:
       print("Positive number")
else:
   print("Negative number")

Python Program to Display Powers of 2 Using Anonymous Function

Source Code

# Display the powers of 2 using anonymous function
terms = 10
# Uncomment code below to take input from the user
# terms = int(input("How many terms? "))
# use anonymous function
result = list(map(lambda x: 2 ** x, range(terms)))
print("The total terms are:",terms)
for i in range(terms):
   print("2 raised to power",i,"is",result[i])

Python Program to Compute the Power of a Number

Example 1: Calculate power of a number using a while loop

base = 3
exponent = 4
result = 1
while exponent != 0:
    result *= base
    exponent-=1
print("Answer = " + str(result))

Python Program to Compute the Power of a Number

Example 2: Calculate power of a number using a for loop

base = 3
exponent = 4
result = 1
for exponent in range(exponent, 0, -1):
    result *= base
print("Answer = " + str(result))

Python Program to Compute the Power of a Number

Example 3: Calculate the power of a number using pow() function

base = 3
exponent = -4
result = pow(base, exponent)
print("Answer = " + str(result))

Python Program to Print all Prime Numbers in an Interval

Source Code

# Python program to display all the prime numbers within an interval
lower = 900
upper = 1000
print("Prime numbers between", lower, "and", upper, "are:")
for num in range(lower, upper + 1):
   # all prime numbers are greater than 1
   if num > 1:
       for i in range(2, num):
           if (num % i) == 0:
               break
       else:
           print(num)

Python Program to Check Prime Number

Example 1: Using a flag variable

# Program to check if a number is prime or not
num = 29
# To take input from the user
#num = int(input("Enter a number: "))
# define a flag variable
flag = False
# prime numbers are greater than 1
if num > 1:
    # check for factors
    for i in range(2, num):
        if (num % i) == 0:
            # if factor is found, set flag to True
            flag = True
            # break out of loop
            break
# check if flag is True
if flag:
    print(num, "is not a prime number")
else:
    print(num, "is a prime number")

Python Program to Check Prime Number

Example 2: Using a for...else statement

# Program to check if a number is prime or not
num = 407
# To take input from the user
#num = int(input("Enter a number: "))
# prime numbers are greater than 1
if num > 1:
   # check for factors
   for i in range(2,num):
       if (num % i) == 0:
           print(num,"is not a prime number")
           print(i,"times",num//i,"is",num)
           break
   else:
       print(num,"is a prime number")
       
# if input number is less than
# or equal to 1, it is not prime
else:
   print(num,"is not a prime number")

Python Program to Print Output Without a Newline

Using end keyword

# print each statement on a new line
print("Python")
print("is easy to learn.")
# new line
print()
# print both the statements on a single line
print("Python", end=" ")
print("is easy to learn.")

Python Program to Create Pyramid Patterns

Example 1: Program to print half pyramid using *

*
* *
* * *
* * * *
* * * * *

Python Program to Create Pyramid Patterns

Source Code

rows = int(input("Enter number of rows: "))
for i in range(rows):
    for j in range(i+1):
        print("* ", end="")
    print("\n")

Python Program to Create Pyramid Patterns

Example 2: Program to print half pyramid a using numbers

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

Python Program to Create Pyramid Patterns

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

Python Program to Create Pyramid Patterns

Example 3: Program to print half pyramid using alphabets

A
B B
C C C
D D D D
E E E E E

Python Program to Create Pyramid Patterns

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

Python Program to Create Pyramid Patterns

Example 4: Inverted half pyramid using *

* * * * *
* * * *
* * *
* *
*

Python Program to Create Pyramid Patterns

Source Code

rows = int(input("Enter number of rows: "))
for i in range(rows, 0, -1):
    for j in range(0, i):
        print("* ", end=" ")
    
    print("\n")

Python Program to Create Pyramid Patterns

Example 5: Inverted half pyramid using numbers

1 2 3 4 5
1 2 3 4
1 2 3
1 2
1

Python Program to Create Pyramid Patterns

Source Code

rows = int(input("Enter number of rows: "))
for i in range(rows, 0, -1):
    for j in range(1, i+1):
        print(j, end=" ")
    
    print("\n")

Python Program to Create Pyramid Patterns

Example 6: Program to print full pyramid using *

        *
      * * *
    * * * * *
  * * * * * * *
* * * * * * * * *

Python Program to Create Pyramid Patterns

Source Code

rows = int(input("Enter number of rows: "))
k = 0
for i in range(1, rows+1):
    for space in range(1, (rows-i)+1):
        print(end="  ")
   
    while k!=(2*i-1):
        print("* ", end="")
        k += 1
   
    k = 0
    print()

Python Program to Create Pyramid Patterns

Example 7: Full Pyramid of Numbers

        1 
      2 3 2 
    3 4 5 4 3 
  4 5 6 7 6 5 4 
5 6 7 8 9 8 7 6 5

Python Program to Create Pyramid Patterns

Source Code

rows = int(input("Enter number of rows: "))
k = 0
count=0
count1=0
for i in range(1, rows+1):
    for space in range(1, (rows-i)+1):
        print("  ", end="")
        count+=1
    
    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()

Python Program to Create Pyramid Patterns

Example 8: Inverted full pyramid of *

* * * * * * * * *
  * * * * * * *
    * * * * *
      * * *
        *

Python Program to Create Pyramid Patterns

Source Code

rows = int(input("Enter number of rows: "))
for i in range(rows, 1, -1):
    for space in range(0, rows-i):
        print("  ", end="")
    for j in range(i, 2*i-1):
        print("* ", end="")
    for j in range(1, i-1):
        print("* ", end="")
    print()

Python Program to Create Pyramid Patterns

Example 9: Pascal's Triangle

           1
         1   1
       1   2   1
     1   3   3    1
   1  4    6   4   1
 1  5   10   10  5   1

Python Program to Create Pyramid Patterns

Source Code

rows = int(input("Enter number of rows: "))
coef = 1
for i in range(1, rows+1):
    for space in range(1, rows-i+1):
        print(" ",end="")
    for j in range(0, i):
        if j==0 or i==0:
            coef = 1
        else:
            coef = coef * (i - j)//j
        print(coef, end = " ")
    print()

Python Program to Create Pyramid Patterns

Example 10: Floyd's Triangle

1
2 3
4 5 6
7 8 9 10

Python Program to Create Pyramid Patterns

Source Code

rows = int(input("Enter number of rows: "))
number = 1
for i in range(1, rows+1):
    for j in range(1, i+1):
        print(number, end=" ")
        number += 1
    print()

Python Program to Solve Quadratic Equation

Source Code

# Solve the quadratic equation ax**2 + bx + c = 0
# import complex math module
import cmath
a = 1
b = 5
c = 6
# calculate the discriminant
d = (b**2) - (4*a*c)
# find two solutions
sol1 = (-b-cmath.sqrt(d))/(2*a)
sol2 = (-b+cmath.sqrt(d))/(2*a)
print('The solution are {0} and {1}'.format(sol1,sol2))

Python Program to Randomly Select an Element From the List

Example 1: Using random module

import random
my_list = [1, 'a', 32, 'c', 'd', 31]
print(random.choice(my_list))

Python Program to Randomly Select an Element From the List

Example 2: Using secrets module

import secrets
my_list = [1, 'a', 32, 'c', 'd', 31]
print(secrets.choice(my_list))

Python Program to Generate a Random Number

Source Code

# Program to generate a random number between 0 and 9
# importing the random module
import random
print(random.randint(0,9))

Python Program Read a File Line by Line Into a List

Example 2: Using for loop and list comprehension

with open('data_file.txt') as f:
    content_list = [line for line in f]
print(content_list)
# removing the characters
with open('data_file.txt') as f:
    content_list = [line.rstrip() for line in f]
print(content_list)

Python Program to Remove Duplicate Element From a List

Example 1: Using set()

list_1 = [1, 2, 1, 4, 6]
print(list(set(list_1)))

Python Program to Remove Duplicate Element From a List

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

Python Program to Remove Punctuations From a String

Source Code

# define punctuation
punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
my_str = "Hello!!!, he said ---and went."
# To take input from the user
# my_str = input("Enter a string: ")
# remove punctuation from the string
no_punct = ""
for char in my_str:
   if char not in punctuations:
       no_punct = no_punct + char
# display the unpunctuated string
print(no_punct)

Python Program to Represent enum

Using enum module

from enum import Enum
class Day(Enum):
    MONDAY = 1
    TUESDAY = 2
    WEDNESDAY = 3
# print the enum member
print(Day.MONDAY)
# get the name of the enum member
print(Day.MONDAY.name)
# get the value of the enum member
print(Day.MONDAY.value)

Python Program to Find the Size (Resolution) of a Image

Source Code of Find Resolution of JPEG Image

def jpeg_res(filename):
   """"This function prints the resolution of the jpeg image file passed into it"""
   # open image for reading in binary mode
   with open(filename,'rb') as img_file:
       # height of image (in 2 bytes) is at 164th position
       img_file.seek(163)
       # read the 2 bytes
       a = img_file.read(2)
       # calculate height
       height = (a[0] << 8) + a[1]
       # next 2 bytes is width
       a = img_file.read(2)
       # calculate width
       width = (a[0] << 8) + a[1]
   print("The resolution of the image is",width,"x",height)
jpeg_res("img1.jpg")

Python Program to Reverse a Number

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

Python Program to Reverse a Number

Example 2: Using String slicing

num = 123456
print(str(num)[::-1])

Python Program to Illustrate Different Set Operations

Source Code

# Program to perform different set operations like in mathematics
# define three sets
E = {0, 2, 4, 6, 8};
N = {1, 2, 3, 4, 5};
# 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)
# set symmetric difference
print("Symmetric difference of E and N is",E ^ N)

Python Program to Shuffle Deck of Cards

Source Code

# Python program to shuffle a deck of card
# importing modules
import itertools, random
# make a deck of cards
deck = list(itertools.product(range(1,14),['Spade','Heart','Diamond','Club']))
# shuffle the cards
random.shuffle(deck)
# draw five cards
print("You got:")
for i in range(5):
   print(deck[i][0], "of", deck[i][1])

Python Program to Sort a Dictionary by Value

Example 1: Sort the dictionary based on values

dt = {5:4, 1:6, 6:3}
sorted_dt = {key: value for key, value in sorted(dt.items(), key=lambda item: item[1])}
print(sorted_dt)

Python Program to Sort a Dictionary by Value

Example 2: Sort only the values

dt = {5:4, 1:6, 6:3}
sorted_dt_value = sorted(dt.values())
print(sorted_dt_value)

Python Program to Find the Square Root

Example: For positive numbers

# Python Program to calculate the square root
# Note: change this value for a different result
num = 8 
# To take the input from the user
#num = float(input('Enter a number: '))
num_sqrt = num ** 0.5
print('The square root of %0.3f is %0.3f'%(num ,num_sqrt))

Python Program to Find the Square Root

Source code: For real or complex numbers

# Find square root of real or complex numbers
# Importing the complex math module
import cmath
num = 1+2j
# To take input from the user
#num = eval(input('Enter a number: '))
num_sqrt = cmath.sqrt(num)
print('The square root of {0} is {1:0.3f}+{2:0.3f}j'.format(num ,num_sqrt.real,num_sqrt.imag))

Python Program to Convert String to Datetime

Example 1: Using datetime module

from datetime import datetime
my_date_string = "Mar 11 2011 11:31AM"
datetime_object = datetime.strptime(my_date_string, '%b %d %Y %I:%M%p')
print(type(datetime_object))
print(datetime_object)

Python Program to Convert String to Datetime

Example 2: Using dateutil module

from dateutil import parser
date_time = parser.parse("Mar 11 2011 11:31AM")
print(date_time)
print(type(date_time))

Python Program to Parse a String to a Float or Int

Example 1: Parse string into integer

balance_str = "1500"
balance_int = int(balance_str)
# print the type
print(type(balance_int))
# print the value
print(balance_int)

Python Program to Parse a String to a Float or Int

Example 2: Parse string into float

balance_str = "1500.4"
balance_float = float(balance_str)
# print the type
print(type(balance_float))
# print the value
print(balance_float)

Python Program to Parse a String to a Float or Int

Example 3: A string float numeral into integer

balance_str = "1500.34"
balance_int = int(float(balance_str))
# print the type
print(type(balance_int))
# print the value
print(balance_int)

Python Program to Get a Substring of a String

Using String slicing

my_string = "I love python."
# prints "love"
print(my_string[2:6])
# prints "love python."
print(my_string[2:])
# prints "I love python"
print(my_string[:-1])

Python Program to Find the Sum of Natural Numbers

Source Code

# Sum of natural numbers up to num
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)

Python Program to Swap Two Variables

Source Code: Using a temporary variable

# Python program to swap two variables
x = 5
y = 10
# To take inputs from the user
#x = input('Enter value of x: ')
#y = input('Enter value of y: ')
# create a temporary variable and swap the values
temp = x
x = y
y = temp
print('The value of x after swapping: {}'.format(x))
print('The value of y after swapping: {}'.format(y))

Python Program to Transpose a Matrix

Matrix Transpose using Nested Loop

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

Python Program to Transpose a Matrix

Matrix Transpose using Nested List Comprehension

''' Program to transpose a matrix using list comprehension'''
X = [[12,7],
    [4 ,5],
    [3 ,8]]
result = [[X[j][i] for j in range(len(X))] for i in range(len(X[0]))]
for r in result:
   print(r)

Python Program to Trim Whitespace From a String

Example 1: Using strip()

my_string = " Python "
print(my_string.strip())

Python Program to Trim Whitespace From a String

Example 2: Using regular expression

import re
my_string  = " Hello Python "
output = re.sub(r'^\s+|\s+$', '', my_string)
print(output)



Write Your Comments or Suggestion...