[go: up one dir, main page]

0% found this document useful (0 votes)
156 views27 pages

Python Practical File

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 27

TANVI CHOUHAN

20100BTCSFBI07423

PRACTICAL -1
AIM: - Introduction to Python Language.
➢ About python
Python is developed by Guido van Rossum. Guido van Rossum started
implementing Python in 1989. Python is a widely used general-purpose, high level
programming language. It was designed with an emphasis on code readability, and
its syntax allows programmers to express their concepts in fewer lines of code.
Python is a programming language that lets you work quickly and integrate systems
more efficiently.
There are two major Python versions: Python 2 and Python 3. Both are quite
different.
➢ Features of Python programming language
1. Readable: Python is a very readable language.

2. Easy to Learn: Learning python is easy as this is a expressive and high level
programming language, which means it is easy to understand the language and thus
easy to learn.

3. Cross platform: Python is available and can run on various operating systems
such as Mac, Windows, Linux, Unix etc. This makes it a cross platform and
portable language.

4. Open Source: Python is a open source programming language.

5. Large standard library: Python comes with a large standard library that has
some handy codes and functions which we can use while writing code in Python.

6. Free: Python is free to download and use. This means you can download it for
free and use it in your application. See: Open Source Python License. Python is an
example of a FLOSS (Free/Libre Open Source Software), which means you can
freely distribute copies of this software, read its source code and modify it.

1
TANVI CHOUHAN
20100BTCSFBI07423

7. Supports exception handling: If you are new, you may wonder what is an
exception? An exception is an event that can occur during program exception and
can disrupt the normal flow of program. Python supports exception handling which
means we can write less error prone code and can test various scenarios that can
cause an exception later on.

8. Advanced features: Supports generators and list comprehensions. We will


cover these features later.

9. Automatic memory management: Python supports automatic memory


management which means the memory is cleared and freed automatically. You do
not have to bother clearing the memory.

➢ Uses
1. Web development
2. Machine learning
3. Data Analysis
4. Scripting
5. Game development
6. You can develop Embedded applications in Python.
7. Desktop applications

2
TANVI CHOUHAN
20100BTCSFBI07423

PRACTICAL -2
AIM: - Introduction to different python supporting editor.
1. Sublime Text
Category: Code Editor

Written by a Google engineer with a dream for a better text editor, Sublime Text is
an extremely popular code editor. Supported on all platforms, Sublime Text has
built-in support for Python code editing and a rich set of extensions (called
packages) that extend the syntax and editing features.

Installing additional Python packages can be tricky: all Sublime Text packages are
written in Python itself, and installing community packages often requires you to
execute Python scripts directly in Sublime Text.

2. Atom
Category: Code Editor

Available on all platforms, Atom is billed as the “hackable text editor for the 21st
Century.” With a sleek interface, file system browser, and marketplace for
extensions, open-source Atom is built using Electron, a framework for creating
desktop applications using JavaScript, HTML, and CSS. Python language support
is provided by an extension that can be installed when Atom is running.

3. GNU Emacs
Category: Code Editor

Back before the iPhone vs Android war, before the Linux vs Windows war, even
before the PC vs Mac war, there was the Editor War, with GNU Emacs as one of
the combatants. Billed as “the extensible, customizable, self-documenting, real-
time display editor,” GNU Emacs has been around almost as long as UNIX and has
a fervent following.

Always free and available on every platform (in one form or another), GNU Emacs
uses a form of the powerful Lisp programming language for customization, and
various customization scripts exist for Python development.

3
TANVI CHOUHAN
20100BTCSFBI07423

4. Vi / Vim
Category: Code Editor

On the other side of the Text Editor War stands VI (aka VIM). Included by default
on almost every UNIX system and Mac OS X, VI has an equally fervent following.

VI and VIM are modal editors, separating the viewing of a file from the editing of
a file. VIM includes many improvements on the original VI, including an
extensibility model and in-place code building. VIMScripts are available for
various Python development tasks.

5. Visual Studio Code


Category: Code Editor

Not to be confused with full Visual Studio, Visual Studio Code (aka VS Code) is a
full-featured code editor available for Linux, Mac OS X, and Windows platforms.
Small and light-weight, but full-featured, VS Code is open-source, extensible, and
configurable for almost any task. Like Atom, VS Code is built on Electron, so it
has the same advantages and disadvantages that brings.

Installing Python support in VS Code is very accessible: the Marketplace is a quick


button click away. Search for Python, click Install, and restart if necessary. VS
Code will recognize your Python installation and libraries automatically.

6. PyCharm
Category: IDE

One of the best (and only) full-featured, dedicated IDEs for Python is PyCharm.
Available in both paid (Professional) and free open-source (Community) editions,
PyCharm installs quickly and easily on Windows, Mac OS X, and Linux platforms.

Out of the box, PyCharm supports Python development directly. You can just open
a new file and start writing code. You can run and debug Python directly inside
PyCharm, and it has support for source control and projects.

4
TANVI CHOUHAN
20100BTCSFBI07423

PRACTICAL -3
AIM: - Write a simple python program that display only print message.
Code:
print("I'm learning python.")
Output:

5
TANVI CHOUHAN
20100BTCSFBI07423

PRACTICAL -4
AIM: - Write a python program to find largest of three no. with the use
of a variable.
Code:
usr = input("Enter three values: ") # taking three inputs at a time
split_text = usr.split(' ') #This will separate list into numbers whenever you give
press spacebar while typing
x = float(split_text[0]) #variable declaration
y = float(split_text[1]) #variable declaration
z = float(split_text[2]) #variable declaration
if x>y and x>z:
print (x)
elif y>z and y>x:
print (y)
else:
print(z)
Output:

6
TANVI CHOUHAN
20100BTCSFBI07423

PRACTICAL -5
AIM: - Write a python program to convert temperature from Celsius to
Fahrenheit with the use of user input.
Code:
ctemp = float(input("Input the temperature in celsius "))
ftemp = (ctemp*1.8) + 32
print("Conversion of {0}°C to Fahrenheit is {1}°F". format(ctemp,ftemp))
Output:

7
TANVI CHOUHAN
20100BTCSFBI07423

PRACTICAL -6
AIM: - Write a program to construct the different patterns using loops
and nested loops.
PATTERN: 1
Code:
n = int(input("Enter the number of rows "))
for i in range(0, n):
for j in range(0, i + 1):
print("+ ", end="")
print()
Output:

PATTERN: 2
Code:
rows = int(input("Enter the number of rows: "))
k=0

8
TANVI CHOUHAN
20100BTCSFBI07423

# Reversed loop for downward inverted pattern


for i in range(rows, 0, -1):
# Increment in k after each iteration
k += 1
for j in range(1, i + 1):
print(k, end=' ')
print()
OUTPUT:

9
TANVI CHOUHAN
20100BTCSFBI07423

PRACTICAL -7
AIM: - Write a python program to print prime numbers less than 20 using
decision statement in python.
Code:
print("Printing prime numbers less than 20 using if-else")
for number in range(1,20+1):
if number>1:
for i in range(2,number):
if (number%i)==0:
break
else:
print(number)
Output:

10
TANVI CHOUHAN
20100BTCSFBI07423

PRACTICAL -8
AIM: - Write a program which accept the radius of a circle from user and
computes the area implement using functions & pass arguments, pass
functions also.
Code:
from math import pi
def area(r):
return pi * r * r
rad= float(input("Enter the radius of the circle: "))
area = area(rad)
print('Area= ',area)
Output:

11
TANVI CHOUHAN
20100BTCSFBI07423

PRACTICAL -9
AIM: - Write a program to design object-oriented programs to convert
an integer to roman with python classes.
Code:
import math
class MyClass:
@staticmethod
def intToRoman(num):

# Storing roman values of digits from 0-9


# when placed at different places
m = ["", "M", "MM", "MMM"]
c = ["", "C", "CC", "CCC", "CD", "D","DC", "DCC", "DCCC", "CM "]
x = ["", "X", "XX", "XXX", "XL", "L","LX", "LXX", "LXXX", "XC"]
i = ["", "I", "II", "III", "IV", "V","VI", "VII", "VIII", "IX"]
# Converting to roman
thousands = m[num // 1000]
hundreds = c[(num % 1000) // 100]
tens = x[(num % 100) // 10]
ones = i[num % 10]
ans = (thousands + hundreds + tens + ones)
return ans
# Driver code
p1=MyClass()

12
TANVI CHOUHAN
20100BTCSFBI07423

a = int(input("Enter any number "))


print(p1.intToRoman(a))
Output:

13
TANVI CHOUHAN
20100BTCSFBI07423

PRACTICAL -10
AIM: - Write a program to implement class inheritance.
Code:
class Robot:
def __init__(self, name):
self.name = name
def say_hi(self):
print("Hi, I am " + self.name)
class PhysicianRobot(Robot):
pass
x = Robot("Marvin")
y = PhysicianRobot("Ultron")
print(x, type(x))
print(y, type(y))
y.say_hi()

Output:

14
TANVI CHOUHAN
20100BTCSFBI07423

PRACTICAL -11
AIM: - Write a program to find a factorial of a number using recursion.
Code:
def factorial (n):
return 1 if(n==1 or n==0) else n * factorial(n - 1)
num = input("enter the no. ")
num=int(num)
# type conversion is must as num will be treat as string!
print("factorial of ", num, "is", factorial(num))
Output:

15
TANVI CHOUHAN
20100BTCSFBI07423

PRACTICAL -12
AIM: - Write a python program to print date & time using date & time
functions.
Code:
import datetime
now = datetime.datetime.now()
print ("Current date and time : ")
print (now.strftime("%Y-%m-%d %H:%M:%S"))

Output:

16
TANVI CHOUHAN
20100BTCSFBI07423

PRACTICAL -13
AIM: - Write a program to add some days to your present date & print
the date added.
Code:
from datetime import timedelta, date
newdate = date.today() + timedelta(days=39)

print("After adding days, new date = ", newdate)


Output:

17
TANVI CHOUHAN
20100BTCSFBI07423

PRACTICAL -14
AIM: - Write a program to demonstrate the use of list & various list
function.
Code:
list = ['A','s','s','i','g','n','m','e','n','t']
print("Having such list:- ",end=" ")
print(list[:]) # printing elements from very starting to the end
print("Operations on List:- ")
print("1. insert()")
list.insert(10,'s') #10 is the place where we want to insert letter 's'.
print(list)
print("2. remove")
list.remove('s') # Here, the very first letter 's' will gonna remove
print(list)
print("3. append ")
list.append('p')
print(list)
print("4. len ")
length = len(list)
print("No. of elements present in list = ", length)
print("5. pop ")
print("Popped element ",list.pop())
print("After popping last element, list = ",list)
print("6. clear ")

18
TANVI CHOUHAN
20100BTCSFBI07423

list.clear()
print("Now, the list is empty using clear ",list)

Output:

19
TANVI CHOUHAN
20100BTCSFBI07423

PRACTICAL -15
AIM: - Write a program to demonstrate the use of tuples.
Code:
t1= ('Hey', 'There','I\'m', 'Tanvi',[2,3])
print("--> T1 tuple: ",t1)
a=()
print("--> Printing type of tuple named a",type(a))
print("--> Printing values inside tuple t1 using for loop to show tuples are iterable:
")
for i in t1:
print(i)
print("--> To show indexing & slicing in tuple: ")
print(f'The first element of tuple t1 is {t1[0]}')
print(f'The last element of tuple t1 is {t1[-1]}')
print("--> Using sorted function on tuple we can create list of that tuple")
k=(5,90,67,43,-1)
print("Tuple k which is unsorted: ", k)
b = sorted(k)
print("Sorted list b, after applying sorted function on tuple b: ",b)
print("--> Length of tuple b: ",len(b))
print("--> Tuples have count & index methods")
c=(78, 89, 90, 18, 23, 78, 90, 90)
print("Tuple c= ",c)
print("Counting no. of times 90 is repeated in tuple: ", c.count(90))

20
TANVI CHOUHAN
20100BTCSFBI07423

print("Getting the index value of 23: ",c.index(23) )


print("--> Adding tuples together ")
f= k + c
print("After adding tuple k & tuple c, the resultant tuple f will be :", f)
Output:

21
TANVI CHOUHAN
20100BTCSFBI07423

PRACTICAL -16
AIM: - Write a program to demonstrate the use of dictionary.
Code:
my_dictionary = {}
print(my_dictionary)
#to check the data type use the type() function
print(type(my_dictionary))
dict_i = dict()
print(dict_i)
print("Creating empty dictionary using dict() & checking the type of
it",type(dict_i))
#create a dictionary
my_information = {'name': 'Tanisha', 'age': 20, 'location': 'Indore'}
print("Printing dictionary which is having some keys & values ",my_information)
print("--> Creating dictionary using fromkeys() method ")
cities = ('Paris','Athens', 'Madrid')
#create the dictionary, `my_dictionary`, using the fromkeys() method
my_dictionary = dict.fromkeys(cities)
print(my_dictionary)
print("--> Setting a value that will be the same for all the keys in the dictionary")
cities = ('Paris','Athens', 'Madrid')
#create a single value
continent = 'Europe'
my_dictionary = dict.fromkeys(cities,continent)

22
TANVI CHOUHAN
20100BTCSFBI07423

print(my_dictionary)
print("--> Printing No. of keys inside the dictionary: ",len(my_dictionary))
print("--> Printing only keys inside the dictionary: ", my_dictionary.keys())
year_of_creation = {'Python': 1993, 'JavaScript': 1995, 'HTML': 1993}
print("--> Only printing values inside the dictionary: ",year_of_creation.values())
print("--> Accessing value for key 'name' : ", my_information['name'])
my_information['job'] = "Student"
print("--> After adding a new key & value to my_information: ",my_information)
print("--> Updating my_information: ")
my_information.update(name= 'Tanvi')
print(my_information)
Output:

23
TANVI CHOUHAN
20100BTCSFBI07423

PRACTICAL -17
AIM: - Write a program to build & package python modules for
reusability.

24
TANVI CHOUHAN
20100BTCSFBI07423

PRACTICAL -18
AIM: - Write a program to implement exception handling in python
application for error handling.

Code:
try:
x = float(input("Your number: "))
inverse = 1.0 / x
print("Inversion of given number: ",inverse)
except ValueError:
print("You should have given either an int or a float")
except ZeroDivisionError:
print("Infinity")
finally:
print("There may or may not have been an exception(Final block code).")
Output:

25
TANVI CHOUHAN
20100BTCSFBI07423

PRACTICAL -19
AIM: - Write a program to read & write files in python.

Output:

26
TANVI CHOUHAN
20100BTCSFBI07423

PRACTICAL -20
AIM: - Write a program to identify python object types.
Code:
language = "Python"
year = 1991
version = 3.9
tuple = ('P','y','t','h','o','n')
print("Checking type of object using type function")
print(type(language))
print(type(year))
print(type(version))
print(type(tuple))
print("Checking type of object using isinstance function")
print(isinstance(language, str))
print(isinstance(year, int))
print(isinstance(version, int))
print(isinstance(tuple,list))
Output:

27

You might also like