0% found this document useful (0 votes)
375 views

Python Programming Examples

This document provides a summary of Python programming examples covering a wide range of concepts like simple programs, mathematical functions, lists, strings, and more. The examples are organized into sections based on the concept covered and include problems, solutions, code, and explanations. Some key areas covered include arithmetic operations, condition checking, string manipulation, list operations, mathematical functions like prime checking, and algorithms. The goal is to provide a set of example programs that teach Python programming in different domains.

Uploaded by

Ashraf Jamal
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
375 views

Python Programming Examples

This document provides a summary of Python programming examples covering a wide range of concepts like simple programs, mathematical functions, lists, strings, and more. The examples are organized into sections based on the concept covered and include problems, solutions, code, and explanations. Some key areas covered include arithmetic operations, condition checking, string manipulation, list operations, mathematical functions like prime checking, and algorithms. The goal is to provide a set of example programs that teach Python programming in different domains.

Uploaded by

Ashraf Jamal
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

Python Programming Examples

This section covers various examples in Python programming Language. These Programs examples cover a wide range of programming areas in
Computer Science. Every example program includes the problem description, problem solution, source code, program explanation and run time test
cases. These examples range from simple Python programs to Mathematical functions, lists, strings, sets, dictionary, recursions, no-recursions, file
handling, classes and objects, linked list, stacks and queues, searching and sorting, trees, heap, graphs, games, greedy algoritms and dynamic
programming.

Here’s a listing of all the Python programs covering all these areas.

1. Simple Python Programs


This section deals with Simple Python Programs. The Python programs in this section performs arithmetic operations like Addition, Multiplication and
Division on the given set of input numbers. This section also covers python programs on reversing the given number and checks whether the given
number is positive or negative number. The other programs in this section checks whether a given number is palindrome or not, prints identity matrix
and inverted star pattern, print prime numbers in a given range using sieve of eratosthenes method. It also talks about python programs on exchanging
two number values without using any temporary variables, counting the number of integers in a given number, entering the student marks in 5 subjects
and displaying the grades.

Python Program to Calculate the Average of Numbers in a Given List


Python Program to Exchange the Values of Two Numbers Without Using a
Temporary Variable
Python Program to Read a Number n and Compute n+nn+nnn
Python Program to Reverse a Given Number
Python Program to Check Whether a Number is Positive or Negative
Python Program to Take in the Marks of 5 Subjects and Display the Grade
Python Program to Print all Numbers in a Range Divisible by a Given
Number
Python Program to Read Two Numbers and Print Their Quotient and
Remainder
Python Program to Accept Three Digits and Print all Possible Combinations
from the Digits
Python Program to Print Odd Numbers Within a Given Range
Python Program to Find the Sum of Digits in a Number
Python Program to Find the Smallest Divisor of an Integer
Python Program to Count the Number of Digits in a Number
Python Program to Check if a Number is a Palindrome
Python Program to Print all Integers that Aren't Divisible by Either 2 or 3 and
Lie between 1 and 50.
Python Program to Read a Number n And Print the Series "1+2+…..+n= "
Python Program to Read a Number n and Print the Natural Numbers
Summation Pattern
Python Program to Print an Identity Matrix
Python Program to Print an Inverted Star Pattern
Python Program to Read Print Prime Numbers in a Range using Sieve of
Eratosthenes

2. Python Programming Examples on Mathematical Functions


The following section contains programs on different types of mathematical functions. These include programs to checks whether the given number is
strong number, perfect number, prime number or armstrong number. It also checks whether a given year is leap year or not. The Python programming
examples also covers programs on performing simple interest with given values, printing the largest even and odd number in the given list. Python
programs on number conversions like converting celcius temperature to farenheit temperature, gray code to binary and binary code to gray. This
section also covers python programs on finding the lcm and gcd of two numbers and also checks whether the two given numbers are amicable
numbers or not. The other programs in this section prints all prime numbers in a given range, print the pascal triangle, programs on trigonometric
functions such as sin(x) and cos(x).

Python Program to Check if a Date is Valid and Print the Incremented Date if
it is
Python Program to Compute Simple Interest Given all the Required Values
Python Program to Check Whether a Given Year is a Leap Year
Python Program to Read Height in Centimeters and then Convert the Height
to Feet and Inches
Python Program to Take the Temperature in Celcius and Covert it to
Farenheit
Python Program to Compute Prime Factors of an Integer
Python Program to Generate all the Divisors of an Integer
Python Program to Print Table of a Given Number
Python Program to Print Sum of Negative Numbers, Positive Even Numbers
and Positive Odd numbers in a List
Python Program to Print Largest Even and Largest Odd Number in a List
Python Program to Form an Integer that has the Number of Digits at Ten's
Place and the Least Significant Digit of the Entered Integer at One's Place
Python Program to Find Those Numbers which are Divisible by 7 and
Multiple of 5 in a Given Range of Numbers
Python Program to Check if a Number is an Armstrong Number
Python Program to Print the Pascal's triangle for n number of rows given by
the user
Python Program to Check if a Number is a Perfect Number
Python Program to Check if a Number is a Strong Number
Python Program to Find the LCM of Two Numbers
Python Program to Find the GCD of Two Numbers
Python Program to Compute a Polynomial Equation given that the
Coefficients of the Polynomial are stored in a List
Python Program to Check If Two Numbers are Amicable Numbers
Python Program to Find the Area of a Triangle Given All Three Sides
Python Program to Find the Gravitational Force Acting Between Two
Objects
Python Program to Check if a Number is a Prime Number
Python Program to Print all the Prime Numbers within a Given Range
Python Program to Print Numbers in a Range (1,upper) Without Using any
Loops
Python Program to Find the Sum of Sine Series
Python Program to Find the Sum of Cosine Series
Python Program to Find the Sum of First N Natural Numbers
Python Program to Find the Sum of the Series: 1 + 1/2 + 1/3 + ….. + 1/N
Python Program to Find the Sum of the Series: 1 + x^2/2 + x^3/3 + … x^n/n
Python Program to Compute the Value of Euler's Number e. Use the
Formula: e = 1 + 1/1! + 1/2! + …… 1/n!
Python Program to Determine all Pythagorean Triplets in the Range
Python Program to Search the Number of Times a Particular Number Occurs
in a List
Python Program to test Collatz Conjecture for a Given Number
Python Program to Count Set Bits in a Number
Python Program to Find Whether a Number is a Power of Two
Python Program to Clear the Rightmost Set Bit of a Number
Python Program to Generate Gray Codes using Recursion
Python Program to Convert Gray Code to Binary
Python Program to Convert Binary to Gray Code

3. Python Programming Examples on Lists


This section contains Python programs examples on Lists. List is a collection of data or information which is ordered and changeable. Lists are written
with square brackets. List is used to store the multiple data at a same time. Each element which is inside the list is called an item. The Python
programs in this section finds the largest and second largest number in the given list, it also finds the second largest number using bubble sort
algorithm. The Python programming examples also contains programs on sorting the given list according to their lengths, merging two lists and sort it,
finds the intersection of two lists. The other python programs in this section performs swapping values and removing duplicate values from the list,
program to solve maximum subarray problem using kadane’s and divide and conquer algorithms. It also talks about python programs on finding the
number which is having perfect square in a given range of numbers.

Python Program to Find the Largest Number in a List


Python Program to Find the Second Largest Number in a List
Python Program to Put Even and Odd elements in a List into Two Different
Lists
Python Program to Merge Two Lists and Sort it
Python Program to Sort the List According to the Second Element in Sublist
Python Program to Find the Second Largest Number in a List Using Bubble
Sort
Python Program to Sort a List According to the Length of the Elements
Python Program to Find the Union of two Lists
Python Program to Find the Intersection of Two Lists
Python Program to Create a List of Tuples with the First Element as the
Number and Second Element as the Square of the Number
Python Program to Find all Numbers in a Range which are Perfect Squares
and Sum of all Digits in the Number is Less than 10
Python Program to Find the Cumulative Sum of a List where the ith Element
is the Sum of the First i+1 Elements From The Original List
Python Program to Generate Random Numbers from 1 to 20 and Append
Them to the List
Python program to Sort a List of Tuples in Increasing Order by the Last
Element in Each Tuple
Python Program to Swap the First and Last Value of a List
Python Program to Remove the Duplicate Items from a List
Python Program to Read a List of Words and Return the Length of the
Longest One
Python Program to Remove the ith Occurrence of the Given Word in a List
where Words can Repeat
Python Program to Remove All Tuples in a List of Tuples with the USN
Outside the Given Range
Python Program to solve Maximum Subarray Problem using Divide and
Conquer
Python Program to solve Maximum Subarray Problem using Kadane’s
Algorithm
Python Program to Find Element Occurring Odd Number of Times in a List

4. Python Programming Examples on Strings


The Python programming examples also contains programs on Strings. Python strings are immutable it means we cannot changed once its created.
Python has a built in string class named str with many features. String is a sequence of characters that exist as an object of the class. The Python
programs in this section performs replace and remove operations in the given string, detects the string if it is anagrams by using sorted() function. This
section also covers python programs on vowels count in a given string and also calculates the string length without using any library functions, checks
whether the given string is palindrome or not. It also talks about python programs on doing calculations of upper and lower case letters count in the
given string and it also calculates how many numbers and characters are in the string. The other programs in this section performs word occurence
count in the given sentence, checks whether a given string is pangram or not, prints all string permutations in an lexicographic order with and without
using recursion.

Python Program to Replace all Occurrences of ‘a’ with $ in a String


Python Program to Remove the nth Index Character from a Non-Empty
String
Python Program to Detect if Two Strings are Anagrams
Python Program to Form a New String where the First Character and the Last
Character have been Exchanged
Python Program to Count the Number of Vowels in a String
Python Program to Take in a String and Replace Every Blank Space with
Hyphen
Python Program to Calculate the Length of a String Without Using a Library
Function
Python Program to Remove the Characters of Odd Index Values in a String
Python Program to Calculate the Number of Words and the Number of
Characters Present in a String
Python Program to Take in Two Strings and Display the Larger String
without Using Built-in Functions
Python Program to Count Number of Lowercase Characters in a String
Python Program to Check if a String is a Palindrome or Not
Python Program to Calculate the Number of Upper Case Letters and Lower
Case Letters in a String
Python Program to Check if a String is a Pangram or Not
Python Program to Accept a Hyphen Separated Sequence of Words as Input
and Print the Words in a Hyphen-Separated Sequence after Sorting them
Alphabetically
Python Program to Calculate the Number of Digits and Letters in a String
Python Program to Form a New String Made of the First 2 and Last 2
characters From a Given String
Python Program to Count the Occurrences of Each Word in a Given String
Sentence
Python Program to Check if a Substring is Present in a Given String
Python Program to Print All Permutations of a String in Lexicographic Order
without Recursion
Python Program to Print All Permutations of a String in Lexicographic Order
using Recursion

5. Python Programming Examples on Dictionary


This section contains Python programming examples on Dictionary. Dictionary is a mapping of unique keys to values. Dictionaries are mutable that
means it can be changed. To construct the dictionary we will use curly brackets {}, square brackets[] is used to index it. Key and values can be
seperated by using comma and colon between the pairs. The Python programs in this section adds a key value pair to the dictionary, concatenates two
dictionary into one, checks whether the given key is exists in dictionary or not. The Python programming examples also covers programs on dictionary
generation that contains the numbers in the format and removes the specific key from the dictionary. The other Python programs in this section
performs addition and multiplication of the items in the dictionary, count the word occurence in the given string using dictionary.

Python Program to Add a Key-Value Pair to the Dictionary


Python Program to Concatenate Two Dictionaries Into One
Python Program to Check if a Given Key Exists in a Dictionary or Not
Python Program to Generate a Dictionary that Contains Numbers (between 1
and n) in the Form (x,x*x).
Python Program to Sum All the Items in a Dictionary
Python Program to Multiply All the Items in a Dictionary
Python Program to Remove the Given Key from a Dictionary
Python Program to Form a Dictionary from an Object of a Class
Python Program to Map Two Lists into a Dictionary
Python Program to Count the Frequency of Words Appearing in a String
Using a Dictionary
Python Program to Create a Dictionary with Key as First Character and
Value as Words Starting with that Character

6. Python Programming Examples on Sets


The following section contains Python programming examples on Sets. Set is a collection of data which is unordered and unindexed. String is a
sequence of characters that exist as an object of the class. The Python programs in this section checks common letters in the given two input strings,
displays the letters which are present in the both strings. This Python programming examples in this sections covers programs on displaying the letters
present in the first string also counts the number of vowels present in the string by using sets.

Python Program to Count the Number of Vowels Present in a String using


Sets
Python Program to Check Common Letters in Two Input Strings
Python Program that Displays which Letters are in the First String but not in
the Second
Python Program that Displays which Letters are Present in Both the Strings
Python Program that Displays which Letters are in the Two Strings but not in
Both

7. Python Programs with Recursions


This section contains Python programming examples on Recursions. Recursion is the attribute that allows a method to call itself. A method that calls
itself is said to be recursive. Recursion is a method in which the solution of a problem depends on the smaller instances of the same problem. The
Python programs in this section determines whether a given number is even or odd, finds the fibonacci series and factorial number using recursion.
This programming examples in this sections covers programs on finding the lcm and gcm of two numbers using recursion and also checks whether
given number is a prime number or not. It also talks about python programs on reversing a string using recursion. The other Python programs in this
section finds the length list using recursion and also finds the sum of the given digits.

Python Program to Determine Whether a Given Number is Even or Odd


Recursively
Python Program to Determine How Many Times a Given Letter Occurs in a
String Recursively
Python Program to Find the Fibonacci Series Using Recursion
Python Program to Find the Factorial of a Number Using Recursion
Python Program to Find the Sum of Elements in a List Recursively
Python Program to Find the Binary Equivalent of a Number Recursively
Python Program to Find the Sum of the Digits of the Number Recursively
Python Program to Find the LCM of Two Numbers Using Recursion
Python Program to Find the GCD of Two Numbers Using Recursion
Python Program to Find if a Number is Prime or Not Prime Using Recursion
Python Program to Find the Product of two Numbers Using Recursion
Python Program to Find the Power of a Number Using Recursion
Python Program to Check Whether a String is a Palindrome or not Using
Recursion
Python Program to Reverse a String Using Recursion
Python Program to Flatten a Nested List using Recursion
Python Program to Find the Total Sum of a Nested List Using Recursion
Python Program to Find the Length of a List Using Recursion

8. Python Programs without Recursions


The Python programs in this section finds the fibonacci series and factorial number without using recursion. The Python programming examples also
covers programs on reversing the string without using recursion and program to find odd numbers and palindromes between a given range of numbers.
It also talks about python programs on finding the sum of given digits without using recursion.

Python Program to Find the Fibonacci Series without Using Recursion


Python Program to find the factorial of a number without recursion
Python Program to Flatten a List without using Recursion
Python Program to Reverse a String without using Recursion
Python Program to Find the Binary Equivalent of a Number without Using
Recursion
Python Program to Find All Numbers which are Odd and Palindromes
Between a Range of Numbers without using Recursion
Python Program to Find the Sum of Digits in a Number without Recursion

9. Python Programs on File Handling


This section contains Python programs examples on File Handling. File is a collection of data and information. The Python programs in this section
reads the contents of a file, count the words and lines number in a text file. This section also covers python programs on word occurrences count in a
given text file, copying and append the contents from one file to another file. The Python programming examples also covers programs on reading a
text file and find the letter apperance count in the given text file. It also talks about python programs to count blank spaces in the text file, reading the
contents of a given text file in a reverse order. The other programs in this section reads a file and capitalize first letter of every word in the given file.

Python Program to Read the Contents of a File


Python Program to Count the Number of Words in a Text File
Python Program to Count the Number of Lines in a Text File
Python Program to Read a String from the User and Append it into a File
Python Program to Count the Occurrences of a Word in a Text File
Python Program to Copy the Contents of One File into Another
Python Program that Reads a Text File and Counts the Number of Times a
Certain Letter Appears in the Text File
Python Program to Read a Text File and Print all the Numbers Present in the
Text File
Python Program to Append the Contents of One File to Another File
Python Program to Count the Number of Blank Spaces in a Text File
Python Program to Read a File and Capitalize the First Letter of Every Word
in the File
Python Program to Read the Contents of a File in Reverse Order

10. Python Programs on Classes and Objects


This section contains Python programming examples on Classes and Objects. Class can be defined as a template that describes the behavior that the
object of its type support. Class is declared by use of the class keyword. The Python programs in this section to find the rectangle area using classes
and modifies the data in list using class. The Python programming examples also covers programs on creating a class and finds the area and
perimeter of the circle and also finds all possible subsets. The other Python programs in this section creates a class in one method and prints in
another method.

Python Program to Find the Area of a Rectangle Using Classes


Python Program to Append, Delete and Display Elements of a List Using
Classes
Python Program to Create a Class and Compute the Area and the Perimeter
of the Circle
Python Program to Create a Class which Performs Basic Calculator
Operations
Python Program to Create a Class in which One Method Accepts a String
from the User and Another Prints it
Python Program to Create a Class and Get All Possible Subsets from a Set of
Distinct Integers

11. Python Programming Examples on Linked Lists


The following section gives a collection of Python Programs which are categorized into various Categories like Programs on Creating and Displaying
the Elements of a Linked List, Programs on Search and Display Functions of a Linked List, Programs on Implementation of Count, Programs on Length
and Print Operations on a Linked List, Programs on Implementation of other Data Structures using Linked List, Programs dealing with the Operations
on the Elements of a Linked List, Programs on Print, Reverse and Read Operations, Programs on Binary Tree Implementation using Linked List,
Programs on Interchange and Modify Operations, Programs on Singly Linked Lists, Programs on Circularly & Doubly Linked Lists. The following link
will guide you to the various programs that belong to the above mentioned category.
 https://www.sanfoundry.com/python-programming-examples-linked-lists/
 

12. Python Programming Examples on Stacks & Queues


In this section, we have Programs on Stack Implementation, Programs on Queue Implementation, Programs on String Implementation. The following
link contains various Python programs on Stacks & Queues under the category mentioned above.
 https://www.sanfoundry.com/python-programming-examples-stacks-queues/
 

13. Python Programming Examples on Searching and Sorting


In this section, we have various Programs on Searching and Sorting. These include Programs on Searching Algorithms, Programs on Sorting
Algorithms, Programs on Sorting using Binary Trees. The link below illustrates all the Programs that are Categorized as above.
 https://www.sanfoundry.com/python-programming-examples-searching-sorting/
 

14. Python Programming Examples on Trees


This section deals with categories of Trees. They include Programs on Tree Traversals, Programs on Heap and Binary Tree Implementation, Programs
dealing with the Nodes of a Tree, Programs on Special Properties of Binary Trees, Programs on BFS and DFS Traversals and Programs on Inorder
Traversal of a Binary Tree. The link below will guide us through all of the above mentioned Programs.
 https://www.sanfoundry.com/python-programming-examples-trees/
 
15. Python Programs on Heap
In this section, we have various Python Programs on Heap. These include Programs on binary heap, binomial tree and binomial heap. Binary heap is a
heap data structure it takes the form of a binary tree. It is mainly used to implement priority queues. Binomial heap is implemented as a set of binomial
trees which satisfies the binomial heap properties. This section also covers python programs on fibonacci heap, ternary and d-ary heap. Fibonacci
heap is a heap data structure consisting of a collection of trees. Fibonacci heap has a better amortized running time than a binomial heap. In ternary
heap each node has up to three children. Ternary Heap is implemented by using the concept of D-ary Heap.

Python Program to Implement Binary Heap


Python Program to Implement Binomial Tree
Python Program to Implement Binomial Heap
Python Program to Implement Fibonacci Heap
Python Program to Implement Ternary Heap
Python Program to Implement D-ary-Heap

16. Python Programming Examples on Graphs


This section deals with programs on Graphs. These include Programs on Connected Components using BFS, Programs on Connected Components
using DFS, Programs on Shortest Path. The link below guides us through all of these Programs.
 https://www.sanfoundry.com/python-programming-examples-graphs/
 

17. Python Programs on Games


This section contains Python programming examples on Games. These includes the implementation of tower of hanoi problem. It also talks about
python programs on solving celebrity problem and n-queen problem with and without using recursion. A celebrity is someone who doesn’t know anyone
(including themselves) but is known by everyone. N-queen problem is the problem of placing N queens on an n x n chessboard such that no queen can
attack another queen.

Python Program to Implement Tower of Hanoi


Python Program to Solve n-Queen Problem without Recursion
Python Program to Solve the Celebrity Problem
Python Program to Solve n-Queen Problem with Recursion

18. Python Programs on Greedy Algorithms


This section deals with Python programs on Greedy Algorithms. These include Python Programs on fractional knapsack and interval scheduling
problem using Greedy Algorithm. Greedy Algorithms gives optimal solution for all subproblems. But greedy algorithm cannot be used to solve all the
dynamic programming problems. This section also covers python programs on closed intervals unit and lateness minimize using greedy algorithm. In
Interval Scheduling Problem, the problems are consider as a set of tasks. Each task is represented by an interval describing that which time it needs to
be executed. Fractional Knapsack Problem is used to find the maximum total weight.

Python Program to Solve Fractional Knapsack Problem using Greedy


Algorithm
Python Program to Solve Interval Scheduling Problem using Greedy
Algorithm
Python Program to Find the Smallest Set of Unit-Length Closed Intervals
that Contains All Points using Greedy Algorithm
Python Program to Minimize Lateness using Greedy Algorithm

19. Python Programs on Dynamic Programming


This section contains Python programming examples on Dynamic programming. Dynamic programming is a method used for solving a complex
problem by breaking it down into simpler subproblems, solving each of those subproblems just once and stores their results in an array. While solving
the complex problem, if the same subproblem occurs again we can reuse the already stored result instead of recomputing its result is called
memoization. Memoization uses the top down technique to solve the problem. Tabulation uses the bottom up approach to solve the problem. The
Python programs in this section to solve rod cutting problem and matrix chain multiplication using dynamic programming with bottom up approach and
memoization. The other Python programs in this section prints fibonacci number and also finds the longest common substring using dynamic
programming.

Python Program to Solve Rod Cutting Problem using Dynamic Programming


with Memoization
Python Program to Solve Rod Cutting Problem using Dynamic Programming
with Bottom-Up Approach
Python Program to Print nth Fibonacci Number using Dynamic
Programming with Memoization
Python Program to Print nth Fibonacci Number using Dynamic
Programming with Bottom-Up Approach
Python Program to Solve Matrix-Chain Multiplication using Dynamic
Programming with Memoization
Python Program to Solve Matrix-Chain Multiplication using Dynamic
Programming with Bottom-Up Approach
Python Program to Find Longest Common Subsequence using Dynamic
Programming with Memoization
Python Program to Find Longest Common Subsequence using Dynamic
Programming with Bottom-Up Approach
Python Program to Find Longest Common Substring using Dynamic
Programming with Memoization
Python Program to Find Longest Common Substring using Dynamic
Programming with Bottom-Up Approach
Python Program to Solve 0-1 Knapsack Problem using Dynamic
Programming with Bottom-Up Approach
Python Program to Solve 0-1 Knapsack Problem using Dynamic
Programming with Memoization
Python Program to Count all Paths in a Grid with Holes using Dynamic
Programming with Memoization
Python Program to Count all Paths in a Grid with Holes using Dynamic
Programming with Bottom-Up Approach

You might also like