Python Programming Lab.
Python Programming Lab.
Python Programming Lab.
Python is copyrighted. Like Perl, Python source code is now available under the
GNU General Public License (GPL).
Python is now maintained by a core development team at the institute, although
Guido van Rossum still holds a vital role in directing its progress.
Python Features:
Python's features include −
• Easy-to-learn − Python has few keywords, simple structure, and a clearly
defined syntax.
This allows the student to pick up the language quickly.
• Easy-to-read − Python code is more clearly defined and visible to the eyes.
• Easy-to-maintain − Python's source code is fairly easy-to-maintain.
• A broad standard library − Python's bulk of the library is very portable and
cross-platform compatible on UNIX, Windows, and Macintosh.
• Interactive Mode − Python has support for an interactive mode which allows
interactive testing and debugging of snippets of code.
• Portable − Python can run on a wide variety of hardware platforms and has the
same interface on all platforms.
• Extendable − can add low-level modules to the Python interpreter. These
modules enable programmers to add to or customize their tools to be more efficient.
• Databases − Python provides interfaces to all major commercial databases.
• GUI Programming − Python supports GUI applications that can be created and
ported to many system calls, libraries and windows systems, such as Windows MFC,
Macintosh, and the X Window system of Unix.
• Scalable − Python provides a better structure and support for large programs
than shell scripting.
Apart from the above-mentioned features, Python has a big list of good features, few
are listed below −
• It supports functional and structured programming methods as well as OOP.
• It can be used as a scripting language or can be compiled to byte-code for
building large applications.
• It provides very high-level dynamic data types and supports dynamic type
checking.
• It supports automatic garbage collection.
• It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
First Python Program:
1. Open notepad and type following program Print (“Hello World”)
2. Save above program with name.py
3. Open command prompt and change path to python program location
4. Type “python name.py” (without quotes) to run the program.
Operators are the constructs which can manipulate the value of operands.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called
operator.
Python Variables: Declare, Concatenate, Global & Local:
A Python variable is a reserved memory location to store values. In other words,
a variable in a python program gives data to the computer for processing.
Every value in Python has a datatype. Different data types in Python are Numbers,
List, Tuple, Strings, Dictionary, etc. Variables can be declared by any name or even
alphabets like a, aa, abc, etc. How to Declare and use a Variable
Let see an example. We will declare variable "a" and print it. a=100
print a
Python code:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))
Output:
Enter first number: 56
Enter Second number: 90
Enter Third number: 67
The largest number is: 90
Output:
Enter the principal amount : 100
Enter the number of years : 20.5
Enter the rate of interest : 33
Simple interest : 676.5
Output:
Enter the principle amount: 100
Result: Python Program for simple & Compound Interest successfully executed.
Output:
Enter temperature in Celsius: 37.0
37.0 Celsius is equal to 98.6 degree Fahrenheit
Aim: Python Program to find sum of even and odd numbers of a given number.
Python code:
number = int(input("Enter a number : "))
even_sum=0
odd_sum =0
for i in range (1, number+1):
if (i % 2 ==0):
even_sum = even_sum +i
else:
odd_sum =odd_sum+i
print("sum of even numbers : ",even_sum)
print("sum of odd numbers : ",odd_sum)
Output:
Enter a number : 10
sum of even numbers : 30
sum of odd numbers : 25
Result: Python Program to find sum of even and odd numbers of a given number
successfully executed.
Output:
Output:
Output:
Enter a number: 4
4 is not a prime number
2 times 2 is 4
Enter a number: 7
7 is a prime number
Result: Python Program to find the given number is Prime or not successfully
executed.
Output:
Please Enter any Number: 12345
Reverse of a Given number is = 54321
12345 is not a Palindrome Number
Output:
Enter a number: 10
The sum is 55
Aim: Python Program to find search element is found or not using Linear
Search.
Python code:
def linear_Search(list1, n, key):
for i in range(0, n):
if (list1[i] == key):
return i
return -1
list1 = []
num=int(input("how many Elements : "))
for i in range(num):
numbers=int(input("Enter any element "+str(i)+ " : "))
list1.append(numbers)
n = len(list1)
res = linear_Search(list1, n, key)
if(res == -1):
print("Element not found")
else:
print("Element found at index: ", res)
.
Output:
how many Elements : 5
Enter any element 0 : 12
Enter any element 1 : 25
Enter any element 2 : 32
Enter any element 3 : 5
Enter any element 4 : 56
Enter Search Element: 32
Element found at index: 2
Result: Python Program to find search element is found or not using Linear
Search successfully executed
Aim: Python Program to find search element is found or not using Binary
Search.
Python code:
def binary_search(list1, n):
low = 0
high = len(list1) - 1
mid = 0
while low <= high:
mid = (high + low) // 2
if list1[mid] < n:
low = mid + 1
return -1
list1 = [ ]
num=int(input("how many elements : "))
for i in range(num):
numbers=int(input("Enter any sorted element "+str(i)+ " : "))
list1.append(numbers)
result = binary_search(list1, n)
if result != -1:
print("Element is present at index :", result)
else:
print("Element is not present in list1")
Output:
how many elements : 3
Enter any sorted element 0 : 15
Enter any sorted element 1 : 36
Enter any sorted element 2 : 45
Enter Search Element: 36
Element is present at index : 1
Result: Python Program to find search element is found or not using Binary
Search successfully executed
Output:
how many numbers : 5
Enter any number : 10
Enter any number : 32
Enter any number : 56
Enter any number : 48
Enter any number : 98
sum= 244
Average = 48
The maximum element in the list : 98
The minimum element in the list : 10
Output:
Enter a Decimal number: 12
Binary equivalent:
1100
Output:
Enter the range of number: 5
0
1
1
2
3
Aim: Python Program to find the given string is Palindrome or not using
recursion.
Python code:
def isPalindrome(string) :
if len(string) == 1 :
return string
else:
return isPalindrome(string[1:])+string[0]
Output:
Enter a number: 5
The factorial of 5 is 120
Enter a number: -5
Sorry, factorial does not exist for negative numbers
Output:
Enter Any Number: 50
50 is : L
if choice == 'a':
print (num_1, " + ", num_2, " = ", add(num_1, num_2))
D:\>py calculator.py
Please select the operation.
a. Add
b. Subtract
c. Multiply
d. Divide
Please enter choice (a/ b/ c/ d): c
Please enter the first number: 12
Please enter the second number: 12
12 * 12 = 144
B.append(row)
print(B)
print("Display Array In Matrix Form")
for i in range(r2):
for j in range(c2):
print(B[i][j], end=" ")
print()
P=[[0 for i in range(c2)] for j in range(r1)]
for i in range(len(A)):
for j in range(c2):
for k in range(len(B)):
P[i][j]=P[i][j]+(A[i][k]*B[k][j]) #multiplication
#print the Addition matrix
print("Product of Matrices A and B: ")
for i in range(r1):
for j in range(c2):
print(P[i][j],end=" ")
print()
else:
print("Matrix Multiplication is not possible.")
Output:
Enter number of Rows of Matrix A: 2
Enter number of Columns of Matrix A: 2
Enter number of Rows of Matrix B: 2
Enter number of Columns of Matrix B: 2
B.append(row)
print(B)
print("Display Array In Matrix Form")
for i in range(r2):
for j in range(c2):
print(B[i][j], end=" ")
print()
S=[[0 for i in range(c2)] for j in range(r2)]
for i in range(len(A)):
for j in range(len(B)):
S[i][j]=A[i][j]+B[i][j] #Addition
#print the Addition matrix
print("Product of Matrices A and B: ")
for i in range(r1):
for j in range(c2):
print(S[i][j],end=" ")
print()
else:
print("Matrix Addition is not possible.")
Output:
Enter number of Rows of Matrix A: 2
Enter number of Columns of Matrix A: 2
Enter number of Rows of Matrix B: 2
Enter number of Columns of Matrix B: 2
Enter the element ::>
25
25
25
25
[[25, 25], [25, 25]]
Display Array In Matrix Form
25 25
25 25
Enter the element ::>
32
32
32
32
[[32, 32], [32, 32]]
Display Array In Matrix Form
32 32
32 32
Product of Matrices A and B:
57 57
57 57
Output:
Enter number of Rows of Matrix A: 3
Enter number of Columns of Matrix A: 2
Aim: Python Program for swap first and last element of a List.
Python code:
a=[ ]
n=int(input("Enter the number of elements in the list :"))
for x in range(0,n):
element=int(input(" Enter the element" +str(x+1) +" : "))
a.append(element)
temp=a[0]
a[0]=a[n-1]
a[n-1]=temp
print(" new list is :")
print(a)
Output:
Enter the number of elements in the list :4
Enter the element1 : 10
Enter the element2 : 25
Enter the element3 : 63
Enter the element4 : 98
new list is :
[98, 25, 63, 10]
Result: Python Program for swap first and last element of a List successfully
executed.
Aim: Python program to Check if the given element is present in tuple or not..
Python code:
test_tup = (10, 4, 5, 6, 8)
# printing original tuple
print("The original tuple : " + str(test_tup))
N = int(input("value to be checked:"))
res = False
for ele in test_tup :
if N == ele :
res = True
break
print("Does contain required value ? : " + str(res))
Output:
The original tuple : (10, 4, 5, 6, 8)
value to be checked:5
Does contain required value ? : True
Result: Python program to to sort a list of tuples alphabetically and check if the
given element is present in tuple or not executed successfully.
Aim: Python Program to read a number n and print the natural numbers
Summation pattern.
Python code:
n=int(input("Enter a number: "))
for j in range(1,n+1):
a=[ ]
for i in range(1,j+1):
print(i,sep=" ",end=" ")
if(i<j):
print("+",sep=" ",end=" ")
a.append(i)
print("=",sum(a))
print( )
Output:
Enter a number: 5
1=1
1+2=3
1+2+3=6
1 + 2 + 3 + 4 = 10
1 + 2 + 3 + 4 + 5 = 15
Result: Python Program to read a number n and print the natural numbers
Summation pattern executed successfully.
Aim: Python Program to Read a String from the User and Append it into a
File.
Python code:
fname = input("Enter file name: ")
file1=open(fname,"a")
c=input("Enter string to append: \n");
file1.write("\n")
file1.write(c)
file1.close()
print("Contents of appended file:");
file2=open(fname,'r')
line1=file2.readline()
while(line1!=""):
print(line1)
line1=file2.readline()
file2.close()
Output:
Aim: Python Program to Take in Two Strings and Display the Larger String
Without Using Built-in Functions.
Python code:
string1 = input('Please enter the name of first string:\n')
string2 = input('Please enter the name of second string:\n')
Output:
Enter string: Hai Civil Engineering Students.
H : ['Hai']
C : ['Civil']
E : ['Engineering']
S : ['Students.']
Aim: Python Program that Reads a Text File and Counts the Number of
Times a Certain Letter Appears in the Text File.
Python Code:
fname = input("Enter file name: ")
l=input("Enter letter to be searched:")
k=0
with open(fname, 'r') as f:
for line in f:
words = line.split()
for i in words:
for letter in i:
if(letter==l):
k=k+1
print("Occurrences of the letter:")
print(k)
Output:
Enter file name: civil2.txt
Enter letter to be searched:h
Occurrences of the letter:
4
Result: Python Program that Reads a Text File and Counts the Number of
Times a Certain Letter Appears in the Text File executed successfully.
Aim: Python Program to print all the numbers present in a text file.
Python Code:
fname = input("Enter file name: ")
with open(fname, 'r') as f:
for line in f:
words = line.split()
for i in words:
for letter in i:
if(letter.isdigit()):
print(letter)
Output:
Result: Python Program to print all the numbers present in a text file executed
successfully.
The Logo programming language was popular among the kids because it enables us to
draw attractive graphs to the screen in the simple way. It is like a little object on the
screen, which can move according to the desired position. Similarly, turtle library
comes with the interactive feature that gives the flexibility to work with Python.
In this tutorial, we will learn the basic concepts of the turtle library, how to set the
turtle up on a computer, programming with the Python turtle library, few important
turtle commands, and develop a short but attractive design using the Python turtle
library.
Program(i):drawing a star
output:
output:
Program(iii):Drawing a hexagon
# import turtle library
import turtle
polygon = turtle.Turtle()
my_num_sides = 6
my_side_length = 70
my_angle = 360.0 / my_num_sides
fori in range(my_num_sides):
polygon.forward(my_side_length)
polygon.right(my_angle)
turtle.done()
output:
output:
Output: