Python Programming Lab.

Download as pdf or txt
Download as pdf or txt
You are on page 1of 58

DATE: EXP NO: Page No:

Introduction to Python Programming.

Python is a general-purpose interpreted, interactive, object-oriented, and high-


level Programming language. It was created by Guido van Rossum during 1985-
1990. Like Perl, Python source code is also available under the GNU General Public
License (GPL). This tutorial gives enough understanding on Python programming
language.
Python is a high-level, interpreted, interactive and object-oriented scripting
language. Python is designed to be highly readable. It uses English keywords
frequently where as other languages use punctuation, and it has fewer syntactical
constructions than other languages.
• Python is Interpreted − Python is processed at runtime by the interpreter. You do
not need to compile your program before executing it. This is similar to PERL and
PHP.
• Python is Interactive − can actually sit at a Python prompt and interact with the
interpreter directly to write your programs.
• Python is Object-Oriented − Python supports Object-Oriented style or technique
of programming that encapsulates code within objects.
• Python is a Beginner's Language − Python is a great language for the beginner-
level programmers and supports the development of a wide range of applications
from simple text processing to WWW browsers to games.
History of Python:
Python was developed by Guido van Rossum in the late eighties and early nineties at
the National Research Institute for Mathematics and Computer Science in the
Netherlands.
Python is derived from many other languages, including ABC, Modula-3, C, C++,
Algol-68, SmallTalk, and Unix shell and other scripting languages.

Python Programming Lab JNTUA College of Engineering, Pulivendula.


DATE: EXP NO: Page No:

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.

Python Programming Lab JNTUA College of Engineering, Pulivendula.


DATE: EXP NO: Page No:

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 Programming Lab JNTUA College of Engineering, Pulivendula.


DATE: EXP NO: Page No:

AIM: Python Program for find maximum of three numbers.

Python code:
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)

Output:
Enter first number: 56
Enter Second number: 90
Enter Third number: 67
The largest number is: 90

Result: Python Program for find maximum of three numbers successfully


executed.

Python Programming Lab JNTUA College of Engineering, Pulivendula.


DATE: EXP NO: Page No:

Aim: Python program for Simple Interest.

P = float(input("Enter the principal amount : "))


N = float(input("Enter the number of years : "))
R = float(input("Enter the rate of interest : "))
SI = (P * N * R)/100
print("Simple interest : {}".format(SI))

Output:
Enter the principal amount : 100
Enter the number of years : 20.5
Enter the rate of interest : 33
Simple interest : 676.5

Aim: Python program for Compound Interest.

p = float(input("Enter the principle amount : "))


r = float(input("Enter the rate of interest : "))
t = float(input("Enter the time in the years: "))
ci = p * (pow((1 + r / 100), t))
print("compound Interest : ", ci)

Output:
Enter the principle amount: 100

Result: Python Program for simple & Compound Interest successfully executed.

Python Programming Lab JNTUA College of Engineering, Pulivendula.


DATE: EXP NO: Page No:

Aim: Python program to convert Celsius to Fahrenheit


Python code:
celsius = float(input('Enter temperature in Celsius: '))
fahrenheit = (celsius * 1.8) + 32
print(“%0.1f Celsius is equal to %0.1f degree Fahrenheit “ %(celsius,fahrenheit))

Output:
Enter temperature in Celsius: 37.0
37.0 Celsius is equal to 98.6 degree Fahrenheit

Aim: Python program to convert Fahrenheit to Celsius.


Python code:
fahrenheit = float(input('Enter temperature in fahrenheit: '))
celsius = ((fahrenheit-32)*5)/9
print(“%0.1f Celsius is equal to %0.1f degree Fahrenheit “ %(fahrenheit,celsius))
Output:
Enter temperature in fahrenheit: 98.6
98.6 Celsius is equal to 37.0 degree Fahrenheit

Result: Python Program to convert Celsius to Fahrenheit and Fahrenheit to


Celsius successfully executed.

Python Programming Lab JNTUA College of Engineering, Pulivendula.


DATE: EXP NO: Page No:

Aim: Python program to find Factorial of a given number.


Python code:

num = int(input("Enter any number : "))


temp=num
factorial= 1
if(num<0):
print("factorial does not defined for negative numbers")
elif (num==0):
print("The factorial of 0 is 1")
else:
while(num>0):
factorial=factorial*num
num=num-1
print("The factorial of ",temp," is:", factorial)
Output:

Enter any number: 4


The factorial of 4 is: 24

Enter any number: 1


The factorial of 1 is: 1

Result: Python Program to find Factorial of a given number successfully


executed.

Python Programming Lab JNTUA College of Engineering, Pulivendula.


DATE: EXP NO: Page No:

Aim: Python Program to Print the Fibonacci sequence.


Python code:
n = int(input("How many terms you want? :"))
n1 = 0
n2 = 1
i=2
if( n<=0):
print("please enter positive number")
elif(n ==0):
print("fibonacci series")
print (n1)
else:
print("fibonacci series")
print(n1,",",n2,end=",")
while i<n:
n3=n1+n2
print( n3, end= "," )
n1=n2
n2=n3
i=i+1
Output:

How many terms you want? :6


fibonacci series
0 , 1,1,2,3,5,
Result: Python Program to Print the Fibonacci sequence successfully executed.

Python Programming Lab JNTUA College of Engineering, Pulivendula.


DATE: EXP NO: Page No:

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.

Python Programming Lab JNTUA College of Engineering, Pulivendula.


DATE: EXP NO: Page No:

Aim: Python Program to find GCD of two numbers.


Python code:
def gcd(x, y):
if x > y:
smaller = y
else:
smaller = x
for i in range(1,smaller + 1):
if((x % i == 0) and (y % i == 0)):
gcd = i
return gcd

num1 = int(input("Enter first number: "))


num2 = int(input("Enter second number: "))
print("The H.C.F. of", num1,"and", num2,"is", gcd(num1, num2))

Output:

Enter first number: 12


Enter second number: 24
The H.C.F. of 12 and 24 is 12

Result: Python Program to find GCD of two numbers successfully executed.

Python Programming Lab JNTUA College of Engineering, Pulivendula.


DATE: EXP NO: Page No:

Aim: Python Program to find LCM of two numbers.


Python code:

def lcm(x, y):


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 = int(input("Enter first number: "))


num2 = int(input("Enter second number: "))
print("The L.C.M. of", num1,"and", num2,"is", lcm(num1, num2))

Output:

Enter first number: 12


Enter second number: 24
The L.C.M. of 12 and 24 is 24

Result: Python Program to find LCM of two numbers successfully executed.

Python Programming Lab JNTUA College of Engineering, Pulivendula.


DATE: EXP NO: Page No:

Aim: Python Program to find the given number is Prime or not.


Python code:
num = int(input("Enter a number: "))
if num > 1:
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")

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.

Python Programming Lab JNTUA College of Engineering, Pulivendula.


DATE: EXP NO: Page No:

Aim: Python Program to Display Prime numbers in given range.


Python code:
lower = int(input("Enter the Lower Number : "))
upper = int(input("Enter the Upper Number : "))

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)
Output:
Enter the Lower Number : 1
Enter the Upper Number : 5
Prime numbers between 1 and 5 are:
2
3
5

Result: Python Program to find to Display Prime numbers in given range


successfully executed.

Python Programming Lab JNTUA College of Engineering, Pulivendula.


DATE: EXP NO: Page No:

Aim: Python Program to display first N Prime Numbers.


Python code:
i=1
x = int(input("Enter the number:"))
counter = 0
while True:
factor=0;
for j in range (1, (i+1), 1):
a = i%j
if (a==0):
factor =factor +1
if (factor==2):
print (i)
counter = counter + 1
if counter >= x:
break
i=i+1
Output:

Enter the number:5


2
3
5
7
11
Result: Python Program to display first N Prime Numbers successfully executed

Python Programming Lab JNTUA College of Engineering, Pulivendula.


DATE: EXP NO: Page No:

Aim: Python Program to find given number is palindrome or not.


Python code:
number = int(input("Please Enter any Number: "))
reverse = 0
temp = number
while(temp > 0):
Reminder = temp % 10
reverse = (reverse * 10) + Reminder
temp = temp //10
print("Reverse of a Given number is = " ,reverse)
if(number == reverse):
print(number, "is a Palindrome Number" )
else:
print(number," is not a Palindrome Number" )

Output:
Please Enter any Number: 12345
Reverse of a Given number is = 54321
12345 is not a Palindrome Number

Please Enter any Number: 12321


Reverse of a Given number is = 12321
12321 is a Palindrome Number

Result: Python Program to find given number is palindrome or not successfully


executed.

Python Programming Lab JNTUA College of Engineering, Pulivendula.


DATE: EXP NO: Page No:

Aim: Python Program to find sum of N natural numbers.


Python code:
num = int(input("Enter a number: "))
if num < 0:
print("Enter a positive number")
else:
sum = 0
# use while loop to iterate un till zero
while(num > 0):
sum += num
num -= 1
print("The sum is”, sum)

Output:
Enter a number: 10
The sum is 55

Result: Python Program to find sum of N natural numbers successfully executed

Python Programming Lab JNTUA College of Engineering, Pulivendula.


DATE: EXP NO: Page No:

Aim: Python Program to check if a number is a strong number or not.


Python code:
sum1=0
num=int(input("Enter a number:"))
temp=num
while(num):
i=1
f=1
r=num%10
while(i<=r):
f=f*i
i=i+1
sum1=sum1+f
num=num//10
if(sum1==temp):
print("The number is a strong number")
else:
print("The number is not a strong number")
Output:
Enter a number:145
The number is a strong number.
Output 2:-
Enter a number:234
The number is not a strong number.
Result: Python to check if a number is a strong number or not successfully
executed.

Python Programming Lab JNTUA College of Engineering, Pulivendula.


DATE: EXP NO: Page No:

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)

key = int(input("Enter Search Element: "))

n = len(list1)
res = linear_Search(list1, n, key)
if(res == -1):
print("Element not found")
else:
print("Element found at index: ", res)
.

Python Programming Lab JNTUA College of Engineering, Pulivendula.


DATE: EXP NO: Page No:

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

how many Elements : 4


Enter any element 0 : 12
Enter any element 1 : 32
Enter any element 2 : 65
Enter any element 3 : 98
Enter Search Element: 85
Element not found

Result: Python Program to find search element is found or not using Linear
Search successfully executed

Python Programming Lab JNTUA College of Engineering, Pulivendula.


DATE: EXP NO: Page No:

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

elif list1[mid] > n:


high = mid - 1
else:
return mid

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)

n = int(input("Enter Search Element: "))

result = binary_search(list1, n)

if result != -1:
print("Element is present at index :", result)
else:
print("Element is not present in list1")

Python Programming Lab JNTUA College of Engineering, Pulivendula.


DATE: EXP NO: Page No:

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

how many elements : 4


Enter any sorted element 0 : 58
Enter any sorted element 1 : 65
Enter any sorted element 2 : 78
Enter any sorted element 3 : 89
Enter Search Element: 99
Element is not present in list1

Result: Python Program to find search element is found or not using Binary
Search successfully executed

Python Programming Lab JNTUA College of Engineering, Pulivendula.


DATE: EXP NO: Page No:

Aim: Python Program to find minimum, maximum and average of N numbers.


Python code:
list=[ ]
num=int(input("how many numbers : "))
for i in range(num):
numbers=int(input("Enter any number : "))
list.append(numbers)
print("sum= ", sum(list))
print("Average =", sum(list)//len(list))
print(" The maximum element in the list :",max(list))
print(" The minimum element in the list :",min(list))

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

Result: Python Program to find minimum, maximum and average of N numbers


successfully executed.

Python Programming Lab JNTUA College of Engineering, Pulivendula.


DATE: EXP NO: Page No:

Aim: Python Program for Decimal to Binary Equivalent of a number without


recursion.
Python code:
L=[ ]
def convert(b):
if(b==0):
return L
dig=b%2
L.append(dig)
convert(b//2)

a=int(input("Enter a Decimal number: "))


convert(a)
L.reverse()
print("Binary equivalent:")
for i in L:
print(i, end =" ")

Output:
Enter a Decimal number: 12
Binary equivalent:
1100

Result: Python Program for Decimal to Binary Equivalent of a number without


recursion successfully executed.

Python Programming Lab JNTUA College of Engineering, Pulivendula.


DATE: EXP NO: Page No:

Aim: Python Program to Print the Fibonacci sequence using Recursion.


Python code:
def fibonacci_series(number):
if(number==0):
return 0
elif (number==1):
return 1
else:
return (fibonacci_series(number-2)+fibonacci_series(number-1))

number=int(input("Enter the range of number : "))


for num in range(0,number):
print(fibonacci_series(num))

Output:
Enter the range of number: 5
0
1
1
2
3

Result: Python Program to Print the Fibonacci sequence using Recursion


successfully executed.

Python Programming Lab JNTUA College of Engineering, Pulivendula.


DATE: EXP NO: Page No:

Aim: Python Program for Binary to Decimal Equivalent of a number without


recursion.
Python code:
decimal_val=0
base=1
binary_val=int(input("Enter a Binary number : "))
while (binary_val > 0):
rem = binary_val % 10
decimal_val = decimal_val + rem * base
binary_val = binary_val // 10
base = base * 2
print(decimal_val)
Output:
Enter a Binary number : 1110
14

Result: Python Program for Binary to Decimal Equivalent of a number without


recursion successfully executed.

Python Programming Lab JNTUA College of Engineering, Pulivendula.


DATE: EXP NO: Page No:

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]

inputStr = input("Enter a string: ")


print("Entered string is :",inputStr)
str2 = isPalindrome(inputStr)
print("reversed string is :",str2)
if inputStr==str2 :
print(inputStr , "is a palindrome.")
else:
print(inputStr , " is n't a palindrome.")
Output:
Enter a string: madam
Entered string is : madam
reversed string is : madam
madam is a palindrome.

Enter a string: civil


Entered string is : civil
reversed string is : livic
civil is n't a palindrome.
Result: Python Program to find the given string is Palindrome or not using
recursion successfully executed.

Python Programming Lab JNTUA College of Engineering, Pulivendula.


DATE: EXP NO: Page No:

Aim: Python Program to find Factorial of a given number using recursion.


Python code:
def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)

num = int(input("Enter a number: "))


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

Output:
Enter a number: 5
The factorial of 5 is 120

Enter a number: -5
Sorry, factorial does not exist for negative numbers

Result: Python Program to find Factorial of a given number using recursion


successfully executed.

Python Programming Lab JNTUA College of Engineering, Pulivendula.


DATE: EXP NO: Page No:

Aim: Python Program to find sum of elements of a list using recursion.


Python code:
def sum_arr(arr,size):
if (size == 0):
return 0
else:
return arr[size-1] + sum_arr(arr,size-1)

n=int(input("Enter the number of elements for list:"))


a=[]
for i in range(0,n):
element=int(input("Enter element " +str(i+1)+ " : "))
a.append(element)
print("The list is:")
print(a)
print("Sum of items in list:")
b=sum_arr(a,n)
print(b)
Output:
Enter the number of elements for list:3
Enter element 1 : 12
Enter element 2 : 32
Enter element 3 : 65
The list is: [12, 32, 65]
Sum of items in list: 109
Result: Python Program to find sum of elements successfully executed.

Python Programming Lab JNTUA College of Engineering, Pulivendula.


DATE: EXP NO: Page No:

Aim: Python Program to convert a number to Roman Number.


Python code:
def int_to_Roman(num):
val = [1000, 900, 500, 400, 100, 90, 50, 40,10, 9, 5, 4,1]
syb = ["M", "CM", "D", "CD","C", "XC", "L", "XL",
"X", "IX", "V", "IV","I"]
roman_num = ''
i=0
while num > 0:
for j in range(num // val[i]):
roman_num += syb[i]
num = num-val[i]
i += 1
return roman_num

number=int(input("Enter Any Number: "))


print(number , "is :", int_to_Roman(number))

Output:
Enter Any Number: 50
50 is : L

Enter Any Number: 97


97 is : XCVII
Result: Python Program to convert a number to Roman Number successfully
executed.

Python Programming Lab JNTUA College of Engineering, Pulivendula.


DATE: EXP NO: Page No:

Aim: Python Program to Make a Simple Calculator


Python Code:
def add(P, Q):
return P + Q
def subtract(P, Q):
return P - Q
def multiply(P, Q):
return P * Q
def divide(P, Q):
return P / Q

print ("Please select the operation.")


print ("a. Add")
print ("b. Subtract")
print ("c. Multiply")
print ("d. Divide")
choice = input("Please enter choice (a/ b/ c/ d): ")
num_1 = int (input ("Please enter the first number: "))
num_2 = int (input ("Please enter the second number: "))

if choice == 'a':
print (num_1, " + ", num_2, " = ", add(num_1, num_2))

elif choice == 'b':


print (num_1, " - ", num_2, " = ", subtract(num_1, num_2))

Python Programming Lab JNTUA College of Engineering, Pulivendula.


DATE: EXP NO: Page No:

elif choice == 'c':


print (num1, " * ", num2, " = ", multiply(num1, num2))
elif choice == 'd':
print (num_1, " / ", num_2, " = ", divide(num_1, num_2))
else:
print ("This is an invalid input")
Output:
Please select the operation.
a. Add
b. Subtract
c. Multiply
d. Divide
Please enter choice (a/ b/ c/ d): a
Please enter the first number: 12
Please enter the second number: 34
12 + 34 = 46

Please select the operation.


a. Add
b. Subtract
c. Multiply
d. Divide
Please enter choice (a/ b/ c/ d): b
Please enter the first number: 45
Please enter the second number: 67
45 - 67 = -22

Python Programming Lab JNTUA College of Engineering, Pulivendula.


DATE: EXP NO: Page No:

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

Please select the operation.


a. Add
b. Subtract
c. Multiply
d. Divide
Please enter choice (a/ b/ c/ d): d
Please enter the first number: 12
Please enter the second number: 1
12 / 1 = 12.0

Result: Python Program to Make a Simple Calculator executed successfully.

Python Programming Lab JNTUA College of Engineering, Pulivendula.


DATE: EXP NO: Page No:

Aim: Python Program to perform matrix multiplication.


Python code:
r1=int(input("Enter number of Rows of Matrix A: "))
c1=int(input("Enter number of Columns of Matrix A: "))
r2=int(input("Enter number of Rows of Matrix B: "))
c2=int(input("Enter number of Columns of Matrix B: "))
if(c1==r2):
A=[]
print("Enter the element ::>")
for i in range(r1):
row=[]
for j in range(c2):
row.append(int(input()))
A.append(row)
print(A)
print("Display Array In Matrix Form")
for i in range(r1):
for j in range(c1):
print(A[i][j], end=" ")
print()
B=[]
print("Enter the element ::>")
for i in range (r2):
row=[]
for j in range(c2):
row.append(int(input()))

Python Programming Lab JNTUA College of Engineering, Pulivendula.


DATE: EXP NO: Page No:

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

Python Programming Lab JNTUA College of Engineering, Pulivendula.


DATE: EXP NO: Page No:

Enter the element ::>


2
3
5
6
[[2, 3], [5, 6]]
Display Array In Matrix Form
23
56
Enter the element ::>
6
7
8
9
[[6, 7], [8, 9]]
Display Array In Matrix Form
67
89
Product of Matrices A and B:
36 41
78 89

Result: Python Program to perform matrix multiplication executed successfully.

Python Programming Lab JNTUA College of Engineering, Pulivendula.


DATE: EXP NO: Page No:

Aim: Python Program to perform matrix Addition.


Python code:
r1=int(input("Enter number of Rows of Matrix A: "))
c1=int(input("Enter number of Columns of Matrix A: "))
r2=int(input("Enter number of Rows of Matrix B: "))
c2=int(input("Enter number of Columns of Matrix B: "))
if(r1==r2 and c1==c2):
A=[]
print("Enter the element ::>")
for i in range(r1):
row=[]
for j in range(c1):
row.append(int(input()))
A.append(row)
print(A)
print("Display Array In Matrix Form")
for i in range(r1):
for j in range(c1):
print(A[i][j], end=" ")
print()
B=[]
print("Enter the element ::>")
for i in range (r2):
row=[]
for j in range(c2):
row.append(int(input()))

Python Programming Lab JNTUA College of Engineering, Pulivendula.


DATE: EXP NO: Page No:

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

Python Programming Lab JNTUA College of Engineering, Pulivendula.


DATE: EXP NO: Page No:

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

Result: Python Program to perform matrix Addition executed successfully.

Python Programming Lab JNTUA College of Engineering, Pulivendula.


DATE: EXP NO: Page No:

Aim: Python Program to perform Transpose of Matrix.


Python code:
r1=int(input("Enter number of Rows of Matrix A: "))
c1=int(input("Enter number of Columns of Matrix A: "))
A=[]
print("Enter the element ::>")
for i in range(r1):
row=[]
for j in range(c1):
row.append(int(input()))
A.append(row)
print(A)
print("Display Array In Matrix Form")
for i in range(r1):
for j in range(c1):
print(A[i][j], end=" ")
print()
transResult= [[A[j][i] for j in range(len(A))] for i in range(len(A[0]))]
# Printing result in the output
print("The transpose of matrix A is: ")
for res in transResult:
print(res)

Output:
Enter number of Rows of Matrix A: 3
Enter number of Columns of Matrix A: 2

Python Programming Lab JNTUA College of Engineering, Pulivendula.


DATE: EXP NO: Page No:

Enter the element ::>


1
2
3
4
5
6
[[1, 2], [3, 4], [5, 6]]
Display Array In Matrix Form
12
34
56
The transpose of matrix A is:
[1, 3, 5]
[2, 4, 6]

Result: Python Program to perform Transpose of matrix executed successfully

Python Programming Lab JNTUA College of Engineering, Pulivendula.


DATE: EXP NO: Page No:

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.

Python Programming Lab JNTUA College of Engineering, Pulivendula.


DATE: EXP NO: Page No:

Aim: Python Program to merge two lists and sort it.


Python code:
a=[ ]
c=[ ]
n1=int(input("Enter number of elements:"))
for i in range(1,n1+1):
b=int(input("Enter element " +str(i)+ ": "))
a.append(b)
n2=int(input("Enter number of elements:"))
for i in range(1,n2+1):
d=int(input("Enter element:"+str(i)+ ": "))
c.append(d)
new=a+c
new.sort()
print("Sorted list is:",new)
Output:
Enter number of elements:3
Enter element 1: 12
Enter element 2: 32
Enter element 3: 65
Enter number of elements:3
Enter element:1: 25
Enter element:2: 36
Enter element:3: 95
Sorted list is: [12, 25, 32, 36, 65, and 95]
Result: Python Program to merge two lists and sort it executed successfully.

Python Programming Lab JNTUA College of Engineering, Pulivendula.


DATE: EXP NO: Page No:

Aim: Python program to sort a list of tuples alphabetically.


Python code:
def SortTuple(tup):
n = len(tup)
for i in range(n):
for j in range(n-i-1):
if tup[j][0] > tup[j + 1][0]:
tup[j], tup[j + 1] = tup[j + 1], tup[j]
return tup

tup = [("Amaruta", 20), ("Jyothi", 32), ("Akshay", 25),


("Nilesh", 21), ("Charitha", 33), ("Pavan", 22)]
print(SortTuple(tup))
Output:
[('Akshay', 25), ('Amaruta', 20), ('Charitha', 33), ('Jyothi', 32), ('Nilesh', 21), ('Pavan',
22)]

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 :

Python Programming Lab JNTUA College of Engineering, Pulivendula.


DATE: EXP NO: Page No:

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

The original tuple : (10, 4, 5, 6, 8)


value to be checked:9
Does contain required value ? : False

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.

Python Programming Lab JNTUA College of Engineering, Pulivendula.


DATE: EXP NO: Page No:

Aim: Python Program to Map Two Lists into a Dictionary.


Python code:
keys=[ ]
values=[ ]
n=int(input("Enter number of elements for dictionary:"))
print("For keys:")
for x in range(0,n):
element=input("Enter element" + str(x+1) + ":")
keys.append(element)
print("For values:")
for x in range(0,n):
element=input("Enter element" + str(x+1) + ":")
values.append(element)
d=dict(zip(keys,values))
print("The dictionary is:")
print(d)
Output:
Enter number of elements for dictionary:2
For keys:
Enter element1:S.No
Enter element2:Sname
For values:
Enter element1:1
Enter element2:Civil
The dictionary is:
{'S.No': '1', 'Sname': 'Civil'}
Result: Python Program to Map Two Lists into a Dictionary executed
successfully.

Python Programming Lab JNTUA College of Engineering, Pulivendula.


DATE: EXP NO: Page No:

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.

Python Programming Lab JNTUA College of Engineering, Pulivendula.


DATE: EXP NO: Page No:

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:

Enter file name: civil.txt


Enter string to append:
Hai Civil
Contents of appended file:
cse
Hai Civil Engineering. Hai Civil
Result: Python Program String from the User and Append it executed successfully.

Python Programming Lab JNTUA College of Engineering, Pulivendula.


DATE: EXP NO: Page No:

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

if string1 < string2:


print(string1 + " comes before " + string2 + " in the dictionary.")
elif string1> string2:
print(string1 + " comes after " + string2 + " in the dictionary.")
else:
print(string1 + " and " + string2 + " are same.")
Output:
Please enter the name of first string:
pulivendula
Please enter the name of second string:
hyderabad
pulivendula comes after hyderabad in the dictionary.

Please enter the name of first string:


madam
Please enter the name of second string:
madam
madam and madam are same.
Result: Python Program to Take in Two Strings and Display the Larger String
Without Using Built-in Functions executed successfully.

Python Programming Lab JNTUA College of Engineering, Pulivendula.


DATE: EXP NO: Page No:

Aim: Python Program to Create a Dictionary with Key as First Character


And Value as Words Starting with that Character.
Python Code:
test_string=input("Enter string:")
l=test_string.split()
d={}
for word in l:
if(word[0] not in d.keys()):
d[word[0]]=[]
d[word[0]].append(word)
else:
if(word not in d[word[0]]):
d[word[0]].append(word)
for k,v in d.items():
print(k,":",v)

Output:
Enter string: Hai Civil Engineering Students.
H : ['Hai']
C : ['Civil']
E : ['Engineering']
S : ['Students.']

Result: Python Program to Create a Dictionary with Key as First Character


And Value as Words starting with that Character executed successfully.

Python Programming Lab JNTUA College of Engineering, Pulivendula.


DATE: EXP NO: Page No:

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.

Python Programming Lab JNTUA College of Engineering, Pulivendula.


DATE: EXP NO: Page No:

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:

Enter file name: civil3.txt


4
7
9

Result: Python Program to print all the numbers present in a text file executed
successfully.

Python Programming Lab JNTUA College of Engineering, Pulivendula.


DATE: EXP NO: Page No:

Python Turtle Programming


Turtle is a Python library which used to create graphics, pictures, and games. It
was developed by Wally Feurzeig, Seymour Parpet and Cynthina Slolomon in
1967. It was a part of the original Logo programming language.

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.

The turtle Library is primarily designed to introduce children to the world of


programming. With the help of Turtle's library, new programmers can get an idea of
how we can do programming with Python in a fun and interactive way.

It is beneficial to the children and for the experienced programmer because it


allows designing unique shapes, attractive pictures, and various games. We can also
design the mini games and animation. In the upcoming section, we will learn to
various functionality of turtle library.

Python Programming Lab JNTUA College of Engineering, Pulivendula.


DATE: EXP NO: Page No:

AIM: write various types of turtle programs using python

Program(i):drawing a star

# import turtle library


import turtle
my_pen = turtle.Turtle()
fori in range(50):
my_pen.forward(50)
my_pen.right(144)
turtle.done()

output:

Program(ii): Drawing a rainbow hexagon


#import turtle library
import turtle
colors=['red','purple','blue','green','orange','yellow']
my_pen=turtle.Pen()
turtle.bgcolor("black")
for x in range(360):
my_pen.pencolor(colors[x%6])
my_pen.width(x/100+1)
my_pen.forward(x)
my_pen.left(59)

Python Programming Lab JNTUA College of Engineering, Pulivendula.


DATE: EXP NO: Page No:

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

Python Programming Lab JNTUA College of Engineering, Pulivendula.


DATE: EXP NO: Page No:

output:

Program(iv):Drawing a square inside square


# import turtle library
import turtle
my_wn = turtle.Screen()
my_wn.bgcolor("light blue")
my_wn.title("Turtle")
my_pen = turtle.Turtle()
my_pen.color("black")
defmy_sqrfunc(size):
fori in range(4):
my_pen.fd(size)
my_pen.left(90)
size = size - 5
my_sqrfunc(146)
my_sqrfunc(126)
my_sqrfunc(106)
my_sqrfunc(86)
my_sqrfunc(66)
my_sqrfunc(46)
my_sqrfunc(26)

Python Programming Lab JNTUA College of Engineering, Pulivendula.


DATE: EXP NO: Page No:

output:

Program(v): Drawing a spiral helix pattern


# import turtle library
import turtle
my_wn = turtle.Screen()
turtle.speed(2)
fori in range(30):
turtle.circle(5*i)
turtle.circle(-5*i)
turtle.left(i)
turtle.exitonclick( )

Output:

Python Programming Lab JNTUA College of Engineering, Pulivendula.


DATE: EXP NO: Page No:

Program(vi):Drawing a spiraling star


import turtle
spiral=turtle.Turtle()
fori in range(20):
spiral.forward(i*10)
spiral.right(144)
turtle.done()
output:

Program(vii):Drawing Circle Spiro graph.


import turtle
# Creating turtle
t = turtle.Turtle()
turtle.bgcolor("black")
turtle.pensize(2)
turtle.speed(0)
while (True):
for i in range(6):
for colors in ["red", "blue", "magenta", "green", "yellow", "white"]:
turtle.color(colors)
turtle.circle(100)
turtle.left(10)
turtle.hideturtle()
turtle.mainloop()

Python Programming Lab JNTUA College of Engineering, Pulivendula.


DATE: EXP NO: Page No:

Python Programming Lab JNTUA College of Engineering, Pulivendula.

You might also like