Name :- Shrey Chaudhary
Roll no :- 2K23CSUN01117
Subject-Python Programming
PYTHON LAB FILE
Basic Programs
Even or Odd:
num = int(input("Enter a number: "))
if num % 2 == 0:
print("Even")
else:
print("Odd")
Largest of Three Numbers:
a, b, c = map(int, input().split())
print(max(a, b, c))
Factorial using Recursion:
def factorial(n):
if n == 0:
return 1
return n * factorial(n-1)
Reverse a String:
s = input("Enter string: ")
print(s[::-1])
Loops & Logic
Fibonacci Sequence:
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
print(a, end=' ')
a, b = b, a + b
Prime Check:
num = int(input("Enter number: "))
if num > 1:
for i in range(2, num):
if num % i == 0:
print("Not Prime")
break
else:
print("Prime")
else:
print("Not Prime")
Count Vowels:
s = input("Enter string: ")
vowels = "aeiouAEIOU"
count = sum(1 for char in s if char in vowels)
print(count)
Data Structures
Remove Duplicates from List:
my_list = [1,2,2,3,4,4]
print(list(set(my_list)))
Frequency of Elements:
from collections import Counter
print(dict(Counter([1,2,2,3,3,3])))
Functions
Check Palindrome Number:
def is_palindrome(n):
return str(n) == str(n)[::-1]
Recursive Power:
def power(x, y):
if y == 0:
return 1
return x * power(x, y - 1)
Strings
String Palindrome:
s = input()
print("Palindrome" if s == s[::-1] else "Not Palindrome")
Character Frequency:
from collections import Counter
s = input()
print(dict(Counter(s)))
List-Based Programs
Largest in List:
print(max([1, 2, 3, 4]))
Remove Duplicates:
print(list(set([1,2,2,3])))
Count Even/Odd:
lst = [1,2,3,4]
even = sum(1 for x in lst if x%2==0)
odd = len(lst) - even
print("Even:", even, "Odd:", odd)
Sort List:
lst = [3,1,2]
lst.sort()
print(lst)
Remove Negative:
print([x for x in [-1,2,-3,4] if x >= 0])
Second Largest:
lst = [10, 20, 4, 45, 99]
lst = list(set(lst))
lst.sort()
print(lst[-2])
Sum and Average:
lst = [1,2,3,4]
total = sum(lst)
print("Sum:", total, "Avg:", total/len(lst))
Tuple-Based Programs
Create and Print Tuple:
t = (1,2,3)
print(t)
Find Index:
t = (1,2,3)
print(t.index(2))
Count Occurrences:
t = (1,2,2,3)
print(t.count(2))
List to Tuple:
print(tuple([1,2,3]))
Element Exists:
print(2 in (1,2,3))
Length:
print(len((1,2,3)))
Max and Min:
t = (1,5,3)
print(max(t), min(t))
Sum of Tuple:
print(sum((1,2,3)))
Iterate Through Tuple:
t = (1,2,3)
for i in t:
print(i)
Concatenate Tuples:
t1 = (1,2)
t2 = (3,4)
print(t1 + t2)
Dictionary-Based Programs
Create and Display Dictionary:
d = {"a":1, "b":2}
print(d)
Frequency of Characters:
from collections import Counter
s = "hello"
print(dict(Counter(s)))
Remove Key:
d = {"a":1, "b":2}
d.pop("a")
print(d)
Check Key Exists:
d = {"a":1, "b":2}
print("a" in d)
Update Key Value:
d = {"a":1}
d["a"] = 10
print(d)
Count Keys:
d = {"a":1, "b":2}
print(len(d))