[go: up one dir, main page]

0% found this document useful (0 votes)
26 views31 pages

PYTHON Practical Final For Btech Cse Students

It's python lab file that help students too much to do work of python lab manual as they can do their lab work with the help of this

Uploaded by

anuragjangir668
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views31 pages

PYTHON Practical Final For Btech Cse Students

It's python lab file that help students too much to do work of python lab manual as they can do their lab work with the help of this

Uploaded by

anuragjangir668
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

2332459 BTCS-513-18

LYALLPUR KHALSA COLLEGE TECHNICAL CAMPUS


JALANDHAR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

PYTHON PRACTICAL

Class: B. Tech CSE – 5A


Name: Simranjot
Roll no: 2332459
2332459 BTCS-513-18
Task 8: Write a python program to find largest of three numbers.
Code:
num1 = int (input ("Enter first number: "))
num2 = int (input ("Enter second number: "))
num3 = int (input ("Enter third number: "))
if (num1 > num2) and (num1 > num3):
largest = num1
elif (num2 > num1) and (num2 > num3):
largest = num2
else:
largest = num3
print ("The largest number is", largest)

Output:
2332459 BTCS-513-18
Task 9: Write a Python program to convert temperatures to and from Celsius, Fahrenheit.
[ Formula: c/5 = f-32/9].
Code:
print ("Options are \n")
print ("1. Convert temperatures from Celsius to Fahrenheit \n")
print ("2. Convert temperatures from Fahrenheit to Celsius \n")
choice=int (input ("Choose any Option (1 or 2): "))
if choice==1:
print ("Convert temperatures from Celsius to Fahrenheit \n")
cel = float (input ("Enter Temperature in Celsius: "))
fahr=(cel*9/5) +32
print ("Temperature in Fahrenheit = “, fahr)
elif choice==2:
print ("Convert temperatures from Fahrenheit to Celcius\n")
fahr = float (input ("Enter Temperature in Fahrenheit: "))
cel=(fahr-32) *5/9;
print ("Temperature in Celsius = “, cel)
else:
print ("Invalid Option")

Output:
2332459 BTCS-513-18
Task 10: Write a Python program to construct the following pattern, using a nested for Loop.
*
**
***
****
*****
****
***
**
*
Code:
n=5;
for i in range(n):
for j in range(i):
print ('*', end="")
print ()
for i in range (n,0, -1):
for j in range(i):
print ('*', end="")
print ()

Output:
2332459 BTCS-513-18
Task 11: Write a Python script that prints prime numbers less than 20.
Code:
print ("Prime numbers between 1 and 20 are:")
i=20;
for num in range(i):
if num > 1:
for i in range (2, num):
if (num % i) ==0:
break
else:
print(num)

Output:
2332459 BTCS-513-18
Task 21: A) Print Pattern 1: using a for loop and range function.
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
Code:
for i in range (1, 6):
for j in range(i):
print (i, end=" ")
print ()

Output:

(B)
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
Code:
for i in range (1, 6):
for j in range (i, 0, -1):
print (j, end=" ")
print ()

Output:
2332459 BTCS-513-18
Task 22: To check whether a give number is even or odd.
Code:
number = int(input("Enter an integer: "))
if number % 2 == 0:
print(f"{number} is an even number.")
else:
print(f"{number} is an odd number.")

Output:

Task 23: To find sum of all the digits of a given number.


Code:
number = input ("Enter a number: ")
sum = 0
for digit in number:
sum += int(digit)
print ("The sum of the digits is:", sum)

Output:
2332459 BTCS-513-18
Task 24: To check whether a number is palindrome or not.
Code:
number =int (input ("Enter the number: "))
original = number
reversed_num = 0
while original > 0:
last_digit = original % 10
reversed_num = (reversed_num * 10) + last_digit
original = original // 10
if number == reversed_num:
print(f"{number} is a palindrome.")
else:
print(f"{number} is not a palindrome.")

Output:
2332459 BTCS-513-18
Task 25: Check if a Substring is Present in a given String.
Code:
string = input ("Enter the string: ")
sub_string = input ("Enter the Sub string: ")
if sub_string in string:
print(f"'{sub_string}' is present in '{string}'.")
else:
print(f"'{sub_string}' is not present in '{string}'.")

Output:
2332459 BTCS-513-18
Task 1: Write a program to demonstrate different number data types in Python.
Code:
# 1. String
name = input ("Enter your name (String): ")
print ("Value:", name)
print ("type:", type(name))
# 2. Tuple
numbers tuple = tuple (input ("\n Enter numbers for tuple: "))
print ("Value:", numbers_tuple)
print (" Type:", type(numbers_tuple))
# 3. List
numbers_list = input ("\n Enter numbers for list separated by space: "). split ()
print ("Value:” numbers_list)
print (" Type:", type(numbers_list))
# 4. Dictionary
student = {}
student["name"] = input ("\nEnter student name: ")
student["age"] = int (input ("Enter student age: "))
student["grade"] = input ("Enter student grade: ")
print ("Value:", student,)
print ("Type:", type(student))
# 5. Set
items = set (input ("\nEnter some items separated by space: "). split ())
print ("Value:", items, "| Type:", type(items))

Output:
2332459 BTCS-513-18
Output:
2332459 BTCS-513-18
Task 2: Write a program to perform different Arithmetic Operations on numbers in python.
Code:
Print ("Choose operation:")
Print ("1. Addition (+)")
Print ("2. Subtraction (-)")
Print ("3. Multiplication (*)")
Print ("4. Exponent (**)")
print ("5. Division (/)")
print ("6. Remainder (%)")
print ("7. Float Division (//)")
again = "yes"
while again. lower () == "yes":
choice = input ("\n Enter choice (1/2/3/4/5/6/7): ")
num1 = float (input ("Enter first number: "))
num2 = float (input ("Enter second number: "))
if choice == "1":
print ("Addition is =", num1 + num2)
elif choice == "2":
print ("Subtraction is =", num1 - num2)
elif choice == "3":
print ("Multiplication is =", num1 * num2)
elif choice == "4":
print ("Exponent is =", num1 ** num2)
elif choice == "5":
if num2! = 0:
print ("Division is =", num1 / num2)
else:
print ("Error: Division by zero not allowed!")
elif choice == "6":
print ("Remainder is =", num1 % num2)
elif choice == "7":
print ("Float Division is =", num1 // num2)
else:
print ("Invalid choice. Please select 1, 2, 3, 4, 5, 6 or 7.")
again = input ("\n Do you want to perform another operation? (yes/no): ")
print ("Exiting program.")
2332459 BTCS-513-18
Output:
2332459 BTCS-513-18
Task 3: Write a program to create, concatenate and print a string and accessing substring
from a given string.
Code:
Print ("1. Create a string")
Print ("2. Concatenate a string")
Print ("3. Access a substring")
Print ("4. Delete a string")
s=input ("\n Enter any String: ")
again = "yes"
while again == "yes":
again = input ("\n Do you want to continue? (yes/no): ")
if again! = "yes":
break
choice = input ("Enter a choice (1/2/3/4): ")
if choice == "1":
s1 = input ("Enter the new string: ")
print ("Original string:", s1)
elif choice == "2":
s2 = input ("Enter the string to concatenate: ")
s = s + s2
print ("Concatenated string:", s)
elif choice == "3":
print ("original string:", s)
start = int (input (" write the starting index:"))
end = int (input (" write the ending index:"))
sub1 = s [start: end]
print ("Substring is:", sub1)
elif choice == "4":
s=input ("enter the string:")
del s
print ("String deleted.")
else:
print ("Invalid choice!")
print ("Exiting program.")
2332459 BTCS-513-18
Task 26: Program to find even length words in a string.
Code:
s= input ("Enter the string:")
words = s. split ()
print ("Even length words are:")
for i in words:
if len(i)%2 ==0:
print(i)

Output:
2332459 BTCS-513-18
Task 27: Program to swap all dots and commas in a string.
Code:
S=input ("Enter any String including commas and dots: \n")
S = S. replace ('.', '*')
S = S. replace (',', '.')
S = S. replace ('*', ',')
Print ("Swapped String of dot and commas: \n", S)

Output:
2332459 BTCS-513-18
Task 28: Given a string “F.R.I.E.N.D.S” change the string to “friends”.
Code:
R= "F.R.I.E.N.D. S"
Print ("string is:", R)
R=R. replace (".","")
R=R. lower ()
Print ('After replacing:', R)

Output:
2332459 BTCS-513-18
Task 29: Extract digit string from a given string.
Code:
R= "(1) My name is Simranjot (2) My Roll No. is 1911"
digits= ""
for i in R:
if i. isdigit ():
digits = digits +i
print ("The Digits are found: ", digits)

Output:
2332459 BTCS-513-18
Task 5: Write a program to create, append, and remove lists in python.
Code:
pets = ['cat', 'dog', 'rat', 'pig', 'tiger']
snakes= ['python', 'anaconda', 'fish', 'cobra', 'mamba']
print ("List of Pets are:", pets)
print ("\n List of Snakes are:", snakes)
animals= pets + snakes
print ("\n Animals are (Append the list):", animals)
snakes. remove("fish")
print ("\n Updated list of Snakes are:", snakes)
print ("\n Fish is removed from the list because fish is not Snake.")

Output:
2332459 BTCS-513-18
Task 6: Write a program to demonstrate working with tuples in python.
Code:
T = ("apple", "banana", "cherry", "mango", "grape", "orange")
Print ("\n Created tuple is:", T)
Print ("\n Second fruit is:", T [1])
Print ("\n from 3-6 fruits are:", T [3:6])
Print ("\n List of all items in Tuple:")
for x in T:
print(x)
if "apple" in T:
print ("\n Yes, 'apple' is in the fruits tuple")
print ("Length of Tuple is:", len (T))

Output:
2332459 BTCS-513-18
Task 30: Program for Insertion in a list before any element.
code:
def insert_before (lst, target, new_element):
if target in lst:
index = lst. Index (target)
lst. Insert (index, new_element)
else:
print (f" Element '{target}' not found in the list.")
return lst
my_list = [10, 20, 30, 40]
print ("List = [10, 20, 30, 40]")
updated_list = insert_before (my_list, 30, 25)
print ("The list After the Insertion:", (updated_list))

Output:
2332459 BTCS-513-18
Task 31: Program to remove all duplicates from a list.
Code:
my_list = [1, 2, 2, 3, 4, 4, 5]
print ("List with duplicates:", (my_list))
unique_list = []
seen = set ()

for item in my_list:


if item not in seen:
unique_list. append (item)
seen. add (item)

print ("\n The Duplicates are removed from the list:", (unique_list))

Output:
2332459 BTCS-513-18
Task 32: WAP that creates a list ‘L’ of 10 random integers. Then create ODD and EVEN lists
containing odd and even values respectively from ‘L’.
Code:
import random
L = [random. randint (1, 100) for _ in range (10)]
Print ("Original List L:", L)
ODD = [num for num in L if num % 2! =0]
EVEN = [num for num in L if num % 2 == 0]

Print ("ODD List:", ODD)


Print ("EVEN List:", EVEN)

Output:
2332459 BTCS-513-18
Task 33: Write a program to delete all consonants from string and create a new string.
Code:
input_str = "Hello, World!! Python is fun."
vowels = "aeiouAEIOU"
new_str = ""
for char in input_str:
if not char. isalpha () or char in vowels:
new_str += char
print ("Original String:", input_str)
print ("\n String without consonants:", new_str)

Output:
2332459 BTCS-513-18
Task 34: Write a program that takes your full name as input and displays the abbreviations
of the first and middle names except the last name which is displayed as it is. For
example, if your name is Robin Ramesh Kumar, then the output should be R. R. Kumar.
Code:
full_name = input ("Enter your full name: ")
name_parts = full_name. strip (). Split ()
abbreviation = ""
for part in name_parts [: - 1]:
abbreviation += part [0]. Upper () + "."
abbreviation += name_parts [-1]. Capitalize ()
print ("Abbreviated name:", abbreviation)

Output:
2332459 BTCS-513-18
Task 35: Write a program that reads a string and returns a table of the letters of the alphabet
in alphabetical order which occur in the string together with the number of times each letter
occurs. {USING DICTIONARY} Case should be ignored.
Code:
text = input ("Enter a string: ")
letter_count = {}
for char in text:
if char. isalpha ():
char = char. lower ()
if char in letter_count:
letter_count[char] += 1
else:
letter_count[char] = 1
print ("Letter occurrences:")
for letter, count in letter_count. Items ():
print(f"{letter}: {count}")

Output:
2332459 BTCS-513-18
Task 36: Write a function scalar_mult (s, v) that takes a number, s and a list, v and returns
the scalar multiple of v by s.

scalar_mult (7, [3, 0, 5, 11, 2]


OUTPUT:
[21, 0, 35, 77, 14])

Code:
def scalar_mult (s, v):
return [s * x for x in v]
result = scalar_mult (7, [3, 0, 5, 11, 2])
print(result)

Output:
2332459 BTCS-513-18
Task 37: Given a tuple and a list as input, write a Python program to count the
occurrences of all items of the list in the tuple.
Examples:
Input: tuple = ('a', 'a', 'c', 'b', 'd')
list = ['a', 'b']
Output: a: 2
b:1
Code:
tup = ('a', 'a', 'c', 'b', 'd')
lst = ['a', 'b']

for item in lst:


print(f"{item}: {tup. Count (item)}")

Output:
2332459 BTCS-513-18
th
Task 38: Given a list of words in Python, the task is to remove the N occurrence of the
given word in that list.
List = [“you”,” can”,” do”,” you”]
Word = you, N=2
List = [“you”,” can”,” do”]
Code:
words = ["you", "can", "do", "you"]
word = "you"
n=2
count = 0
for i in range(len(words)):
if words[i] == word:
count += 1
if count == n:
del words[i]
break
print(words)

Output:
2332459 BTCS-513-18
Task 39: Given a string, write a program to mirror the characters. change ‘a’ to ‘z’, ‘b’ to ‘y’,
and so on. (Using Dictionary)
Code:
input_str = "hello Python"
mirror_dict = {}
for i in range (26):
mirror_dict [chr (97 + i)] = chr (122 - i)
mirrored_str = ""
for char in input_str:
if char. lower () in mirror_dict:
mirrored_char = mirror_dict [char. lower ()]
mirrored_str += mirrored_char. upper () if char. isupper () else mirrored_char
else:
mirrored_str += char

print ("The Original String is:", input_str)


print ("\n The Original to Mirrored String:", mirrored_str)

Output:
2332459 BTCS-513-18
Task 40: Merge following two Python dictionaries into one.
dict1 = {'Ten': 10, 'Twenty': 20, 'Thirty': 30}

dict2 = {'Thirty': 30, 'Fourty': 40, 'Fifty': 50}

Code:
dict1 = {'Ten': 10, 'Twenty': 20, 'Thirty': 30}
print ("dict1:", (dict1))
dict2 = {'Thirty': 30, 'Forty': 40, 'Fifty': 50}
print ("dict2:", (dict2))
merged_dict = {**dict1, **dict2}
print ("\n The Merged dictionary is:", (merged_dict))

Output:

You might also like