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

example programs

example programs

Uploaded by

kiruthikamphilcs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

example programs

example programs

Uploaded by

kiruthikamphilcs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

Program 1 :

# Python program to print "Hello Python"


print ('Hello Python')
Output:
Hello Python

__________________________________________________________________________________
________
Program 2:
# 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))

Output
The sum of 1.5 and 6.3 is 7.8
__________________________________________________________________________________
________
Program 3:
# 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))

Output
Enter first number: 1.5
Enter second number: 6.3
The sum of 1.5 and 6.3 is 7.8
__________________________________________________________________________________
________
Program 4:
#Python program to find the area of a triangle
Mathematical formula:
Area of a triangle = (s*(s-a)*(s-b)*(s-c))-1/2
Here is the semi-perimeter and a, b and c are three sides of the triangle.
Let's understand the following example.

# Three sides of the triangle is a, b and c:


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)
Output:
Enter first side: 5
Enter second side: 6
Enter third side: 7
The area of the triangle is 14.70
__________________________________________________________________________________
________
Program 5:
#Python program to swap two variables
P = int( input("Please enter value for P: "))
Q = int( input("Please enter value for Q: "))

# To swap the value of two variables


# we will user third variable which is a temporary variable
temp_1 = P
P=Q
Q = temp_1

print ("The Value of P after swapping: ", P)


print ("The Value of Q after swapping: ", Q)
Output:
Please enter value for P: 13
Please enter value for Q: 43
The Value of P after swapping: 43
The Value of Q after swapping: 13

__________________________________________________________________________________
________
Program 5:
#Python Program to Generate a Random Number
#Importing the random module
import random

# Using random function from the random module


n = random.random()

# Printing Results
print("Random Number between 0 to 1:", n)
print("Random Number between 0 to 1:", random.random())
print("Random Number between 0 to 1:", random.random())
Output:
Random Number between 0 to 1: 0.11835380687392505
Random Number between 0 to 1: 0.2563622979831378
Random Number between 0 to 1: 0.4344921246881883

__________________________________________________________________________________
________
Program 6:
# Generating a random integer between 0 to 50 using the randint() function
# Importing the random module
import random

# Using randint function from the random module


n = random.randint(0, 50)

# Printing Results
print("Random Number between 0 to 50:", n)
print("Random Number between 0 to 50:", random.randint(0, 50))
print("Random Number between 0 to 50:", random.randint(0, 50))
Output:
Random Number between 0 to 50: 12
Random Number between 0 to 50: 18
Random Number between 0 to 50: 8
__________________________________________________________________________________
________
Program 7:
# Python program to display calendar
import calendar and then apply the syntax
(calendar.month(yy,mm))

# Import calendar
import calendar
# Enter the month and year
yy = int(input("Enter year: "))
mm = int(input("Enter month: "))

# display the calendar


print(calendar.month(yy,mm))
Output:
__________________________________________________________________________________
________
Program 8:
# Python Program to check if a Number is Positive, Negative or Zero
# Default function to run if else condition
def NumberCheck(a):
# Checking if the number is positive
if a > 0:
print("Number given by you is Positive")
# Checking if the number is negative
elif a < 0:
print("Number given by you is Negative")
# Else the number is zero
else:
print("Number given by you is zero")
# Taking number from user
a = float(input("Enter a number as input value: "))
# Printing result
NumberCheck(a)
Output:
Enter a number as input value: -6
Number given by you is Negative
Program 8:

Python Program to Check if a Number is


#

Odd or Even
Odd and Even numbers:
If you divide a number by 2 and it gives a remainder of 0 then it is known as even number, otherwise
an odd number.
Even number examples: 2, 4, 6, 8, 10, etc.
Odd number examples:1, 3, 5, 7, 9 etc.
PauseNext
Mute
Current Time 0:00
/
Duration 18:10
Loaded: 0.37%
Â
Fullscreen
Backward Skip 10sPlay VideoForward Skip 10s
ADVERTISEMENT
ADVERTISEMENT
See this example:
num = int(input("Enter a number: "))
if (num % 2) == 0:
print("{0} is Even number".format(num))
else:
print("{0} is Odd number".format(num))
Output:

Python Class and Object


class Parrot:

# class attribute
name = ""
age = 0

# create parrot1 object


parrot1 = Parrot()
parrot1.name = "Blu"
parrot1.age = 10

# create another object parrot2


parrot2 = Parrot()
parrot2.name = "Woo"
parrot2.age = 15

# access attributes
print(f"{parrot1.name} is {parrot1.age} years old")
print(f"{parrot2.name} is {parrot2.age} years old")
Run Code
Output
Blu is 10 years old
Woo is 15 years old

Use of Inheritance in Python


# base class
class Animal:

def eat(self):
print( "I can eat!")

def sleep(self):
print("I can sleep!")

# derived class
class Dog(Animal):

def bark(self):
print("I can bark! Woof woof!!")

# Create object of the Dog class


dog1 = Dog()

# Calling members of the base class


dog1.eat()
dog1.sleep()

# Calling member of the derived class


dog1.bark();
Run Code
Output
I can eat!
I can sleep!
I can bark! Woof woof!!

Encapsulation
class Computer:

def __init__(self):
self.__maxprice = 900

def sell(self):
print("Selling Price: {}".format(self.__maxprice))

def setMaxPrice(self, price):


self.__maxprice = price

c = Computer()
c.sell()
# change the price
c.__maxprice = 1000
c.sell()

# using setter function


c.setMaxPrice(1000)
c.sell()
Run Code
Output
Selling Price: 900
Selling Price: 900
Selling Price: 1000
Polymorphism
class Polygon:
# method to render a shape
def render(self):
print("Rendering Polygon...")

class Square(Polygon):
# renders Square
def render(self):
print("Rendering Square...")

class Circle(Polygon):
# renders circle
def render(self):
print("Rendering Circle...")

# create an object of Square


s1 = Square()
s1.render()

# create an object of Circle


c1 = Circle()
c1.render()
Run Code
Output
Rendering Square...
Rendering Circle...

Lambda

# declare a lambda function


greet = lambda : print('Hello World')

# call lambda function


greet()

# Output: Hello World


# lambda that accepts one argument
greet_user = lambda name : print('Hey there,', name)

# lambda call
greet_user('Delilah')

# Output: Hey there, Delilah


ExampleGet your own Python Server
Add 10 to argument a, and return the result:
x = lambda a : a + 10
print(x(5))
Try it Yourself »
Lambda functions can take any number of arguments:
Example
Multiply argument a with argument b and return the result:
x = lambda a, b : a * b
print(x(5, 6))
Try it Yourself »
Example
Summarize argument a, b, and c and return the result:
x = lambda a, b, c : a + b + c
print(x(5, 6, 2))
Try it Yourself »

def myfunc(n):
return lambda a : a * n

mydoubler = myfunc(2)

print(mydoubler(11))
Try it Yourself »
Python program to print "Hello Python"
Python program to do arithmetical operations
Python program to find the area of a triangle
Python program to solve quadratic equation
Python program to swap two variables
Python program to generate a random number
Python program to convert kilometers to miles
Python program to convert Celsius to Fahrenheit
Python program to display calendar
Python Program to Check if a Number is Positive, Negative or Zero
Python Program to Check if a Number is Odd or Even
Python Program to Check Leap Year
Python Program to Check Prime Number
Python Program to Print all Prime Numbers in an Interval
Python Program to Find the Factorial of a Number
Python Program to Display the multiplication Table
Python Program to Print the Fibonacci sequence
Python Program to Check Armstrong Number
Python Program to Find Armstrong Number in an Interval
Python Program to Find the Sum of Natural Numbers
Python Program to Print Reverse of a String
Python Program to Print Sum of First Ten Natural Numbers

Python Function Programs


Python Program to Find LCM
Python Program to Find HCF
Python Program to Convert Decimal to Binary, Octal and Hexadecimal
Python Program To Find ASCII value of a character
Python Program to Make a Simple Calculator
Python Program to Display Calendar
Python Program to Display Fibonacci Sequence Using Recursion
Python Program to Find Factorial of Number Using Recursion
Python Program to Calculate the Power of a Number

Python Number Programs


Python program to check if the given number is a Disarium Number
Python program to print all disarium numbers between 1 to 100
Python program to check if the given number is Happy Number
Python program to print all happy numbers between 1 and 100
Python program to determine whether the given number is a Harshad Number
Python program to print all pronic numbers between 1 and 100
Python program to print first ten natural numbers.
Python Progran to check an Armstrong number or not

Python Basic Programs


Python program to print "Hello Python"
Python program to do arithmetical operations
Python program to find the area of a triangle
Python program to solve quadratic equation
Python program to swap two variables
Python program to generate a random number
Python program to convert kilometers to miles
Python program to convert Celsius to Fahrenheit
Python program to display calendar
Python Program to Check if a Number is Positive, Negative or Zero
Python Program to Check if a Number is Odd or Even
Python Program to Check Leap Year
Python Program to Check Prime Number
Python Program to Print all Prime Numbers in an Interval
Python Program to Find the Factorial of a Number
Python Program to Display the multiplication Table
Python Program to Print the Fibonacci sequence
Python Program to Check Armstrong Number
Python Program to Find Armstrong Number in an Interval
Python Program to Find the Sum of Natural Numbers
Python Program to Print Reverse of a String
Python Program to Print Sum of First Ten Natural Numbers

What is a Function in Python?


In the field of computer science, a function is a code that has a self contained block of code and
performs a concrete job or operation. Abilities of functions are made to divide program into modules
and they are reusable, this makes programming more readable, concise and convenient to debug.

Python Function Programs


Python Program to Find LCM
Python Program to Find HCF
Python Program to Convert Decimal to Binary, Octal and Hexadecimal
Python Program To Find ASCII value of a character
Python Program to Make a Simple Calculator
Python Program to Display Calendar
Python Program to Display Fibonacci Sequence Using Recursion
Python Program to Find Factorial of Number Using Recursion
Python Program to Calculate the Power of a Number
In the next section, we will see the some of number programs.

Python Number Programs


Python program to check if the given number is a Disarium Number
Python program to print all disarium numbers between 1 to 100
Python program to check if the given number is Happy Number
Python program to print all happy numbers between 1 and 100
Python program to determine whether the given number is a Harshad Number
Python program to print all pronic numbers between 1 and 100
Python program to print first ten natural numbers.
Python Progran to check an Armstrong number or not
In the next section, we will see the programs based on arrays.
Before we going to see programs of an array, lets know the what is an array.

What is an Array?
An array, one of the most important elements, is used in computer science as a fundamental data
structure in which a collection of elements is stored in the contagious memory locations and all these
data are usually of one type. The arrays give the chance to grouped and access data in a consecutive
chunk of memory space. They can be accessed through their indices or positions in the array.
Let's see the list of programs based on an arrays below:

Python Array Programs


Python program to copy all elements of one array into another array
Python program to find the frequency of each element in the array
Python program to left rotate the elements of an array
Python program to print the duplicate elements of an array
Python program to print the elements of an array
Python program to print the elements of an array in reverse order
Python program to print the elements of an array present on even position
Python program to print the elements of an array present on odd position
Python program to print the largest element in an array
Python program to print the smallest element in an array
Python program to print the number of elements present in an array
Python program to print the sum of all elements in an array
Python program to right rotate the elements of an array
Python program to sort the elements of an array in ascending order
Python program to sort the elements of an array in descending order
Python Program to Merge Two Arrays into a Single Array
Python Program to Insert an Element into an Array
Python Program to Delete an Element from an Array

Python String Programs


Python Program to Sort Words in Alphabetic Order
Python Program to Remove Punctuation From a String
Python Program to reverse a string
Python Program to convert list to string
Python Program to convert int to string
Python Program to concatenate two strings
Python Program to generate a Random String
Python Program to convert Bytes to string
Python Program to check whether given string is a palindrome or not
Python Program to print length of a string
Python Program to reverse the characters of a string
Convert the string into lowercase to uppercase
Convert the string into uppercase to lowercase
Python Program to find the occurrence of a substring within a string

Python List Programs


Python Program to append element in the list
Python Program to compare two lists
Python Program to convert list to dictionary
Python Program to remove an element from a list
Python Program to add two lists
Python Program to convert List to Set
Python Program to convert list to string
Python Program to remove duplicates from a list
Python program to print length of a list

Python programs with conditions and loops


There can be various programs on conditions and loops. A list of top useful condition and loop
programs are given below:
Python Program to Check if a Number is Positive, Negative or Zero
Python Program to Check if a Number is Odd or Even
Python Program to Check Leap Year
Python Program to Check Prime Number
Python Program to Print all Prime Numbers in an Interval
Python Program to Find the Factorial of a Number
Python Program to Display the multiplication Table
Python Program to Print the Fibonacci sequence
Python Program to Check Armstrong Number
Python Program to Find Armstrong Number in an Interval
Python Program to Find the Sum of Natural Numbers

Python Function Programs


There can be many useful function programs in python. A list of top python function programs are
given below:
Python Program to Find LCM
Python Program to Find HCF
Python Program to Convert Decimal to Binary, Octal and Hexadecimal
Python Program To Find ASCII value of a character
Python Program to Make a Simple Calculator
Python Program to Display Calendar
Python Program to Display Fibonacci Sequence Using Recursion
Python Program to Find Factorial of Number Using Recursion

Example program:
1. num = int (input ("Enter the numerator: "))
2. den = int (input ("Enter the denominator: "))
3. try:
4. res = num/den
5. except ZeroDivisionError:
6. print ("The denominator cannot be zero")
7. else:
8. print ("The result of the division:", res)
Output:
#Sample output-1-No exception rose
Enter the numerator: 3
Enter the denominator: 4
The result of the division: 0.75

#Sample output-2-Exception rose


Enter the numerator: 3
Enter the denominator: 0
The denominator cannot be zero

1. try:
2. array = [2,3,5,6]
3. print (array)
4. for i in range (0,5):
5. print ("The element in",i,"index is:",array[i])
6. except:
7. print ("Tried to access an out of bound index-check it")
8. else:
9. print("No exceptions. Well done")
10. finally:
11. print("You are now looking at the code in the finally block")
Output:
[2, 3, 5, 6]
The element in 0 index is: 2
The element in 1 index is: 3
The element in 2 index is: 5
The element in 3 index is: 6
Tried to access an out of bound index-check it
You are now looking at the code in the finally block

You might also like