Dav Institute of Engineering & Technology, Jalandhar
Dav Institute of Engineering & Technology, Jalandhar
Dav Institute of Engineering & Technology, Jalandhar
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.
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.
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.
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.
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.
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.
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
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.
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:-
# 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
# 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)
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")
Output:-
Python LAB Karan Gupta
BTCS 513-18 1904018
Task 5:
Write a program to create, append, and remove lists in python.
Input:-
# insert 4 at position 3
cubes.insert(3, 4)
print ("inserting into 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
#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 = {}
# create a dictionary
squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Output:-
Python LAB Karan Gupta
BTCS 513-18 1904018
Task 8:
Write a python program to find largest of three numbers.
Input:-
Task 9:
Write a Python program to convert temperatures to and from Celsius, Fahrenheit.
Input:-
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:-
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
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)
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())
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
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:
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:
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
class conversion:
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
Output:-
Python LAB Karan Gupta
BTCS 513-18 1904018
Task 19:
Python LAB Karan Gupta
BTCS 513-18 1904018
Input:-
# Write a Python class to implement pow(x, n)
class pow:
if (y % 2 == 0):
return temp * temp
else:
if(y > 0):
return x * temp * temp
else:
return (temp * temp) / x
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
class Rev:
Output:-