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

python lab manual

Python
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)
13 views

python lab manual

Python
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/ 20

Sree Chaitanya College of Engineering

Department of CSE & CSD

PYTHON PROGRAMMING

LAB MANUAL

R22 LAB MANUAL

Week-1
1. i) Use a web browser to go to the Python website http://python.org. This
page contains information
about Python and links to Python-related pages, and it gives you the ability to
search the Python
documentation
In Python, webbrowser module is a convenient web browser controller. It
provides a high-level interface that allows displaying Web-based documents to
users.
webbrowser can also be used as a CLI tool. It accepts a URL as the argument
with the following optional parameters: -n opens the URL in a new browser
window, if possible, and -t opens the URL in a new browser tab.

 Python

python -m webbrowser -t "https://www.google.com"

NOTE: webbrowser is part of the python standard library. Therefore, there is no


need to install a separate package to use it.
The webbrowser module can be used to launch a browser in a platform-
independent manner as shown below:
Code #1 :
 Python3

import webbrowser

webbrowser.open('http://www.python.org')

Output :
True
This opens the requested page using the default browser. To have a bit more
control over how the page gets opened, use one of the following functions given
below in the code –
Code #2 : Open the page in a new browser window.
 Python3

webbrowser.open_new('http://www.python.org')

Output :
True
Code #3 : Open the page in a new browser tab.
 Python3

webbrowser.open_new_tab('http://www.python.org')

Output :
True
These will try to open the page in a new browser window or tab, if possible and
supported by the browser. To open a page in a specific browser, use the
webbrowser.get() function to specify a particular browser.
Code #4 :
 Python3

c = webbrowser.get('firefox')

c.open('http://www.python.org')
c.open_new_tab('http://docs.python.org')

Output :
True
True
Being able to easily launch a browser can be a useful operation in many scripts.
For example, maybe a script performs some kind of deployment to a server and
one would like to have it quickly launch a browser so one can verify that it’s
working. Or maybe a program writes data out in the form of HTML pages and
just like to fire up a browser to see the result. Either way, the webbrowser
module is a simple solution.

ii) Start the Python interpreter and type help() to start the online help utility.

Python help() Method

The Python help() function invokes the interactive built-in help system. If the
argument is a string, then the string is treated as the name of
a module, function, class, keyword, or documentation topic, and a help page is
printed on the console. If the argument is any other kind of object, a help page on
the object is displayed.

Syntax:

help(object)

Parameters:

object: (Optional) The object whose documentation needs to be printed on the


console.

Return Vype:
Returns a help page.

The following displays the help on the builtin print method on the Python
interactive shell.

Help >>> help('print')

Help on built-in function print in module builtins:

print(...)

print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

Prints the values to a stream, or to sys.stdout by default.

Optional keyword arguments:

file: a file-like object (stream); defaults to the current sys.stdout.

sep: string inserted between values, default a space.

end: string appended after the last value, default a newline.

flush: whether to forcibly flush the stream.on built-in function print in module
builtins:

>>> he'print'
streamAbove, the specified string matches with the built-in print function, so it
displays help on it.

The following displays the help page on the module.

>> help('math')
Help on built-in module math:

NAME
math

DESCRIPTION
This module is always available. It provides access to the
mathematical functions defined by the C standard.
FUNCTIONS
acos(x, /)
Return the arc cosine (measured in radians) of x.

acosh(x, /)
Return the inverse hyperbolic cosine of x.

asin(x, /)
Return the arc sine (measured in radians) of x.

asinh(x, /)
Return the inverse hyperbolic sine of x.

atan(x, /)
Return the arc tangent (measured in radians) of x.
-- More -->> help('math')
Help on built-in module math:

NAM-

Above, the specified string matches with the Math module, so it displays the
help of the Math functions. -- More -- means there is more information to display
on this by pressing the Enter or space key.
2. Start a Python interpreter and use it as a Calculator

# This function adds two numbers

def add(x, y):

return x + y

# This function subtracts two numbers

def subtract(x, y):

return x - y

# This function multiplies two numbers

def multiply(x, y):

return x * y

# This function divides two numbers

def divide(x, y):

return x / y

print("Select operation.")

print("1.Add")

print("2.Subtract")

print("3.Multiply")

print("4.Divide")

while True:

# take input from the user

choice = input("Enter choice(1/2/3/4): ")

# check if choice is one of the four options


if choice in ('1', '2', '3', '4'):

try:

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

num2 = float(input("Enter second number: "))

except ValueError:

print("Invalid input. Please enter a number.")

continue

if choice == '1':

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

elif choice == '2':

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

elif choice == '3':

print(num1, "*", num2, "=", multiply(num1, num2))

elif choice == '4':

print(num1, "/", num2, "=", divide(num1, num2))

# check if user wants another calculation

# break the while loop if answer is no

next_calculation = input("Let's do next calculation? (yes/no): ")

if next_calculation == "no":
break

else:

print("Invalid Input")

output:

Select operation.

1.Add

2.Subtract

3.Multiply

4.Divide

Enter choice(1/2/3/4): 1

Enter first number: 5

Enter second number: 6

5.0 + 6.0 = 11.0

Let's do next calculation? (yes/no):


3 .i) Write a program to calculate compound interest when principal, rate and
number of periods are given.
# Python code
# To find compound interest
# inputs
p= 1200 # principal amount
t= 2 # time
r= 5.4 # rate
# calculates the compound interest
a=p*(1+(r/100))**t # formula for calculating amount
ci=a-p # compound interest = amount - principal amount
# printing compound interest value
print(ci)

Output
133.0992000000001
ii. Given coordinates (x1, y1), (x2, y2) find the distance between two points

import math
p1 = [4, 0]
p2 = [6, 6]
distance = math.sqrt( ((p1[0]-p2[0])**2)+((p1[1]-p2[1])**2) )

print(distance)

output:

6.324555320336759
4.Read name, address, email and phone number of a person through
keyboard and print the details.

print("enter your name ",end="")

name=input()

print("enter your address",end="")

address=input()

print("enter your email ",end="")

email=input()

print("enter yoyr contactno",end="")

contactno=input()

print("name:",name)

print("address:",address)

print("email:",email)

print("contactno",contactno)

output: enter your name priyanka

enter your addressknr

enter your email [email protected]

enter yoyr contactno9502780251

name: priyanka

address: knr

email: [email protected]
contactno 9502780251

Week – 2

1. Print the below triangle using for loop.


5
44
333
2222
1 1 1 1 1.

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

n=5

for i in range(rows):

for j in range(i+1):

print(n, end="")

n=n-1

print("\n")

Output:

Enter number of rows: 5

4 4

3 3 3

2 2 2 2

1 1 1 1 1
2.Write a program to check whether the given input is digit or
lowercasecharacter or uppercase character or a special character (use 'if-else-
if' ladder

ch = input("Please Enter Your Own Character : ")

if(ch>='0' and ch<='9'):

print("the given charecter", ch,"is a digit")

elif(ch.isupper()):

print("The Given Character ", ch, "is an Uppercase Alphabet")

elif(ch.islower()):

print("The Given Character ", ch, "is a Lowercase Alphabet")

else:

print("The Given Character ", ch, "is Not a Lower or Uppercase Alphabet")

Please Enter Your Own Character : B

The Given Character B is an Uppercase Alphabet

Please Enter Your Own Character : a

The Given Character a is a Lowercase Alphabet

Please Enter Your Own Character : 2

the given charecter 2 is a digit


3.Python Program to Print the Fibonacci sequence using while loop

nterms = int(input("How many terms? "))

# first two terms

n1, n2 = 0, 1

count = 0

# check if the number of terms is valid

if nterms <= 0:

print("Please enter a positive integer")

# if there is only one term, return n1

elif nterms == 1:

print("Fibonacci sequence upto",nterms,":")

print(n1)

# generate fibonacci sequence

else:

print("Fibonacci sequence:")

while count < nterms:

print(n1)

nth = n1 + n2

# update values

n1 = n2

n2 = nth

count += 1
output:

How many terms? 8


Fibonacci sequence:
0
1
1
2
3
5
8
13
4.Python program to print all prime numbers in a given interval (use break)
lower = 900
upper = 1000

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:

Prime numbers between 900 and 1000 are:


907
911
919
929
937
941
947
953
967
971
977
983
991
997
>
Week -3

1.i) Write a program to convert a list and tuple into arrays.

import numpy as np

my_list = [1, 2, 3, 4, 5, 6, 7, 8]

print("List to array: ")

print(np.asarray(my_list))

my_tuple = ([8, 4, 6], [1, 2, 3])

print("Tuple to array: ")

print(np.asarray(my_tuple))

output:

List to array:

[1 2 3 4 5 6 7 8]

Tuple to array:

[[8 4 6]

[1 2 3]]

ii)Write a program to find common values between two arrays.

import numpy as np

ar1 = np.array([0, 1, 2, 3, 4])

ar2 = [1, 3, 4]

# Common values between two arrays

print(np.intersect1d(ar1, ar2))
output:[1 3 4]
2.Write a function called gcd that takes parameters a and b and returns their
greatest common divisor.

# importing "math" for mathematical operations

import math

# prints 12

print("The gcd of 60 and 48 is : ", end="")

print(math.gcd(60, 48))

# palindrome or not

def isPalindrome(str):

# Run loop from 0 to len/2

for i in range(0, int(len(str)/2)):

if str[i] != str[len(str)-i-1]:

return False

return True

# main function

s = "malayalam"

ans = isPalindrome(s)

if (ans):

print("Yes")

else:

print("No")

Output:
The gcd of 60 and 48 is : 12 Yes

3.Write a function called palindrome that takes a string argument and


returnsTrue if it is a palindrome and False otherwise. Remember that you can
use the built-in function len to check the length of a string.

# Recursive function to check if a


# string is palindrome
def isPalindrome(s):

# to change it the string is similar case


s = s.lower()
# length of s
l = len(s)

# if length is less than 2


if l < 2:
return True

# If s[0] and s[l-1] are equal


elif s[0] == s[l - 1]:

# Call is palindrome form substring(1,l-1)


return isPalindrome(s[1: l - 1])

else:
return False

# Driver Code
s = "MalaYaLam"
ans = isPalindrome(s)

if ans:
print("Yes")

else:
print("No")
output: Yes

You might also like