DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY
Name: K.SHYAM
Roll No:2K24CSUN01322
Course: B.TECH CSE CSTI
Subject: Python Programming (CSH108B-T) & (CSH108B-P)
Lab -2: Programming constructs in python -hands-on practice
Learning Outcomes:
To impart understanding of basic programming concepts in
python language.
To enable the student to articulate given program scenario and apply
different programming constructs.
1. basic data types
input:
#Integer
a = 10
print("Integer:", a)
# Float
b = 20.5
print("Float:", b)
# String
c = "Hello, World!"
print("String:", c)
# List
d = [1, 2, 3, 4, 5]
print("List:", d)
# Tuple
e = (1, 2, 3, 4, 5)
print("Tuple:", e)
# Dictionary
f = {"name": "Alice", "age": 25}
print("Dictionary:", f)
output:
2.even or odd
Input:
num = int(input("Enter a number: "))
if num % 2 == 0:
print(f"{num} is even")
else:
print(f"{num} is odd")
output:
3.leap year or not
Input:
year = int(input("Enter a year: "))
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print(f"{year} is a leap year")
else:
print(f"{year} is not a leap year")
output:
4.vowel or constant
Input:
char = input("Enter a character: ").lower()
if char in 'aeiou':
print(f"{char} is a vowel")
else:
print(f"{char} is a consonant")
output:
5.smallest b/w two numbers
Input:
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if num1 < num2:
print(f"{num1} is smaller than {num2}")
else:
print(f"{num2} is smaller than {num1}")
output:
6.factorial of a number
Input:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
num = int(input("Enter a number: "))
print(f"The factorial of {num} is {factorial(num)}")
output:
7.print the pattern
Input:
def print_pattern(n):
for i in range(n):
for j in range(n-i-1):
print(" ", end="")
for j in range(i+1):
print("* ", end="")
print()
n=4
print_pattern(n)
output:
8.program to print this series
Input:
n = int(input("Enter the number of terms: "))
a, b = 1, 1
print(a, b, end=" ")
for i in range(2, n):
c=a+b
print(c, end=" ")
a, b = b, c
print()
output:
9.whether a number is prime or not
Input:
num = int(input("Enter a number: "))
if num > 1:
for i in range(2, int(num/2)+1):
if num % i == 0:
print(f"{num} is not a prime number")
break
else:
print(f"{num} is a prime number")
else:
print(f"{num} is not a prime number")
output:
10.create a calculator
Input:
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
if y != 0:
return x / y
else:
return "Division by zero is not allowed"
print("Select operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
choice = input("Enter choice(1/2/3/4): ")
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '1':
print(f"{num1} + {num2} = {add(num1, num2)}")
elif choice == '2':
print(f"{num1} - {num2} = {subtract(num1, num2)}")
elif choice == '3':
print(f"{num1} * {num2} = {multiply(num1, num2)}")
elif choice == '4':
print(f"{num1} / {num2} = {divide(num1, num2)}")
else:
print("Invalid input")
output:
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY
Course: B.TECH CSE CSTI
Subject: Python Programming (CSH108B-T) & (CSH108B-P)
LAB-3
Course Outcome:
CSW108B.1: To impart understanding of basic programming concepts in python language.
CSW108B.2: To enable the student to articulate given program scenario and apply different
programming constructs.
Learning outcome:
Students will be able to do hands-on practice of Programming constructs in python
Blooms Taxonomy Level: BT1, BT2, BT3
1. Write a python program to swap two numbers using a third
variable CODE:
# Write a python program to swap two numbers using a third
variable a=10
b=3
c=0
print("First number is",a,"Second number
is",b) c=a
a=b
b=c
print("First number is",a,"Second number
is",b) OUTPUT:
2. Write a python program to swap two numbers without using third
variable CODE:
# Write a python program to swap two numbers without using third variable
a=10
b=3
print("First number is",a,"Second number
is",b) a=a+b
b=a-b
a=a-b
print("First number is",a,"Second number
is",b) OUTPUT:
3. Write a python program to read two numbers and find the sum of their
cubes CODE:
# Write a python program to read two numbers and find the sum of their cubes
a=int(input("Enter number 1: "))
b=int(input("Enter number 2:
"))
print("Sum of cubes of",a,"and",b,"is",(a**3)+
(b**3)) OUTPUT:
4. Write a python program to read three numbers and if any two variables are equal, print
that number
CODE:
# Write a python program to read three numbers and if any two variables are equal,
print that number.
num1=int(input("Enter number 1: "))
num2=int(input("Enter number 2: "))
num3=int(input("Enter number 3: "))
if (num1==num2):
print("There is a same value:
",num1) elif (num1==num3):
print("There is a same value:
",num3) elif (num2==num3):
print("There is a same value:
",num2) else:
print("No same values")
OUTPUT:
5. Write a python program to read three numbers and find the smallest among
them CODE:
# Write a python program to read three numbers and find the smallest among them
num1=int(input("Enter number 1: "))
num2=int(input("Enter number 2: "))
num3=int(input("Enter number 3: "))
if (num1<num2) and (num1<num3):
print("Smallest value is: ",num1)
elif (num2<num1) and
(num2<num3): print("Smallest value
is: ",num2)
elif (num3<num2) and
(num3<num1): print("Smallest value
is: ",num3)
else:
print("Error")
OUTPUT:
6. Write a python program to read three numbers and print them in ascending order
(without using sort function)
CODE:
# Write a python program to read three numbers and print them in ascending order (without
using sort function)
num1=int(input("Enter number 1: "))
num2=int(input("Enter number 2: "))
num3=int(input("Enter number 3: "))
if num1 <= num2 and num1 <=
num3:
if num2 <= num3:
print(num1, num2, num3)
else:
print(num1, num3, num2)
elif num2 <= num1 and num2 <=
num3: if num1 <= num3:
print(num2, num1, num3)
else:
print(num2, num3, num1)
else:
if num1 <= num2:
print(num3, num1, num2)
else:
print(num3, num2, num1)
OUTPUT:
7. Write a python program to read radius of a circle and print the
area CODE:
# Write a python program to read radius of a circle and print the area.
radius=int(input("Enter radius: "))
area=3.14*(radius**2)
print(area)
OUTPUT:
8. Write a python program to read a number, if it is an even number , print the square of
that number and if it is odd number print cube of that number
CODE:
# Write a python program to read a number, if it is an even number , print the square of
that number and if it is odd number print cube of that number.
num=int(input("Enter number:
")) if num%2==0:
print(num**2)
elif num%2!=0:
print(num**3)
else:
print("Error")
OUTPUT:
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY
Course: B.TECH CSE CSTI
Subject: Python Programming (CSH108B-T) & (CSH108B-P)
Lab 4
Course Outcome:
CSW108B.1: To impart understanding of basic programming concepts in python language.
CSW108B.2: To enable the student to articulate given program scenario and apply different
programming constructs.
Learning outcome:
Students will be able to do hands-on practice of Strings in Python
Blooms Taxonomy Level: BT1, BT2, BT3
Blooms Taxonomy Level: BT2, BT3
1. WAP to demonstrate Slicing Operations in Strings
CODE:
# WAP to demonstrate Slicing Operations in Strings.
a=[10,20,30,40,50,60,70,80,90,100]
print(a[0:])
print(a[:])
print(a[4:])
print(a[3:7])
a[3:8]=[110]
print(a)
OUTPUT:
2. WAP to demonstrate built in functions of Strings.
CODE:
# WAP to demonstrate built in functions of Strings
text = "Hello, World!"
print("text in all uppercase is",text.upper())
print("text in all lowercase is",text.lower())
print("text in first letter capital is",text.capitalize())
print("text in capital is i.e. first letter of every word capital is",text.title())
print("text is found at",text.find("World"))
print("text in replaced from world to python",text.replace("World", "Python"))
print("text is split by a space character",text.strip())
print("text is split with , character",text.split(","))
print("text is checked to be all digits",text.isdigit())
print("text is checked to be all alphabets",text.isalpha())
print("text is checked to be all digits and alphabets",text.isalnum())
print("text is checked to be all uppercase",text.isupper())
print("text is checked to be all lowercase",text.islower())
print("text is counted for number of characters",len(text))
print("text first character is",text[0])
OUTPUT:
3. WAP to check weather a given string is palindrome or not.
CODE:
# WAP to check weather a given string is palindrome or not.
string = input("Enter a string: ")
if string == string[::-1]:
print("The string is a palindrome.")
else:
print("The string is not a palindrome.")
OUTPUT:
4. WAP to capitalize the first and last character of each word in a string.
CODE:
# Q4. WAP to capitalize the first and last character of each word in a string.
a="Hello, Python"
a=a[0].upper()+a[1:-1].lower()+a[-1].upper()
print(a)
OUTPUT:
5. WAP to accept two strings from the user and display the common words.
CODE:
# WAP to accept two strings from the user and display the common words.
str1 = input("Enter first string: ").split()
str2 = input("Enter second string: ").split()
common_words = [word for word in str1 if word in str2]
print("Common words:", common_words)
OUTPUT:
6. WAP to accept a string and count the frequency of each vowel.
CODE:
string = input("Enter a string: ")
vowels = "aeiou"
a=0
e=0
i=0
o=0
u=0
for char in string.lower():
if char == 'a':
a += 1
elif char == 'e':
e += 1
elif char == 'i':
i += 1
elif char == 'o':
o += 1
elif char == 'u':
u += 1
print("Frequency of vowels:")
print("a:", a)
print("e:", e)
print("i:", i)
print("o:", o)
print("u:", u)
OUTPUT:
7. WAP to display the smallest word from the string.
CODE:
string = input("Enter a string: ")
words = string.split()
smallest_word = words[0]
for word in words:
if len(word) < len(smallest_word):
smallest_word = word
print("The smallest word is:", smallest_word)
OUTPUT:
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY
Course: B.TECH CSE CSTI
Subject: Python Programming (CSH108B-T) & (CSH108B-P)
Lab 5
Course Outcome:
CSW108B.1: To impart understanding of basic programming concepts in python language.
CSW108B.2: To enable the student to articulate given program scenario and apply different
programming constructs.
Learning outcome:
Students will be able to do hands-on practice of Loops and Strings in Python
Blooms Taxonomy Level: BT3
1. WAP to demonstrate while loop with else
statement. CODE:
counter = 0
while counter < 5:
print(f"Counter is at: {counter}")
counter += 1
else:
print("While loop has finished
executing.") OUTPUT:
2. Print 1st 5 even numbers (use break
statement). CODE:
count = 0
num = 2
while True:
print(num)
count += 1
if count == 5:
break
num+=2
OUTPUT:
3. Print 1st 4 even numbers (use continue
statement). CODE:
count = 0
num = 0
while count < 4:
num += 1
if num % 2 !=
0: continue
print(num)
count += 1
OUTPUT:
4. WAP to demonstrate Pass
statements. CODE:
for num in range(1,
6): if num == 3:
pass
else:
print(num)
OUTPUT:
5. Write a Python program to calculate the length of a
string. CODE:
string = "Hello,
World!" length =
len(string)
print("The length of the string is:",
length) OUTPUT:
6. Write a Python program to count the number of characters (character frequency) in a
string.
CODE:
string = "hello"
for char in
string:
print(f"{char}: {string.count(char)}")
OUTPUT:
7. Write a Python program to get a string made of the first 2 and the last 2 chars from a
given a string. If the string length is less than 2, return instead of the empty string.
CODE:
string = "hello"
if len(string) <
2:
result = ""
else:
result = string[:2] + string[-
2:] print(result)
OUTPUT:
8. Write a Python program to get a string from a given string where all occurrences of its
first char have been changed to '$', except the first char itself.
CODE:
string = "restart"
first_char =
string[0]
new_string = first_char + string[1:].replace(first_char, '$')
print(new_string)
OUTPUT:
9. Write a Python program to get a single string from two given strings, separated by a
space and swap the first two characters of each string.
CODE:
string1 = "hello"
string2 = "world"
new_string = string2[:2] + string1[2:] + " " + string1[:2] + string2[2:]
print(new_string)
OUTPUT:
10. Write a Python program to add 'ing' at the end of a given string (length should be at
least 3). If the given string already ends with 'ing' then add 'ly' instead. If the string
length of the given string is less than 3, leave it unchanged.
CODE:
string = "play"
if len(string) >= 3:
if string.endswith("ing"):
string += "ly"
else:
string += "ing"
print(string)
OUTPUT:
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY
Course: B.Tech CSE CSTI
Subject: Python Programming (CSH108B-T) & (CSH108B-P)
Lab 6
Course Outcome:
CSW108B.1: To impart understanding of basic programming concepts in python language.
CSW108B.2: To enable the student to articulate given program scenario and apply different
programming constructs.
Learning outcome:
Students will be able to do hands-on practice of Lists in Python
Blooms Taxonomy Level: BT3
List
1. Write a Python program to sum all the items in a
list. CODE:
numberlist = [1, 2, 3, 4, 5]
total = 0
for num in numberlist:
total += num
print(total)
OUTPUT:
2. Write a Python program to multiplies all the items in a
list. CODE:
numbers = [1, 2, 3, 4, 5]
result = 1
for num in numbers:
result *= num
print(result)
OUTPUT:
3. Write a Python program to get the largest number from a
list CODE:
numbers = [1, 2, 3, 4,
5] largest = numbers[0]
for num in numbers:
if num > largest:
largest =
num
print(largest)
OUTPUT:
4. Write a Python program to get the smallest number from a
list. CODE:
numbers = [1, 2, 3, 4,
5] smallest =
numbers[0] for num in
numbers:
if num <
smallest:
smallest =
num
print(smallest)
OUTPUT:
5. Write a Python program to count the number of strings where the string length is 2
or more and the first and last character are same from a given list of strings
Sample List : ['abc', 'xyz', 'aba',
'1221'] Expected Result : 2
CODE:
strings = ['abc', 'xyz', 'aba',
'1221'] count = 0
for s in strings:
if len(s) >= 2 and s[0] == s[-
1]: count += 1
print(count)
OUTPUT:
6. Write a Python program to get a list, sorted in increasing order by the last element
in each tuple from a given list of non-empty tuples.
Sample List : [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)] Expected Result : [(2, 1), (1, 2), (2, 3),
(4, 4), (2, 5)]
CODE:
tuples = [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]
tuples.sort(key=lambda x: x[-1])
print(tuples)
OUTPUT:
7. Write a Python program to remove duplicates from a
list. CODE:
numbers = [1, 2, 3, 2, 4, 5,
3] unique_numbers = []
for num in numbers:
if num not in unique_numbers:
unique_numbers.append(num)
print(unique_numbers)
OUTPUT:
8. Write a Python program to check a list is empty or
not. CODE:
my_list = []
if not my_list:
print("The list is
empty") else:
print("The list is not
empty") OUTPUT:
9. Write a Python program to clone or copy a
list. CODE:
original_list = [1, 2, 3, 4, 5]
cloned_list = original_list[:]
print(cloned_list)
OUTPUT:
10. Write a Python program to find the list of words that are longer than n from a given list
of words.
CODE:
words = ['apple', 'banana', 'kiwi', 'orange', 'grape']
n=5
long_words = []
for word in words:
if len(word) > n:
long_words.append(word)
print(long_words)
OUTPUT:
11. Write a Python function that takes two lists and returns True if they have at least
one common member.
CODE:
def have_common_member(list1, list2):
for item in list1:
if item in list2:
return True
return False
list1 = [1, 2,
3]
list2 = [3, 4, 5]
print(have_common_member(list1, list2))
OUTPUT:
12. Write a Python program to print a specified list after removing the 0th, 4th and 5th
elements. Sample List : ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow']
Expected Output : ['Green', 'White',
'Black'] CODE:
colors = ['Red', 'Green', 'White', 'Black', 'Pink',
'Yellow'] del colors[5]
del colors[4]
del colors[0]
print(colors)
OUTPUT:
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY
Course: B.Tech CSE CSTI
Subject: Python Programming (CSH108B-T) & (CSH108B-P)
Lab 7
Course Outcome:
CSW108B.1: To impart understanding of basic programming concepts in python language.
CSW108B.2: To enable the student to articulate given program scenario and apply different
programming constructs.
Learning outcome:
Students will be able to do hands-on practice of Tuples in Python
Blooms Taxonomy Level: BT3
Tuples
1. Write a Python program to create a
tuple. CODE:
my_tuple = (1, 2, 3, 4,
5) print(my_tuple)
OUTPUT:
2. Write a Python program to create a tuple with different data
types. CODE:
my_tuple = (1, "Hello", 3.14,
True) print(my_tuple)
OUTPUT:
3. Write a Python program to create a tuple with numbers and print one
item. CODE:
my_tuple = (10, 20, 30, 40,
50) print(my_tuple[2])
OUTPUT:
4. Write a Python program to unpack a tuple in several
variables. CODE:
my_tuple = (10, 20,
30) a, b, c = my_tuple
print(a)
print(b)
print(c)
OUTPUT:
5. Write a Python program to add an item in a
tuple. CODE:
my_tuple = (1, 2, 3)
new_item = 4
my_tuple = my_tuple +
(new_item,) print(my_tuple)
OUTPUT:
6. Write a Python program to convert a tuple to a
string. CODE:
my_tuple = ('H', 'e', 'l', 'l', 'o')
my_string = ''.join(my_tuple)
print(my_string)
OUTPUT:
7. Write a Python program to get the 4th element and 4th element from last of a
tuple CODE:
my_tuple = (10, 20, 30, 40, 50, 60, 70)
fourth_element = my_tuple[3]
fourth_from_last = my_tuple[-4]
print("4th element:",
fourth_element)
print("4th element from last:",
fourth_from_last) OUTPUT:
8. Write a Python program to create the colon of a
tuple. CODE:
my_tuple = (10, 20, 30, 40, 50, 60, 70)
sliced_tuple =
my_tuple[1:5]
print(sliced_tuple)
OUTPUT:
9. Write a Python program to find the repeated items of a
tuple. CODE:
my_tuple = (1, 2, 3, 4, 5, 1, 2, 6, 7, 8, 2)
repeated_items = set(x for x in my_tuple if my_tuple.count(x) >
1) print(repeated_items)
OUTPUT:
10. Write a Python program to check whether an element exists within a
tuple. CODE:
my_tuple = (10, 20, 30, 40, 50)
element = 30
if element in my_tuple:
print("Element exists in the
tuple.")
else:
print("Element does not exist in the
tuple.") OUTPUT:
11. Write a Python program to convert a list to a
tuple. CODE:
my_list = [1, 2, 3, 4, 5]
my_tuple = tuple(my_list)
print(my_tuple)
OUTPUT:
12. Write a Python program to remove an item from a
tuple. CODE:
my_tuple = (10, 20, 30, 40,
50) temp_list = list(my_tuple)
temp_list.remove(30)
my_tuple = tuple(temp_list)
print(my_tuple)
OUTPUT:
13. Write a Python program to slice a
tuple CODE:
my_tuple = (10, 20, 30, 40, 50, 60, 70)
sliced_tuple =
my_tuple[2:5]
print(sliced_tuple)
OUTPUT:
14. Write a Python program to find the index of an item of a
tuple. CODE:
my_tuple = (10, 20, 30, 40, 50)
index_of_item = my_tuple.index(30)
print(index_of_item)
OUTPUT:
15. Write a Python program to find the length of a
tuple. CODE:
my_tuple = (10, 20, 30, 40, 50)
length_of_tuple = len(my_tuple)
print(length_of_tuple)
OUTPUT:
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY
Course: B.Tech CSE CSTI
Subject: CSH109C Python Programming
Lab 8
Course Outcome:
CSW108B.1: To impart understanding of basic programming concepts in python language.
CSW108B.2: To enable the student to articulate given program scenario and apply different
programming constructs.
Learning outcome:
Students will be able to do hands-on practice of Sets in Python
Blooms Taxonomy Level: BT3
Sets
Given
set1 = {10, 20, 30, 40, 50}
set2 = {30, 40, 50, 60, 70}
1. Create a new set of identical items from two sets
CODE:
set1 = {10, 20, 30, 40, 50}
set2 = {30, 40, 50, 60, 70}
identical_items = set1 & set2
print(identical_items)
OUTPUT:
2. Create a new set from unique items from two sets
CODE:
set1 = {10, 20, 30, 40, 50}
set2 = {30, 40, 50, 60, 70}
unique_items = set1 |
set2 print(unique_items)
OUTPUT:
3. Update the first set with items that don’t exist in the second set
CODE:
set1 = {10, 20, 30, 40, 50}
set2 = {30, 40, 50, 60, 70}
set1 -= set2
print(set1)
OUTPUT:
4. Check if two sets have any elements in common. If yes, display the common elements
CODE:
set1 = {10, 20, 30, 40, 50}
set2 = {30, 40, 50, 60, 70}
if not set1.isdisjoint(set2):
common_elements = set1 &
set2
print("Common elements:", common_elements)
OUTPUT:
5. Update set1 by adding items from set2, except common items
CODE:
set1 = {10, 20, 30, 40, 50}
set2 = {30, 40, 50, 60, 70}
set1 ^= set2
print(set1)
OUTPUT: