Problem Solving and Python Programming: Laboratory Programs

Laboratory Python Programs Set 4

Problem Solving and Python Programming

Engineering Chemistry : UNIT V : Energy Sources and storage devices : Program for practice

Experiment 1: Write a Python Program to display current date and Time

import datetime

now = datetime.datetime.now()

print ("Current date and time :")

print (now.strftime("%Y-%m-%d %H:%M:%S"))

Output

Current date and time :

2018-04-10 10:58:53

 

Experiment 2: Write a Python Program to display Calendar

import calendar

print("Enter Year: ");

yy = int(input())

print("Enter month: ");

mm = int(input());

print("\n", calendar.month(yy,mm));

Output

Enter Year:

2018

Enter month:

4


 

Experiment 3: Write a Python Program to check whether the input year is leap year or not

print("Enter a year: ")

year = int(input())

if (year % 4) = = 0:

if (year % 100) = = 0:

if (year % 400) = = 0:

print("{0} is a leap year".format(year))

else:

print("{0} is not a leap year".format(year))

else:

print("{0} is a leap year".format(year))

else:

print("{0} is not a leap year".format(year))

Output

Enter a year:

2016

2016 is a leap year

 

Experiment 4: Write a Python program to accept two numbers, multiply them and print the result      Jan 18

print("Enter first number: ").

a = int(input())

print("Enter second number: ")

b = int(input())

c = a*b

print("The multiplication is:",c)

Output

Enter first number:

10

Enter second number:

20 The multiplication is: 200

 

Experiment 5: Write a Python Program to accept two numbers, find the greatest and print the result     Jan 18

print("Enter first number: ")

a = int(input())

print("Enter second number: ")

b = int(input()) if a > b:

print("First number is greater")

else:

print("Second number is greater")

Output

Enter first number:

10

Enter second number:

20

Second number is greater

 

Experiment 6: Write a Python program to implement simple calculator

def add(x, y):

return x + y

 

def sub(x, y):

return x - y

 

def mult(x, y):

return x * y

 

def div(x, y):

return x/y

print("Main Menu")

print("1.Add")

print("2.Subtract")

print("3. Multiply")

print("4.Divide")

 

print("Enter your choice")

choice = int(input())

print("Enter first number")

num1 = int(input())

print("Enter second number: ")

num2 = int(input())

 

if choice = = 1:

print(num1,"+",num2,"=", add(num1,num2))

elif choice = = 2:

print(num1,"-",num2,"=", sub(num1, num2))

elif choice = = 3:

print(num 1, "*", num2,"=", mult(num1, num2))

elif choice == 4:

print(num1,"7",num2,"=", div(num1,num2))

else:

print("Invalid input")

Output

Main Menu

1.Add

2. Subtract

3.Multiply

4.Divide Enter your choice

1

Enter first number

10

Enter second number:

20

10 + 20 = 30

 

Experiment 7 : Write a Python Program to check whether the number is positive, negative or zero

print("Enter some number")

num = int(input())

if num > 0:

print("Positive number")

elif num = = 0:

print("Zero")

else:

print("Negative number")

Output(Run 1)

Enter some number

4

Positive number

Output(Run 2)

Enter some number

-4

Negative number

Output(Run 3)

Enter some number

0

Zero

 

Experiment 8 : Write a Python program to find area of triangle(using Base and height)

print("Enter base: ")

b = float(input())

print("Enter height: ")

h = float(input())

area = 0.5*b*h

print("The area of triangle is: ", area)

Output

Enter base:

10

Enter height:

20

The area of triangle is: 100.0

 

Experiment 9 : Write a Python program to find area of triangle(using three sides)

import math

print("Enter first side: ")

a = float(input())

print("Enter second side: ")

b = float(input())

print("Enter third side: ")

c = float(input())

s = (a+b+c)/2

area = math.sqrt((s*(s-a)*(s-b)*(s-c)))

print("The area of triangle is: "area)

Output

Enter first side:

3

Enter second side:

4

Enter third side:

5

The area of triangle is: 6.0

 

Experiment 10 : Write a Python Program to convert Celsius to Fahrenheit temperature

print("Enter the celsius value: ")

celsius = float(input())

fahrenheit = (celsius * 1.8) + 32

print("Fahrenheit value =",fahrenheit)

Output

Enter the celsius value:

40.5

Fahrenheit value = 104.9

 

Experiment 11 : Write a Python Program to convert Fahrenheit to Celsius temperature

print("Enter the Fahrenheit value: ")

fahrenheit = float(input())

celsius = (fahrenheit - 32)/1.8

print("Celsius value =",celsius)

Output

Enter the Fahrenheit value:

104.9

Celsius value = 40.5

 

Experiment 12: Write a Python Program to convert Kilometers to Miles

print("Enter value in kilometers: ")

kilometers = float(input()).

factor = 0.621371

miles = kilometers * factor

print("miles= ",miles)

Output

Enter value in kilometers:

100

miles= 62.137100000000004

 

Experiment 13: Write a Python Program for finding L.C.M. of two numbers

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

b = int(input("Enter second number: "))

if a > b:

m = a

else:

m = b

while(True):

if((m %a = = 0) and (m % b = = 0)):

lcm = m

break

m + = 1

print("The L.C.M. of", a, "and", b, "is",1cm)

Output

Enter first number: 4

Enter second number: 6

The L.C.M. of 4 and 6 is 12

 

Experiment 14 : Write a Python Program to display GCD of two numbers

print("Enter first number: ")

a = int(input())

print("Enter second number: ");

b = int(input())

rem = a%b

while rem!=0 :

a = b

b = rem

rem = a%b

print ("gcd of given numbers is: ",b)

Output

Enter first number:

15

Enter second number:

5

god of given numbers is: 5

 

Experiment 15: Write a Python program to display all the prime numbers within the given interval

print("Enter the range (a,b)")

a = int(input())

b= print(input())

print("Prime numbers between", a,"and", b,"are...")

 

for num in range(a, b + 1):

# 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 range [a, b]

1

10

Prime numbers between 1 and 10 are...

2

3

5

7

 

Experiment 16 : Write a Python Program to print the factors of a given number

print("Enter number: ")

num = int(input())

print("The factors of", num,"are...")

for i in range(1, num + 1):

if num %i = = 0:

print(i)

Output

Enter number:

12

The factors of 12 are...

1

2

3

4

6

12

 

Experiment 17 : Write a Python Program to convert decimal number to binary using recursion

def DecToBin(n):

if n > 1:

DecToBin(n//2)

print(n % 2, end = ")

 

print("Enter decimal number: ")

d = int(input())

DecToBin(d)

Output

Enter decimal number:

10

1010

 

Experiment 18 : Write a Python Program to perform addition of two matrices

A = [[1,2,3],

[4,5,6],

[7,8,9]]

B = [[11,12,13),

[14,15,16),

[17,18,19]]

C = [[0,0,0],

[0,0,0],

[0,0,0]]

for i in range(len(A)):

# iterate through columns

for j in range(len(A[0])):

C[i][j] = A[i][j] + B[i][j]

 

print("Matrix A..")

for i in A:

print(i)

www

print("Matrix B..")

for j in B:

print()

print("The addition of two matrices is..")

for k in C:

print(k)

Output

Matrix A..

[1, 2, 3]

[4, 5, 6]

[7, 8, 9]

Matrix B..

[11, 12, 13]

[14, 15, 16]

[17, 18, 19]

The addition of two matrices is..

[12, 14, 16]

[18, 20, 22]

[24, 26, 28]

 

Experiment 19: Write a Python Program to perform multiplication of two matrices

A = [[1,2,3],

[4,5,6), 17,8,9]]

B = [[11,12,13),

[14,15,16],

[17,18,19]]

C = [[0,0,0],

[0,0,0],

[0,0,0]]

for i in range(len(A)):

#iterate through columns

for j in range(len(A[0])):

for k in range(len(B)):

C[i][j]+= A[i][k] * B[k][j]

 

print("Matrix A..")

for i in A:

print(i)

 

print("Matrix B..")

for j in B:

print(j)

 

print("The multiplication of two matrices is..")

for k in C:

print(k)

Output

Matrix A..

[1, 2, 3]

[4, 5, 6]

[7, 8, 9]

Matrix B..

[11, 12, 13]

[14, 15, 16]

[17, 18, 19]

The multiplication of two matrices is..

[90, 96, 102]

[216, 231, 246]

[342, 366, 390]

 

Experiment 20 : Write a Python Program to find the transpose of matrix

A = [[1,2],

[3, 4],

[5, 6]]

B = [[0, 0, 0],

[0, 0, 0]]

for i in range(len(A)):

for j in range(len(A[0])):

B[j][i] = A[i][j]

print("Original Matrix is...")

for k in A:

print(k)

print("Transposed Matrix is...")

for k in B:

print(k)

Output

Original Matrix is...

[1, 2]

[3, 4]

[5, 6]

Transposed Matrix is...

[1, 3, 5]

[2, 4, 6]

 

Experiment 21 : Write a Python Program to find x' using recursion

def power(x,y):

if(y = = 1);

return(x)

if(y!= 1):

retum(x * power(x,y-1)

x = int(input "Enter base: "))

y = int input("Enter exponential value: "))

print("Result:", power(x,y))

Output

Enter base: 2

Enter exponential value: 3

Result: 8

 

Experiment 22 : Write a Python program to check if the number is Armstrong number

print("Enter some number to check if it is Armstrong number: ")

num = int(input())

total = 0;

temp = num;

while temp > 0:

digit = temp% 10;

total + = digit ** 3;

temp // = 10;

if num == total:

print(num,"is an Armstrong Number.");

else:

print(num,"is not an Armstrong Number.");

Output(Run 1)

Enter some number to check if it is Armstrong number:

153

153 is an Armstrong Number.

Output(Run 2)

Enter some number to check if it is Armstrong number:

101

101 is not an Armstrong Number.

 

Experiment 23 : Write a Python Program to find ASCII value of a character

ch = input("Enter a character: ")

print("The ASCII value of " + ch + "is",ord(ch))

Output

Enter a character: A

The ASCII value of 'A' is 65

 

Experiment 24 : Write a Python Program to display the ASCII values

print("The ASCII values are...")

for i in range(1, 255):

ch = chr(i);

print(i,"=", ch);

 

Experiment 25 : Write a Python Program to find palindrome of a given string

str = 'madam'

# reverse the string

rev_str = reversed(str)

 

if list(str) = = list(rev_str):

print("It is palindrome")

else:

print("It is not palindrome")

Output

It is palindrome

 

Experiment 26 : Write a python Program to separate out and display the letters, digits and special characters from the given string.

string = input("Enter string:")

vowels = 0

consonants = 0

for i in string:

if(i= ='a' or i = ='e' or i = ='i' or i = ='d' or i = ='u' or i = ='A' or i = ='E' or i = =I' or i = ='0' or i = ='U');

vowels=vowels + 1

else:

consonants = consonants +1

print("Number of vowels are:")

print(vowels)

print("Number of consonants are:")

print(consonants)

Output

Enter string:hello

Number of vowels are:

2

Number of consonants are:

3

 

Experiment 27 : Write a Python Program to remove punctuation marks from the given string

punctuations = "!()-[1{};:"'\,<>./?@#$%^&*_~"

str = input("Enter a string: ")

result = "

for ch in str:

if ch not in punctuations:

result = result + ch

print("The string after removing punctuations: "result)

Output

Enter a string: hello!how are you? Bye.

The string after removing punctuations: hellohow are you Bye

 

Experiment 28 : Write a Python Program to sort the words alphabetically from given string

str = input("Enter a string: ")

words = str.split()

words.sort()

print("The sorted words are:")

for word in words:

print(word)

Output

Enter a string: Shilpa Archana Supriya

The sorted words are:

Archana

Shilpa

Supriya

 

Experiment 29 : Write a Python Program to swap to strings

str1 = input("Enter First String: ");

str2 = input("Enter Second String: ");

print("\nBefore swapping:");

print("First String =",str1);

print("Second String =",str2);

temp = str1;

str1 = str2;

str2 = temp;

print("\nAfter swapping:");

print("First String =", str1);

print("Second String =", str2);

Output

Enter First String: aaa

Enter Second String: bbb

Before swapping:

First String = aaa

Second String = bbb

After swapping:

First String = bbb

Second String = aaa

 

Experiment 30 : Write a Python Program to delete a desired word from given string

string = input("Enter any string to remove particular word: ");

word = input("Enter word to be deleted: ");

word_list = string.split();

print(''.join([i for i in word_list if i not in word]));

Output

Enter any string to remove particular word: This is big Python program

Enter word to be deleted: big

This is Python program

 

Experiment 31 : Write a Python Program to remove a space from given string

str = input("Enter some string with spaces in between: ");

new_string = str.replace(" ", "');

print("\nNew string after removing all spaces:");

print(new_string);

Output

Enter some string with spaces in between: Hello Friend

New string after removing all spaces:

HelloFriend

 

Experiment 32: Write a Python Program to display following pattern


j = 0

print("Enter number of rows: ")

rows = int(input())

for i in range(1, rows+1):

for space in range(1, (rows-i)+1):

print(end=" ")

whilej != (2*i-1):

print("* ", end='')

j = j + 1

j = 0 print()

Output

Enter number of rows:

10


 

Experiment 33 : Write a Python Program to display a Pascal's Triangle

n = int(input("Enter number of rows: "))

a = [ ]

for i in range(n):

a.append([ ])

a[i].append(1)

for j in range(1,1):

a[i].append(a[i-1][j-1]+a[i-1][j])

if(n!=0);

a[i].append(1)

for i in range(n):

print(" *(n-i),end="",sep="")

for j in range(0,i+1):

print('{0:5}'.format(a[i][j]),end="",sep="")

print()

Output

Enter number of rows: 5


 

Experiment 34 : Write a Python Program to display Pascal's Triangle using List

print("Enter number of rows: ")

row = int(input())

list = [1]

for i in range(row):

print(list)

newlist = [ ]

newlist.append(list[0])

for i in range(len(list)-1):

newlist.append(list[i]+list[i+1])

newlist.append(list[-1])

list = newlist

Output

Enter number of rows:

5

[1]

[1, 11

[1, 2, 1]

[1, 3, 3, 1]

[1, 4, 6, 4, 1]

 

Experiment 35 : Write a Python Program to find the sum of all the elements in a List

def sum_list(items):

total = 0

for x in items:

total + = x

return total

print(sum_list([10,20,30,40]))

Output

100

 

Experiment 36: Write a Python Program to find the largest element from the List

def Largest(items):

max_ele=items[0]

for x in items:

if x > max_ele:

max_ele = x

return max_ele

print(Largest([5,-1,100,2,30]))

Output

100

 

Experiment 37 : Write a Python Program to replace the last element of first list by the entire second list elements

def Replace_element(num1, num2):

num 1[-1:) = num2

print(num1)

num1 = [1, 2, 3, 4, 5]

num2 = (11, 12, 13, 14]

Replace_element(num1,num2)

Output

[1, 2, 3, 4, 11, 12, 13, 14]

 

Experiment 38 : Write a Python Program to accept a string from console and display the characters present at even indexes.

def display_even(str):

str = str[::2]

print(str)

str = input("Enter some string:")

display_even(str)

Output

Enter some string: python

pto

 

Experiment 39 : Write a Python Program to iterate a list in reverse order

def display_reverse(str):

str = str[::-1]

print(str)

str = input("Enter some string: ")

display_reverse(str)

Output

Enter some string: python

nohtyp

 

Experiment 40 : Write a Python program to count number of characters in a string. Display the character and its count. Make use of concept of dictionary.

def display_char_count(str):

d = {}

print("The occurrences of characters are as follows ...")

for s in str:

d[s]=d.get(s,0)+1

print (d.items())

str = input("Enter some string:")

display_char_count(str)

Output

Enter some string: abccaade

The occurrences of characters are as follows ...

dict_items([('a', 3), ('b', 1), ('c', 2), ('d', 1), ('e', 1)]).

 

Experiment 41 : Write a Python program to display a number from 1 to 10 along with its square.Make use of concept of dictionary.

def display_Square():

d = dict()

for i in range(1,11):

d[i] = i*i

print (d)

display_Square()

Output

{1:1, 2:4, 3:9, 4: 16, 5: 25, 6:36, 7: 49, 8: 64, 9: 81, 10: 100}

 

Experiment 42: Write a program to convert a tuple to string

def display_Str( ):

t = ('M', 'y', 'T', 'n', 'd','1', 'a')

st r=".join(t) print(str)

display_Str( )

Output

MyIndia

 

Experiment 43 : Write a Python program to create a tuple from a list of numbers from 1 to 10

def Create_tuple():

li = list()

for i in range(1,11):

li.append(i)

print(tuple(li))

Create_tuple()

 (1,2,3,4,5,6,7,8,9,10)

 

Experiment 44 : Write a Python program to create another tuple of even numbers from the tuple containing the numbers from 1 to 10

def Even_tuple():

t1 = (1,2,3,4,5,6,7,8,9,10)

li = list()

for i in t1:

if i<10: if t1[i]%2 = = 0:

li.append(t1[i])

t2 = tuple(li)

print(t2)

Output

Even_tuple()

Output

(2, 4, 6, 8, 10)

 

 

Problem Solving and Python Programming: Laboratory Programs : Tag: Engineering Python : Problem Solving and Python Programming - Laboratory Python Programs Set 4