0% found this document useful (0 votes)
409 views26 pages

Convert Fahrenheit to Celsius in AWK

The document is a practical lab report submitted by Ankit Kumar to Komal Sharma for the course Python Programming (BTCS 510-18). It contains 20 programming problems solved in Python with the goal of demonstrating skills in variables, data types, operators, conditional statements, loops, functions, modules, classes and exceptions. The problems cover topics like number systems, strings, lists, tuples, dictionaries, file handling and more. Sample code and outputs are provided for each problem.

Uploaded by

ankit kumar
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)
409 views26 pages

Convert Fahrenheit to Celsius in AWK

The document is a practical lab report submitted by Ankit Kumar to Komal Sharma for the course Python Programming (BTCS 510-18). It contains 20 programming problems solved in Python with the goal of demonstrating skills in variables, data types, operators, conditional statements, loops, functions, modules, classes and exceptions. The problems cover topics like number systems, strings, lists, tuples, dictionaries, file handling and more. Sample code and outputs are provided for each problem.

Uploaded by

ankit kumar
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

l,

PRACTICAL LAB
OF
PYTHON PROGRAMMING
(BTCS 510-18)

BACHELOR OF TECHNOLOGY
In
(Electronics & Communication Engineering)

Submitted By : Submitted To :
Ankit Kumar Komal Sharma
Roll No. (1816652) (Assistant Professor )
Batch 2018-2022 CSE Department

CHANDIGARH ENGINEERING COLLEGE


JHANJERI, MOHALI
l,

Affiliated to I.K Gujral Punjab Technical University, Jalandhar

Table of Contents

No. Of Practicals
1. Write a program to demonstrate different number datatypes in python.
2. Write a program to perform different arithmetic operations on numbers in python.
3. Write a program to create, concatenate and print a string and accessing sub-string
from a given string.
4. Write a python script to print the current date in following format “Sun May 29,
[Link] IST 2017”
5. Write a python program to create, append and remove lists in python.
6. Write a program to demonstrate working with tuples in python.
7. Write a program to demonstrate working with dictionaries in python.
8. Write a python program to find largest of three numbers.
9. Write a python program to convert temperature to and from Celsius to fahrenheit.
10. Write a python program to construct the following pattern using nested for loop.
11. Write a python program to print prim numbers less than 20.
12. Write a python program to find factorial of a number using recursion.
13. Write a python program to that accepts length of three sides of a triangle as inputs.
The program should indicate whether or not the triangle is a right-angled triangle
(use Pythagorean theorem).
14. Write a python program to define a module to find Fibonacci Numbers and import
the module to another program.
15. Write a python program to define a module and import a specific function in
that module to another program.
16. Write a script named [Link]. This script should prompt the user for the names
of two text files. The contents of the first file should be innput and written to the
second file.
17. Write a program that inputs a text file. The program should print all of the unique
words in the file in alphabetical order.
l,

18.

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


19. Write a Python class to implement pow(x, n).
20. Write a Python class too reverse a string word by word.

1. Write a program to demonstrate different number datatypes in python.


Source code:

i=7

c=24+8j

f=701

s='HELLO EVERYONE!!\nThis is john\'s python programming..'

# NOTE: boolean has truth values that are case sensitive Ex: True (T is
caps!) b= True

print("the value of c is:",i,'\nits type is:',type(i))

print("the value of c is:",f,'\nits type is:',type(f))

print("the value of c is:",c,'\nits type is:',type(c))

print("the value of c is:",s,'\nits type is:',type(s))

rint("the value of c is:",b,'\nits type is:',type(b))

print('NOTE: boolean has truth values that are case sensitive Ex: True (T is caps!)')
l,

Output:
l,

2. Write a program to perform different arithmetic operations on numbers in python.


Source code:

a=10; b=3

print("addition of a:",a,"&b:",b,"is:",a+b)

print("substraction of a:",a,"&b:",b,"is:",a-b)

print("multiplication of a:",a,"&b:",b,"is:",a*b)

print("division of a:",a,"&b:",b,"is:",a/b)

print("floor divison of a:",a,"&b:",b,"is:",a//b)

print("moduli of a:",a,"&b:",b,"is:",a%b)

print("exponent of a:",a,"&b:",b,"is:",a**b)

Output:
l,

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

pi=3.14

s= "Venkata"

v= "Subhramanyam"

print("the value of s is:",s)

print("the value of v is:",v)

string_add = s+v

print("after concatenating s and v the string is:",s+v)

text = 'The value of pi is ' + str(pi)

print("NOTE: variables after '+' operator must be converted to string before using them as
strings\n otherwise value will be considered as its class type")

print(text)

Output:
l,

4. Write a python script to print the current date in following format “Sun
May 29 [Link] IST 2017”

Source code:

import time

import datetime

x =[Link]()

print([Link]("%c"))

Output:
l,

5. Write a python program to create, append and remove lists in python.

Source code:

# creating list with college names..

colleges = ["SIIET", "GNIT", "AVN"]

print(colleges)

# appending new college in collges list

[Link]("MVSR")

#checking if its added or not

print(colleges)

#adding a new college at a positon

[Link](1,"BHARAT")

print(colleges) #remove a name from

colleges [Link]("BHARAT")

print(colleges)

#remove a name with an index value

del colleges[1]

# NOTE: index starts from 0 so 2nd value in list will be


removed print(colleges)

Output:
l,

6. Write a program to demonstrate working with tuples in python


Source code:

# creating tuples with college names..

colleges = ("SIIET","BHARAT","GNIT", "AVN")

print("the lists in colleges tuple is",colleges)

print("we can\'t add or remove new elements in a tuple")

print("length of the tuple colleges is:",len(colleges))

# checking whether 'SIIET' is present in the tuple or


not if "SIIET" in colleges:

print("Yes, 'SIIET' is in the colleges tuple")

Output:
l,

7. Write a program to demonstrate working with dictionaries in python


Source code:

# creating a dictionary
for SIIET college = {

"name": "siiet",

"code": "INDI",

"id": "x3"

print(college)

#adding items to dictionary

college["location"] = "IBP"

print(college)

#changing values of a key

college["location"] = "sheriguda"

print(college)

# to remove items
use pop()
[Link]("code")
print(college)
#know the length using len()
print("length of college
is:",len(college)) #to copy the same
dictionary use copy() mycollege=
[Link]() print(mycollege)

Output:
l,

8. Write a python program to find largest of three numbers


Source code:

# user-defined function to know which number


is larger def bigOf3(a,b,c):

if(a>b):

if(a>c):

print("a is greater than b and c")

else:

print("c is greater than a and b")

elif(b>c):

print("b is greater than a and c")

else:

print("c is greater than a and b")

txt= input("enter a,b,c values:")

a,b,c= [Link]()

bigOf3(int(a),int(b),int(c)) #calling the function

Output:
l,

9. Write a python program to convert temperature to and from Celsius to fahrenheit.


Source code:
while(1):

print("[Link] TO FAHRENHEIT\[Link] TO CELSIUS\[Link]\n")

choice=input("ENTER YOUR CHOICE:")

ch=int(choice)

if(ch==1):

c=int(input("ENTER TEMPERATURE IN CELSIUS:"))

f=((9*c)/5)+32

print("converted temperature is:",f)

elif(ch==2):

f=int(input("ENTER TEMPERATURE IN FAHRENHEIT:"))

c=((f-32)/9)*5

print("converted temperature is:",c)

elif(ch==3):

exit()

else:

print("wrong choice")

Output:
l,

10. Write a python program to construct the following pattern using nested for loop:

*
**
***
****
*****
*****
****
***
**
*
Source code:

n=int(input("ENTER A VALUE:"))

for x in range(0,n+1,1):

print(x*'*')

if(x==n):

for x in range(n,0,-1): print(x*'*')

Output:
l,

11. Write a python program to print prim numbers less than 20:
Source code:

n=int(input("enter range of prime numbers:"))

for num in range(2,n+1): #takes each number

count=0

for i in range(2,num//2+1): #checks the divisibility of each num

if(num%i==0):

count=count+1 #if its noot prime count increases.

if(count==0):

print(num)

Output:
l,

12. Write a python program to find factorial of a number using recursion:


Source code:

def recursion(n):

if(n<1):

print("FACTORIAL NOT POSSIBLE!!")

elif(n>1):

return n*recursion(n-1)

else:

return 1

n=int(input("enter a number:"))

print("factorial of",n,"is:",recursion(n))

OUTPUT:
l,

13. Write a python program to that accepts length of three sides of a triangle as
inputs. The program should indicate whether or not the triangle is a right-angled
triangle (use Pythagorean theorem):

Source code:

a=float(input("enter length of hypotenuse side:"))

b=float(input("enter length of base side:"))

c=float(input("enter length of height side:"))

def pythagorean(a,b,c): #defining function


a=a*a; b=b*b; c=c*c

if(a==b+c):

print("yes!! the given inputs are triplets of a right angled triangle!!")

print("height:",c**0.5,"\nbase:",b**0.5,"\nhypotenuse:",a**0.5)

pythagorean(a,b,c) # calling function

Output:
l,

14. Write a python program to define a module to find Fibonacci Numbers and
import the module to another program.
Source code:

[Link]

def fibonacci(n):

n1=0; n2=1;

print(n1)

print(n2)

for x in range(0,n):

n3=n1+n2

if(n3>=n):

break;

print(n3,end = ' ')

n1=n2

n2=n3

using_fibonacci.py

Note: we will be using previous program as a library or package It is mandatory to write both

the programs are separately

import fibonacci

n=int(input("enter range:"))

if(n<0):

print("enter correct range!!")

else:
l,

print("-------------------------------FIBONACCI SERIES ------------------------------- \n")

[Link] (n)
l,

Output:
l,

15. Write a python program to define a module and import a specific function in
that module to another program.
Source code:

[Link]

def fibonacci(n):
n1=0;
n2=1;
print(n1)
print(n2)

for x in range(0,n):

n3=n1+n2

if(n3>=n):

break;

print(n3,end = ' ')

n1=n2

n2=n3

using_fibonacci.py

Note: we will be using previous program as a library or package It is mandatory to write


both the programs are separately
from fibonacci import fibonacci

n=int(input("enter range:"))

if(n<0):

print("enter correct range!!")

else:

print("-------------------------------FIBONACCI SERIES ------------------------------- \n")

fibonacci (n)
l,

Output:
l,

[Link] a script named [Link]. This script should prompt the user for the names of
two text files. Thhe contents of the first file should be innput and written to the second
file.
Source code:

Note: create a text file as “[Link]” and write some date in it. This will be used in the program.

with open("[Link]") as inputt:

with open("[Link]","w") as output:

for line in input: output.w rite(line)

print("JOB DONE!!")

Output:
l,

17. Write a program that inputs a text file. The program should print all of the
unique words in the file in alphabetical order.
Source code:

fname=input("enter file name with correct extension:")

file_opened=open(fname)

our_list=list() #creating an empty list

for line in file_opened:

word=[Link]().split() #rstrip for removing unwanted spaces

for element in word:

if element in our_list:

continue

else:

our_list.append(element)

our_list.sort()

print(our_list)

Output:
l,

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


Source code:

class roman_solution:

def int_to_Roman(num):

val = [1000, 900, 500, 400, 100, 90, 50, 40, , 9, 5, 4, 1]

syb = ["M", "CM", "D", "CD", "C", "XC", "L", "XL","X", "IX", "V", "IV",
"I” ] roman_num = “”

i=0

if(n<1 or n>3999):

print("ENTER A GOOD VALUE!")

else:

while num > 0:

if(num-val[i]>=0):

roman_num+=syb[i]

num-=val[i]

else:

i+=1

return roman_num n=int(input("ENTER A NUMBER:"))

print("roman numeral of given number is:",roman_solution.int_to_Roman(n))

Output:
l,

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


Source code:

class py_power:

def power(x,n):

print("power of given literals:\nx:",x,"\nn\n:",n,"is:",x**n)

x=float(input("ENTER X(BASE) VALUE:"))

n=float(input("ENTER N(POWER) VALUE:"))

py_power.power(x,n)

Output:
l,

20. Write a Python class too reverse a string word by word.


Source code:

fname="HELLO EVERYONEE THIS IS PYTHON PROGRAMMING ANND WE'RE


PLAYING WITH LISTS"

our_list=list() #creating an empty list

word=[Link]() #spliting up the list

for element in word:

our_list.append(element)

print("tried sentence is:",ourr_list)

our_list.reverse() #method to reverse the elements in the list

print("list after the reverse()",oour_list)

Output:

Common questions

Powered by AI

Lists in Python are mutable, meaning that you can modify them in place by adding, removing, or changing elements, as shown when colleges are appended to and removed from the list . In contrast, tuples are immutable, so once they are defined, their elements cannot be changed, added, or removed, demonstrated by the tuple example that includes colleges without the ability to modify its content .

The method involves opening the text file, iterating through each line, splitting lines into words, and storing them in a list. If the word is not already in the list, it gets appended. After processing all lines, the list is sorted to display the words in alphabetical order. This approach ensures that each word is included only once in the output list, achieved through checking membership before appending .

The 'copyfile.py' script reads from a specified input file and writes its contents to a specified output file. It ensures that both files are properly opened and closed by using the 'with' statement, which automatically handles file closing, thus preventing file leaks and ensuring efficient resource management. The script prompts the user for file names, allowing flexibility and user control in file handling operations .

In Python, class implementation allows for encapsulation of logical processes in a structured way. For converting integers to Roman numerals, a class method can easily map integer values to their respective Roman numeral strings in descending order of precedence. It iteratively subtracts the integer values from the number while the value is greater than the integer, appending the corresponding Roman symbol to a result string, neatly encapsulating this conversion logic within a class method .

Using classes to implement mathematical operations in Python allows for organizing functions into logical units with the added benefit of object-oriented features like encapsulation and reusability. For power functions, a class method can take base and exponent arguments, compute the result using the '**' operator, and return the result in a clean interface that can be easily reused or extended in more complex class structures .

Importing modules in Python allows code to be organized into reusable components or libraries, promoting clean and efficient code. In the Fibonacci example, the function to calculate Fibonacci numbers is defined in a separate module and imported into another script, demonstrating how a well-defined function can be reused without rewriting the logic, thus enhancing modularity and code reusability .

The recursive approach to calculating factorial involves defining a function that calls itself with a reduced argument until a base case is reached. In the Python source code, the factorial function checks if the input number is less than 1 (invalid input), equals 1 (base case returning 1), or greater than 1, in which case it returns the product of the number and the factorial of the number minus one .

Python uses the Pythagorean theorem, a^2 = b^2 + c^2, to check whether a triangle is right-angled by squaring the lengths of the sides and checking if the square of the longest side (hypotenuse) equals the sum of the squares of the other two sides. The source code uses this method to print out a confirmation when the condition holds true, signifying that the given sides form a right-angled triangle .

The Python program uses nested loops to construct a pattern of asterisks that first increases in line count and then decreases. It begins with a loop that increases the count of asterisks printed on each line until a maximum is reached, then reverses the process with a second loop decrementing the count of asterisks printed. This double-loop structure allows for the symmetric increase and decrease, producing a complete pyramid shape .

Python handles strings as a sequence of characters, allowing for concatenation using the '+' operator after converting non-string variables into strings, as shown in the examples where variables are concatenated into a full string . Extraction, or slicing, can be achieved by accessing characters using index positions, but specific examples of slicing were not shown in the provided document excerpts.

You might also like