Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
133 views35 pages

Dav Institute of Engineering & Technology, Jalandhar

Download as docx, pdf, or txt
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 35

DAV INSTITUTE OF ENGINEERING & TECHNOLOGY, JALANDHAR

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

PROGRAMMING IN PYTHON LAB FILE


(BTCS 513-18)

SUBMITTED TO: SUBMITTED BY:


Mr. Aman Arora Karan Gupta
University Roll No.-1904018
Class Roll No. -166/19
CSE-5th sem
Python LAB Karan Gupta
BTCS 513-18 1904018

Familiarization with Programming Environment

Introduction to the programming environment


The term programming environment is sometimes reserved for environments containing
language specific editors and source level debugging facilities; here, the term will be used in
its broader sense to refer to all of the hardware and software in the environment used by the
programmer. All programming can therefore be properly described as takin place in a
programming environment.

Programming environments may vary considerably in complexity. An example of a simple


environment might consist of a text editor for program preparation, an assembler for
translating programs to machine language, and a simple operating system consisting of
input-output drivers and a file system. Although card input and non-interactive operation
characterized most early computer systems, such simple environments were supported on
early experimental time-sharing systems by 1963.

Introduction to Python Language

Python is a widely used general-purpose, high level programming language. It was created by
Guido van Rossum in 1991 and further developed by the Python Software Foundation. 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 Language

There are many features in Python, some of which are discussed below –
1. Easy to code: Python is a high-level programming language. Python is very easy to learn
the language as compared to other languages like C, C#, Javascript, Java, etc. It is very
easy to code in python language and anybody can learn python basics in a few hours or
days. It is also a developer-friendly language.

2. Free and Open Source: Python language is freely available at the official website. Since
it is open-source, this means that source code is also available to the public. So you can
download it as, use it as well as share it.

3. Object-Oriented Language: One of the key features of python is Object-Oriented


programming. Python supports object-oriented language and concepts of classes, objects
encapsulation, etc.
Python LAB Karan Gupta
BTCS 513-18 1904018

4. GUI Programming Support: Graphical User interfaces can be made using a module such
as PyQt5, PyQt4, wxPython, or Tk in python.PyQt5 is the most popular option for creating
graphical apps with Python.

5. High-Level Language: Python is a high-level language. When we write programs in


python, we do not need to remember the system architecture, nor do we need to manage the
memory.

6. Extensible feature: Python is a Extensible language. We can write us some Python code


into C or C++ language and also we can compile that code in C/C++ language.

7. Python is Portable language: Python language is also a portable language. For example,
if we have python code for windows and if we want to run this code on other platforms
such as Linux, Unix, and Mac then we do not need to change it, we can run this code on
any platform.

8. Python is Integrated language: Python is also an Integrated language because we can


easily integrated python with other languages like c, c++, etc.

9. Interpreted Language: Python is an Interpreted Language because Python code is


executed line by line at a time. like other languages C, C++, Java, etc. there is no need to
compile python code this makes it easier to debug our code. The source code of python is
converted into an immediate form called byte code.

10. Large Standard Library Python has a large standard library which provides a rich set of
module and functions so you do not have to write your own code for every single thing.
There are many libraries present in python for such as regular expressions, unit-testing,
web browsers, etc.

11. Dynamically Typed Language: Python is a dynamically-typed language. That means


the type (for example- int, double, long, etc.) for a variable is decided at run time not in
advance because of this feature we don’t need to specify the type of variable.

Advantage of Python Language

The Python language has diversified application in the software development companies such
as in gaming, web frameworks and applications, language development, prototyping, graphic
design applications, etc. This provides the language a higher plethora over other
programming languages used in the industry. Some of its advantages are-

 Extensive Support Libraries: It provides large standard libraries that include the areas like
string operations, Internet, web service tools, operating system interfaces and protocols.
Most of the highly used programming tasks are already scripted into it that limits the
length of the codes to be written in Python.
Python LAB Karan Gupta
BTCS 513-18 1904018

 Integration Feature: Python integrates the Enterprise Application Integration that makes it
easy to develop Web services by invoking COM or COBRA components. It has powerful
control capabilities as it calls directly through C, C++ or Java via Jython. Python also
processes XML and other markup languages as it can run on all modern operating
systems through same byte code.

 Improved Programmer’s Productivity: The language has extensive support libraries and
clean object-oriented designs that increase two to tenfold of programmer’s productivity
while using the languages like Java, VB, Perl, C, C++ and C#.

 Productivity: With its strong process integration features, unit testing framework and
enhanced control capabilities contribute towards the increased speed for most
applications and productivity of applications. It is a great option for building scalable
multi-protocol network applications.

Disadvantages of Python Languages

Python has varied advantageous features, and programmers prefer this language to other
programming languages because it is easy to learn and code too. However, this language has
still not made its place in some computing arenas that includes Enterprise Development
Shops. Therefore, this language may not solve some of the enterprise solutions, and
limitations include-

 Difficulty in Using Other Languages: The Python lovers become so accustomed to its
features and its extensive libraries, so they face problem in learning or working on other
programming languages. Python experts may see the declaring of cast “values” or
variable “types”, syntactic requirements of adding curly braces or semi colons as an
onerous task.

 Weak in Mobile Computing: Python has made its presence on many desktop and server
platforms, but it is seen as a weak language for mobile computing. This is the reason very
few mobile applications are built in it like Carbonnelle.

 Gets Slow in Speed: Python executes with the help of an interpreter instead of the
compiler, which causes it to slow down because compilation and execution help it to
work normally. On the other hand, it can be seen that it is fast for many web applications
too.

 Run-time Errors: The Python language is dynamically typed so it has many design
restrictions that are reported by some Python developers. It is even seen that it requires
more testing time, and the errors show up when the applications are finally run.
Python LAB Karan Gupta
BTCS 513-18 1904018

 Underdeveloped Database Access Layers: As compared to the popular technologies


like JDBC and ODBC, the Python’s database access layer is found to be bit
underdeveloped and primitive. However, it cannot be applied in the enterprises that need
smooth interaction of complex legacy data.

Python 3.9 idle

IDLE stands for Integrated Development and Learning Environment. The story behind the
name IDLE is similar to Python. Guido Van Rossum named Python after the British comedy
groups Monty Python while the name IDLE was chosen to pay tribute to Eric Idle, who was
one of the Monty Python's founding members. IDLE comes bundled with the default
implementation of the Python language since the 01.5.2b1 release. It is packaged as an
optional part of the Python packaging with many Linux, Windows, and Mac distributions.

IDLE, as shown above, is a very simple and sophisticated IDE developed primarily for
beginners, and because of its simplicity, it is highly considered and recommended for
educational purposes. It offers a variety of features that you will look in detail along with
examples later in this tutorial.

Some of the key features it offers are:


 Python shell with syntax highlighting,
 Multi-window text editor,
 Code auto completion,
 Intelligent indenting,
 Program animation and stepping which allows one line of code to run at a time helpful
for debugging,
 Persistent breakpoints,
 Finally, Call stacks visibility.
Python LAB Karan Gupta
BTCS 513-18 1904018

Task 1:
Write a program to demonstrate different number data types in Python.

Input:-

#str
x = "Hello World"
print(type(x),x)

#int
x = 20
print(type(x),x)

#float
x = 20.5
print(type(x),x)

#complex
x = 3+1j
print(type(x),x)

#list
x = ["Apple", "Banana", "Cherry"]
print(type(x),x)

#tuple
x = ("Apple", "Banana", "Guava")
print(type(x),x)

#dict
x = {"First-name" : "John", "Last-name" : "Smith"}
print(type(x),x)

#set
x = {"Football", "Hockey", "Tennis"}
print(type(x),x)

#bool
x = False
print(type(x),x)
Python LAB Karan Gupta
BTCS 513-18 1904018

Output:-
Python LAB Karan Gupta
BTCS 513-18 1904018

Task 2:
Write a program to perform different Arithmetic Operations on numbers in Python.

Input:-

# Examples of Arithmetic Operator


a=9
b=4

print ("a: ", a,",","b: ", b)

# Addition of numbers
add = a + b

# Subtraction of numbers
sub = a - b

# Multiplication of number
mul = a * b

# Division(float) of number
div1 = a / b

# Division(floor) of number
div2 = a // b

# Modulo of both number


mod = a % b

# Power
p = a ** b

# print results
print("Additon: ", add)
print("Subtraction: ", sub)
print("Multiplication: ", mul)
print("Division(float): ", div1)
print("Division(floor): ", div2)
print("Modulo ", mod)
print("Power: ",p)
Python LAB Karan Gupta
BTCS 513-18 1904018

Output:-
Python LAB Karan Gupta
BTCS 513-18 1904018

Task 3:
Write a program to create, concatenate and print a string and accessing sub-string from a
given string.

Input:-

x = "Python is "
y = "awesome"
z= x+y
print ("x: ",x)
print ("y: ",y)
print("concatenated string: ", z)

string = "Programming in Python"


print ("string: ", string)

str1 = string[0:8]
print("substring string[0:8]-->", str1)

str2 = string[5:8]
print("substring string[5:8]-->", str2)

str3 = string[-1]
print("substring string[-1]-->", str3)

Output:-
Python LAB Karan Gupta
BTCS 513-18 1904018

Task 4:
Write a python script to print the current date in the following format “Sun May 29 02:26:23
IST 2017”
Input:-

import datetime

x = datetime.datetime.now()
# “Sun May 29 02:26:23 IST 2017”
weekday = x.strftime("%a")
month = x.strftime("%b")
day = x.strftime("%d")
hour = x.strftime("%H")
minute = x.strftime("%M")
sec = x.strftime("%S")
year = x.strftime("%Y")

print(weekday, month, day, hour+":"+minute+":"+sec, "IST", year)

Output:-
Python LAB Karan Gupta
BTCS 513-18 1904018

Task 5:
Write a program to create, append, and remove lists in python.
Input:-

#create, append, and remove lists in python

cubes = [1, 8, 27, 64, 125]


print ("creating list: ", cubes)

# insert 4 at position 3
cubes.insert(3, 4)
print ("inserting into list: ", cubes)

#remove first occurence of 4


cubes.remove(4)
print ("removing from list: ", cubes)

#append
cubes.append(216)
print ("appending into list: ", cubes)

#list-sorting
cubes.sort(reverse=True)
print ("sorting in reverse order :", cubes)
Python LAB Karan Gupta
BTCS 513-18 1904018

Output:-
Python LAB Karan Gupta
BTCS 513-18 1904018

Task 6:
Write a program to demonstrate working with tuples in python.
Input:-

#tuples in python

subjects = ('python', 'dbms', 'cn', 'flat', 'erp')


print ("creating tuple subjects: ", subjects)

print ("subjects[1:5]: ", subjects[1:5])

print ("length of subjects: ", len(subjects))

#membership test
print ("checking if 'se' in subjects: ", ('se' in subjects))

#updating tuple
print ("updating tuple subjects: ")
subjects[1] = "se"

Output:-
Python LAB Karan Gupta
BTCS 513-18 1904018

Task 7:
Write a program to demonstrate working with dictionaries in python.
Input:-

# empty dictionary
my_dict = {}

# dictionary with integer keys


my_dict = {1: 'apple', 2: 'ball'}
print ('dicitonary: ', my_dict)

# dictionary with mixed keys


my_dict = {'name': 'John', 1: [2, 4, 3]}
print ('dicitonary with mixed keys: ', my_dict)

# remove all items


my_dict.clear()

# create a dictionary
squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

print ('dictionary items: ', squares.items())

# remove a particular item, returns its value


print("Removing value for key 4 from dictionary: ", squares.pop(4))

print('Square of 5 is: ', squares.get(5))

#sorted() - Return a new sorted list of keys in the dictionary.


Python LAB Karan Gupta
BTCS 513-18 1904018

print('Sorted keys(reversed): ', sorted(squares, reverse=True))

Output:-
Python LAB Karan Gupta
BTCS 513-18 1904018

Task 8:
Write a python program to find largest of three numbers.
Input:-

print("Enter three numbers:")


a = float(input())
b = float(input())
c = float(input())
if a>b and a>c:
largest = a
elif b>a and b>c:
largest = b
else:
largest = c

print (f"Largest number: {largest}")


Output:-
Python LAB Karan Gupta
BTCS 513-18 1904018

Task 9:
Write a Python program to convert temperatures to and from Celsius, Fahrenheit.
Input:-

print ("Enter 1 to convert from Celsius to Fahrenheit")


print ("Enter 2 to convert from Fahrenheit to Celsius")
a = int(input())
if a == 1:
cel = float(input("Enter temp in celsius:"))
far = cel*9/5 + 32
print (f"Temp in Fahrenheit: {far}")

elif a == 2:
far = float(input("Enter temp in Fahrenheit:"))
cel = (far-32)*5/9
print (f"Temp in Fahrenheit: {cel}")

else:
print("Did not enter correct choice")

Output:-
Python LAB Karan Gupta
BTCS 513-18 1904018

Task 10:
Write a Python program to construct the following pattern, using a nested for loop

*
**
***
****
***
**
*
Input:-

# print a * pattern using nested for


def pattern(n):
for i in range(0, n):
for j in range(0, i):
print("* ", end="")
print("\r")

for i in range(n, 0 , -1):


for j in range(0, i):
print("* ", end="")
print("\r")

pattern(4)
Python LAB Karan Gupta
BTCS 513-18 1904018

Output:-
Python LAB Karan Gupta
BTCS 513-18 1904018

Task 11:
Write a Python script that prints prime numbers less than 20.
Input:-
lower = 1
upper = 20

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:-
Python LAB Karan Gupta
BTCS 513-18 1904018

Task 12:
Write a python program to find factorial of a number using Recursion.
Input:-
# factorial of a number using Recursion

def rec_factorial(n):
if n == 1:
return n
else:
return n*rec_factorial(n-1)

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

if num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of", num, "is", rec_factorial(num))

Output:-
Python LAB Karan Gupta
BTCS 513-18 1904018

Task 13:
Write a program that accepts the lengths of three sides of a triangle as inputs. The program
output should indicate whether or not the triangle is a right triangle (Recall from the
Pythagorean Theorem that in a right triangle, the square of one side equals the sum of the
squares of the other two sides).
Input:-
print("Input three integers(sides of a triangle)")
x = int(input())
y = int(input())
z = int(input())

if x**2 + y**2 == z**2:


print('Yes')
else:
print('No')
Output:-
Python LAB Karan Gupta
BTCS 513-18 1904018

Task 14:
Write a python program to define a module to find Fibonacci Numbers and import the
module to another program.
Input:-
(a)
# define a module to find Fibonacci Numbers and import the module to another program

def fibonacci(n):
# first two terms
n1, n2 = 0, 1
count = 0

# check if the number of terms is valid


if n <= 0:
print("Please enter a positive integer")

elif n == 1:
print("Fibonacci sequence upto", terms, ":")
print(n1)

else:
print("Fibonacci sequence: ")
while count < n:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1
Python LAB Karan Gupta
BTCS 513-18 1904018

if __name__ == "__main__":
terms = int(input("How many terms? "))
fibonacci(terms)

Output:-

(b)
import lab14module
terms = int(input("Enter number of terms:"))
lab14module.fibonacci(terms)
Output:-

Task 15:
Python LAB Karan Gupta
BTCS 513-18 1904018

Write a python program to define a module and import a specific function in that module to
another program.
Input:-
(a)
def absolute_value(num):
"""This function returns the absolute
value of the entered number"""

if num >= 0:
return num
else:
return -num

if __name__ == "__main__":
n = int(input("Enter a number"))
res = absolute_value(n)
print (res)

Output:-

(b) # define a module and import a specific function in that module to another program

import lab15module
n = int(input("Enter a number: "))
res = lab15module.absolute_value(n)
print (res)

Output:-
Python LAB Karan Gupta
BTCS 513-18 1904018

Task 16:
Python LAB Karan Gupta
BTCS 513-18 1904018

Write a script named copyfile.py. This script should prompt the user for the names of two
text files. The contents of the first file should be input and written to the second file.
Input:-
# open both files
with open('lab16file1.txt','r') as firstfile, open('lab16file2.txt','a') as secondfile:

# read content from first file


for line in firstfile:

# append content to second file


secondfile.write(line)
Output:-

As we can see code has been appended in file 2.

Task 17:
Python LAB Karan Gupta
BTCS 513-18 1904018

Write a program that inputs a text file. The program should print all of the unique words in
the file in alphabetical order.
Input:-
# print all of the unique words in the file in alphabetical order

words = list()
with open('python-wiki.txt','r') as file:

# reading each line


for line in file:

# reading each word


for word in line.split():

# appending word to the list words


words.append(word)

word_set = set(words)
words = sorted(word_set)
print (words)

Output:-
Python LAB Karan Gupta
BTCS 513-18 1904018

Task 18:
Python LAB Karan Gupta
BTCS 513-18 1904018

Write a Python class to convert an integer to a roman numeral.


Input:-
# Write a Python class to convert an integer to a roman numeral

class conversion:

def __init__(self, n_int):


self.n = n_int

def printRoman(self):
num = [1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000]
sym = ["I", "IV", "V", "IX", "X", "XL", "L", "XC", "C", "CD", "D",
"CM", "M"]
i = 12
while self.n:
div = self.n // num[i]
self.n %= num[i]

while div:
print(sym[i], end = "")
div -= 1
i -= 1

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


conv = conversion(num)
conv.printRoman()

Output:-
Python LAB Karan Gupta
BTCS 513-18 1904018

Task 19:
Python LAB Karan Gupta
BTCS 513-18 1904018

Write a Python class to implement pow(x, n)

Input:-
# Write a Python class to implement pow(x, n)

class pow:

def power(self, x, y):


if(y == 0):
return 1
temp = self.power(x, int(y / 2))

if (y % 2 == 0):
return temp * temp
else:
if(y > 0):
return x * temp * temp
else:
return (temp * temp) / x

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


p = int(input("Enter power: "))

powObj = pow()
res = powObj.power(num, p)
print (res)

Output:-
Python LAB Karan Gupta
BTCS 513-18 1904018

Task 20:
Python LAB Karan Gupta
BTCS 513-18 1904018

Write a Python class to reverse a string word by word.


Input:-
# reverse a string word by word

class Rev:

def reverse(self, sentence):


# first split the string into words
words = sentence.split(' ')
# then reverse the split string list and join using space
reverse_sentence = ' '.join(reversed(words))
# finally return the joined string
return reverse_sentence

str1 = input("Enter a sentence: ")


revObj = Rev()
res = revObj.reverse(str1)
print (res)

Output:-

You might also like