0% found this document useful (0 votes)
7 views30 pages

Full Computer Science Practical File

The document contains a practical file with various Python programming exercises, including functions for calculating factors, HCF, LCM, Fibonacci series, and prime numbers. It also includes menu-driven programs for arithmetic sequences, series addition, and operations on lists, tuples, and dictionaries. Additionally, it covers concepts such as loops, conditionals, and user-defined functions for different mathematical and data manipulation tasks.

Uploaded by

bludoggo2008
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)
7 views30 pages

Full Computer Science Practical File

The document contains a practical file with various Python programming exercises, including functions for calculating factors, HCF, LCM, Fibonacci series, and prime numbers. It also includes menu-driven programs for arithmetic sequences, series addition, and operations on lists, tuples, and dictionaries. Additionally, it covers concepts such as loops, conditionals, and user-defined functions for different mathematical and data manipulation tasks.

Uploaded by

bludoggo2008
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/ 30

PRACTICAL FILE

PYTHON
1. Factors of a Number (User-Controlled Loop)
---------------------------------------------
def factors(n):
print(f"Factors of {n}: ", end="")
for i in range(1, n+1):
if n % i == 0:
print(i, end=" ")
print()

while True:
num = int(input("Enter a number (0 to stop): "))
if num == 0:
break
factors(num)

2. HCF and LCM of Two Numbers


-----------------------------
def hcf(a, b):
while b:
a, b = b, a % b
return a

def lcm(a, b):


return (a * b) // hcf(a, b)

while True:
x = int(input("Enter first number (0 to stop): "))
if x == 0:
break
y = int(input("Enter second number: "))
print("HCF:", hcf(x, y))
print("LCM:", lcm(x, y))

3. Power (X^N) using loop


-------------------------
while True:
x = float(input("Enter base X (0 to stop): "))
if x == 0:
break
n = int(input("Enter exponent N: "))
result = 1
for _ in range(n):
result *= x
print(f"{x}^{n} = {result}")

4. First 20 Armstrong Numbers


-----------------------------
def is_armstrong(num):
power = len(str(num))
return num == sum(int(d)**power for d in str(num))

count = 0
n=1
while count < 20:
if is_armstrong(n):
print(n, end=" ")
count += 1
n += 1

5. Sum of First N Prime Numbers


-------------------------------
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n**0.5)+1):
if n % i == 0:
return False
return True

N = int(input("Enter N: "))
count = 0
num = 2
total = 0
while count < N:
if is_prime(num):
total += num
count += 1
num += 1
print("Sum:", total)

6. Sum of Composite Numbers 1 to N


----------------------------------
def is_composite(n):
if n < 4:
return False
for i in range(2, int(n**0.5)+1):
if n % i == 0:
return True
return False

N = int(input("Enter N: "))
total = sum(i for i in range(1, N+1) if is_composite(i))
print("Sum of composite numbers:", total)

7. Fibonacci Series (First N Terms)


-----------------------------------
N = int(input("Enter N: "))
a, b = 0, 1
for _ in range(N):
print(a, end=" ")
a, b = b, a + b

8. Menu Driven Arithmetic Sequences


-----------------------------------
def menu_sequence():
print("A. 5,10,15,...")
print("B. 1,6,11,...")
print("C. 10,30,50,...")
choice = input("Enter choice A/B/C: ")
n = int(input("Enter N: "))
if choice == 'A':
for i in range(1, n+1):
print(i*5, end=" ")
elif choice == 'B':
for i in range(n):
print(1 + i*5, end=" ")
elif choice == 'C':
for i in range(n):
print(10 + i*20, end=" ")

menu_sequence()

9. Menu Driven Series Addition


------------------------------
def menu_add_series():
print("A. 2+4+6+...")
print("B. 5+11+17+...")
print("C. 50+150+250+...")
choice = input("Enter choice A/B/C: ")
n = int(input("Enter N: "))
if choice == 'A':
print(sum([2*i for i in range(1, n+1)]))
elif choice == 'B':
print(sum([5 + 6*i for i in range(n)]))
elif choice == 'C':
print(sum([50 + 100*i for i in range(n)]))

menu_add_series()

10. Menu Driven Series with X & Factorials


------------------------------------------
import math

def series_xn(n, x):


return sum([x**i for i in range(1, n+1)])

def series_xn_over_fact(n, x):


return sum([x**i / math.factorial(i) for i in range(1, n+1)])

def series_xodd_over_fact(n, x):


return sum([x**(2*i+1) / math.factorial(2*i+1) for i in range(n)])

n = int(input("Enter N: "))
x = float(input("Enter X: "))

print("A. X + X^2 + X^3 + ...")


print("B. X + X^2/2! + X^3/3! + ...")
print("C. X + X^3/3! + X^5/5! + ...")

ch = input("Choose A/B/C: ")


if ch == 'A':
print(series_xn(n, x))
elif ch == 'B':
print(series_xn_over_fact(n, x))
elif ch == 'C':
print(series_xodd_over_fact(n, x))
11. Menu-Driven Output: Print Pattern from Loop
-----------------------------------------------
for i in range(20, 100, 25):
print(i, end=">>")
12. Nested Loop with Step Pattern
---------------------------------
for C in range(8, 1, -2):
print(C, C+2, sep="*", end="#")

13. Running Sum with Loop


-------------------------
S=0
for P in range(1, 25, 5):
S += P
print(P, end="+")
print("=", S)

14. Loop with Break and Else


----------------------------
for R in range(1, 25, 3):
print(R, end=",")
if R % 5 == 0:
print("Break")
break
else:
print("Terminated")

15. Reverse a Number using While Loop


-------------------------------------
P = 13245
while P > 0:
print(P % 10, end="")
P //= 10
print("END")

16. Print Last 2 Digits Using While


-----------------------------------
P = 13245
while P > 0:
print(P % 100, end="\t")
P //= 100
else:
print("END")

17. Palindrome Check Using Mod and While


----------------------------------------
P = 14235
while P > 0:
print(P % 10, end="")
if P % 7 == 0:
print(end="$")
break
P //= 10
else:
print(end="*")
print("END")

18. Print and Multiply in Loop


------------------------------
S=0
P=1
for C in range(80, 10, -15):
S += C
print(C)
P=P*C
print(P, end="")
print(S)
print(P)

19. Evaluate the Expression


---------------------------
print(23 % 3**2 * 6 // 2 * (5 + 10)) # Output: 315

20. Complex Expression Output


-----------------------------
print(25 + int(24 > 24/2 + 12) - 2**(6-5)) # Output: 24

21. Prime Generator Using Nested Loop


-------------------------------------
N=6
P=2
I=1
while I <= N:
for C in range(2, P//2 + 1):
if P % C == 0:
break
else:
print(P, end=' ')
I += 1
P += 1

22. While vs For, ; vs \, break vs continue, keyword vs identifier


------------------------------------------------------------------
# While loop is condition-based; for loop is iterator-based.
# ';' is used to separate statements; '\' continues the line.
# 'break' exits loop; 'continue' skips to next iteration.
# Keywords are reserved; identifiers are user-defined names.

23. List Operations for E, M, T (Marks)


--------------------------------------
E = [int(input("Eng: ")) for _ in range(5)]
M = [int(input("Maths: ")) for _ in range(5)]
T = [E[i] + M[i] for i in range(5)]

print("E:", E)
print("M:", M)
print("T:", T)
print("Min:", min(E), min(M), min(T))
print("Max:", max(E), max(M), max(T))
print("Avg:", sum(E)/5, sum(M)/5, sum(T)/5)

24. Merge A and B Alternating into C


------------------------------------
A = [10, 20, 30, 40]
B = [35, 25, 15, 45]
C = []
for i in range(len(A)):
C.append(A[i])
C.append(B[i])
print("C:", C)

25. List Functions Add, Display, Reverse, Sums


---------------------------------------------
def AddValues(L):
for _ in range(5):
L.append(int(input("Enter value: ")))

def DispValues(L):
print("Values:", L)

def RevContent(L):
L.reverse()

def AddEven(L):
return sum(x for x in L if x % 2 == 0)
def AddOdd(L):
return sum(x for x in L if x % 2 != 0)

def AddZeroEnd(L):
return sum(x for x in L if x % 10 == 0)

def Show7Ten(L):
print([x for x in L if (x // 10) % 10 == 7])

def Show20_50(L):
print([x for x in L if 20 <= x <= 50])

L = []
AddValues(L)
DispValues(L)
RevContent(L)
DispValues(L)
print("Sum Even:", AddEven(L))
print("Sum Odd:", AddOdd(L))
print("Sum Ending 0:", AddZeroEnd(L))
Show7Ten(L)
Show20_50(L)

26. Swap Adjacent Pairs and Halves


----------------------------------
def SwapPair(L):
for i in range(0, len(L)-1, 2):
L[i], L[i+1] = L[i+1], L[i]

def SwapHalf(L):
half = len(L)//2
L[:half], L[half:] = L[half:], L[:half]

L = []
AddValues(L)
DispValues(L)
SwapPair(L)
DispValues(L)
SwapHalf(L)
DispValues(L)

27. City List Functions


-----------------------
def AddCity(C):
for _ in range(5):
C.append(input("Enter city: "))

def AllUcase(C):
for i in range(len(C)):
C[i] = C[i].upper()

def ShowDisp(C):
print("Cities:", C)

def Arrange(C):
C.sort(reverse=True)

def ShortNameCities(C):
print([city for city in C if len(city) <= 4])

def BigNameCities(C):
print([city for city in C if len(city) > 4])

def CityNameLength(C):
print([len(city) for city in C])

C = []
AddCity(C)
AllUcase(C)
ShowDisp(C)
Arrange(C)
ShortNameCities(C)
BigNameCities(C)
CityNameLength(C)

28. Tuple Operations


--------------------
T = (10, 40, 20, 30, 50, 70)
print("Reversed:", T[::-1])
print("Sum:", sum(T))
print("Min/Max:", min(T), max(T))
print("Adjacent sums:", [T[i]+T[i+1] for i in range(len(T)-1)])

29. Dictionary from Tuple + List


--------------------------------
WD = (1,2,3,4,5,6,7)
WDN = ['SUN','MON','TUE','WED','THU','FRI','SAT']
W = dict(zip(WD, WDN))
print("W:", W)

# Rearranged
WDN2 = ['MON','TUE','WED','THU','FRI','SAT','SUN']
W = dict(zip(WD, WDN2))
print("Updated W:", W)

# Copy to MyDays and OfficeDays


MyDays = {k: W[k] for k in [2,4,7]}
OfficeDays = {k: v for k, v in W.items() if k not in MyDays}
print("MyDays:", MyDays)
print("OfficeDays:", OfficeDays)

30. Check if Color is Traffic Light


-----------------------------------
TL = ('RED', 'YELLOW', 'GREEN')
CL = [input("Enter color: ").upper() for _ in range(10)]

for color in CL:


if color in TL:
print(color, "TRAFFIC LIGHT")
else:
print(color, "NOT TRAFFIC LIGHT")

TM = ('STOP', 'BE READY TO START/STOP', 'GO')


TLM = dict(zip(TL, TM))
print("TLM Dictionary:", TLM)
31. Generate N Prime Numbers in List
------------------------------------
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n**0.5)+1):
if n % i == 0:
return False
return True

N = int(input("Enter N: "))
primes = []
num = 2
while len(primes) < N:
if is_prime(num):
primes.append(num)
num += 1
print("Primes:", primes)

32. Store N Fibonacci Numbers in List


-------------------------------------
N = int(input("Enter N: "))
fib = [0, 1]
for _ in range(2, N):
fib.append(fib[-1] + fib[-2])
print("Fibonacci:", fib[:N])

33. Function: Isprime()


-----------------------
def Isprime(n):
if n < 2:
return 0
for i in range(2, int(n**0.5)+1):
if n % i == 0:
return 0
return 1

for i in range(1, 101):


if Isprime(i):
print(i, end=" ")

34. Div2 and Div3 Function


--------------------------
def Div2(n):
return 1 if n % 2 == 0 else 0

def Div3(n):
return 1 if n % 3 == 0 else 0

NUM = int(input("Enter number: "))


if Div2(NUM) and Div3(NUM):
print("Divisible by 2 and 3")
else:
print("Not divisible")

35. Sum of Series 1! + 2! + ... + N!


-----------------------------------
import math
def Factorial(n):
return math.factorial(n)
N = int(input("Enter N: "))
print("Sum:", sum(Factorial(i) for i in range(1, N+1)))

36. Power(x, y) Function


------------------------
def Power(x, y):
result = 1
for _ in range(y):
result *= x
return result

T = float(input("Enter T: "))
N = int(input("Enter N: "))
print("Series Sum:", sum(Power(T, i) for i in range(1, N+1)))

37. Reverse() for Palindrome Check


----------------------------------
def Reverse(n):
return int(str(n)[::-1])

num = int(input("Enter number: "))


print("Palindrome" if num == Reverse(num) else "Not Palindrome")

38. Sum() of Digits Function


----------------------------
def Sum(n):
return sum(int(d) for d in str(n))

for _ in range(3):
print("Digit Sum:", Sum(int(input("Enter number: "))))

39. Result(): Total and Average


-------------------------------
def Result(eng, phy, chem, math, comp):
total = eng + phy + chem + math + comp
avg = total / 5
return total, avg

marks = [int(input(f"Enter marks for {sub}: ")) for sub in ["English", "Physics", "Chemistry", "Math",
"CompSci"]]
total, avg = Result(*marks)
print("Total:", total, "Average:", avg)

40. HCF of 3 Numbers


--------------------
def HCF(a, b):
while b:
a, b = b, a % b
return a

x, y, z = int(input()), int(input()), int(input())


print("HCF:", HCF(HCF(x, y), z))

41–45: Pattern Problems (Pass N to Function)


-------------------------------------------
def pattern_a(n):
for i in range(n, 0, -1):
print(*range(1, i+1))

def pattern_b(n):
for i in range(n):
print(" "*(n-i-1), *range(1, i+2))

def pattern_c(n):
for i in range(n):
print(str(i+1)*(n-i))

def pattern_d(n):
for i in range(1, n+1):
print("".join(chr(64+j) for j in range(1, i+1)))

def pattern_e(n):
for i in range(n):
print("*" * (2*i+1))

# Call like:
# pattern_a(3), pattern_b(3), etc.

46. Series: X + X^2 + ... + X^N


-------------------------------
def series1(N, X):
return sum([X**i for i in range(1, N+1)])

47. Series: X + X^2/2! + ... + X^N/N!


------------------------------------
def series2(N, U):
import math
return sum([U**i / math.factorial(i) for i in range(1, N+1)])
48. Series: X + 2X + 3X + ... + NX
----------------------------------
def series3(N, X):
return sum([i*X for i in range(1, N+1)])

49. Series: 1 - U^2/2! + U^3/3! - ...


------------------------------------
def series4(N, U):
import math
result = 0
for i in range(1, N+1):
sign = (-1)**(i+1)
result += sign * (U**i / math.factorial(i))
return result

50. Create(): Dict from CONTINENTS


----------------------------------
def Create(L):
D = {}
for name in L:
key = name[0]
D[key] = D.get(key, 0) + len(name.replace(" ", ""))
return D

# Example
L = ["ANTARCTICA","SOUTH AMERICA", "NORTH
AMERICA","ASIA","AFRICA","EUROPE","AUSTRALIA"]
print(Create(L))

51. New(String): First and Last Letter of Each Word


---------------------------------------------------
def New(S):
return [word[0] + word[-1] for word in S.split()]

print(New("Yours was an exemplary performance"))

52. Make(): City → Vowel Count


------------------------------
def Make(Cities):
vowels = 'AEIOUaeiou'
return {city: sum(1 for ch in city if ch in vowels) for city in Cities}

53. SingleIt(): Dict to List


----------------------------
def SingleIt(Students):
L = []
for k, v in Students.items():
L.extend([k, v])
return L

Students = {12:78, 15:82, 17:98, 18:76, 20:68}


print(SingleIt(Students))

54. HighProfits(P): Annual >= 20000


-----------------------------------
def HighProfits(P):
for year, q in P.items():
total = sum(q)
if total >= 20000:
print(f"{year}#{total}")

Profits = {
2020:[5000,3000,4000,7000],
2021:[4000,4000,5000,7000],
2022:[5000,3000,4000,5000],
2023:[4000,5000,6000,7000]
}
HighProfits(Profits)

55. Piglatin Converter


----------------------
def ToPiglatin(W):
return W[1:] + W[0] + 'a'

print(ToPiglatin("hello"))

56. Extract Even & Odd from List


-------------------------------
def Extract(Values):
even = [x for x in Values if x % 2 == 0]
odd = [x for x in Values if x % 2 != 0]
return even, odd

57. Alternate Characters in Two Strings


---------------------------------------
def Alternate(STR):
S1 = STR[::2]
S2 = STR[1::2]
return S1, S2

58. Count Integers and Strings in Tuple


---------------------------------------
def countTypes(tup):
int_count = sum(isinstance(i, int) for i in tup)
str_count = sum(isinstance(i, str) for i in tup)
return int_count, str_count

59. Design(str): Word → Vowel Count


-----------------------------------
def Design(s):
vowels = 'aeiouAEIOU'
return {w: sum(1 for ch in w if ch in vowels) for w in s.split()}
60. Create 'friends.txt' and Write 5 Names
------------------------------------------
with open("friends.txt", "w") as f:
for _ in range(5):
f.write(input("Enter name: ") + "\n")

61. Display Contents of File (Function)


---------------------------------------
def display_file(fname):
with open(fname, "r") as f:
print(f.read())

display_file("friends.txt")

62. Display n Characters of a File


----------------------------------
def display_n_chars(n):
with open("friends.txt", "r") as f:
print(f.read(n))

n = int(input("Enter number of characters: "))


display_n_chars(n)

63. Create 'students.txt' with Input Loop


-----------------------------------------
def create_students():
with open("students.txt", "w") as f:
while True:
name = input("Enter student name (STOP to end): ")
if name.upper() == "STOP":
break
f.write(name + "\n")

create_students()

64. Append More Names to 'students.txt'


---------------------------------------
def append_students():
with open("students.txt", "a") as f:
while True:
name = input("Enter name to add (STOP to end): ")
if name.upper() == "STOP":
break
f.write(name + "\n")

append_students()

65. Count Letters, Digits, Spaces in File


-----------------------------------------
def analyze_file():
with open("students.txt", "r") as f:
text = f.read()
upper = sum(1 for c in text if c.isupper())
lower = sum(1 for c in text if c.islower())
digits = sum(1 for c in text if c.isdigit())
spaces = text.count(" ")
print("Uppercase:", upper)
print("Lowercase:", lower)
print("Digits:", digits)
print("Spaces:", spaces)

analyze_file()

66. Count Vowels in File


------------------------
def count_vowels():
vowels = 'aeiouAEIOU'
with open("students.txt", "r") as f:
print("Vowel count:", sum(1 for c in f.read() if c in vowels))

count_vowels()

67. Copy Alphabets, Digits, Others to Files


-------------------------------------------
def copy():
with open("story.txt", "r") as src, \
open("alpha.txt", "w") as a, \
open("digit.txt", "w") as d, \
open("other.txt", "w") as o:
for ch in src.read():
if ch.isalpha():
a.write(ch)
elif ch.isdigit():
d.write(ch)
else:
o.write(ch)

copy()

68. Count Word 'is' in File


---------------------------
def count_is():
with open("students.txt", "r") as f:
text = f.read()
print("Count of 'is':", text.lower().split().count('is'))

count_is()

69. Count 4-Letter Words


------------------------
def count_4_letter_words():
with open("students.txt", "r") as f:
words = f.read().split()
print("4-letter words:", sum(1 for word in words if len(word) == 4))

count_4_letter_words()

70. Print Words with * from File


--------------------------------
def star_words():
with open("xyz.txt", "r") as f:
for word in f.read().split():
print(word + "*", end=" ")

star_words()

71. Reverse Words Starting with 'I'


-----------------------------------
def display_reverse_i():
with open("story.txt", "r") as f:
words = f.read().split()
for word in words:
if word.startswith('I'):
print(word[::-1])

display_reverse_i()

72. Count User-Entered Word in File


-----------------------------------
def countuser():
word = input("Enter word to count: ").lower()
with open("story.txt", "r") as f:
print("Count:", f.read().lower().split().count(word))

countuser()

73. Reverse Each Line of File


-----------------------------
def reverse_lines():
with open("xyz.txt", "r") as f:
for line in f:
print(line[::-1].strip())

reverse_lines()

74. Print Lines Ending with 'y' or 'Y'


-------------------------------------
def lines_y():
with open("xyz.txt", "r") as f:
for line in f:
if line.rstrip().endswith(('y', 'Y')):
print(line, end="")

lines_y()

75. Count Number of Lines in 'article.txt'


------------------------------------------
def countline():
with open("article.txt", "r") as f:
print("Lines:", sum(1 for _ in f))
countline()

76. Display 5 Letters Starting from 6th


---------------------------------------
def display_part():
with open("friends.txt", "r") as f:
text = f.read()
print(text[5:10])

display_part()

77. Replace 'a' with 'b' in File


-------------------------------
def replace_a_b():
with open("friends.txt", "r") as f:
text = f.read()
text = text.replace('a', 'b')
with open("friends.txt", "w") as f:
f.write(text)

replace_a_b()

78. Toggle Case in File


-----------------------
def toggle_case():
with open("xyz.txt", "r") as f:
text = f.read()
with open("xyz.txt", "w") as f:
f.write(text.swapcase())

toggle_case()

79. Display Alternate Lines


---------------------------
def alt_lines():
with open("xyz.txt", "r") as f:
for idx, line in enumerate(f):
if idx % 2 == 0:
print(line, end="")

alt_lines()

80. Show Words Containing '@cmail'


----------------------------------
def find_emails():
with open("Emails.txt", "r") as f:
words = f.read().split()
for word in words:
if "@cmail" in word:
print(word)

find_emails()

81. Words > 5 Characters


------------------------
def long_words():
with open("Words.txt", "r") as f:
print([w for w in f.read().split() if len(w) > 5])

long_words()

82. Count of 'e' in Each Line


-----------------------------
def COUNT():
with open("Gratitude.txt", "r") as f:
for idx, line in enumerate(f, start=1):
print(f"Line {idx} :", line.count('e') + line.count('E'))

COUNT()

83. Lines Starting with 'I'


---------------------------
def Start_with_I():
with open("Gratitude.txt", "r") as f:
for line in f:
if line.strip().startswith("I"):
print(line.strip())

Start_with_I()

84. Lines Starting with 'You'


-----------------------------
def show_you():
with open("Alpha.txt", "r") as f:
for line in f:
if line.startswith("You"):
print(line, end="")
show_you()

85. Count Vowels in Poem.txt


----------------------------
def vowelCount():
vowels = "aeiouAEIOU"
with open("Poem.txt", "r") as f:
print("Vowels:", sum(1 for ch in f.read() if ch in vowels))

vowelCount()

86. Count Lines Not Starting with Vowel


---------------------------------------
def COUNTLINES():
with open("TESTFILE.TXT", "r") as f:
count = 0
for line in f:
if line[0].lower() not in 'aeiou':
count += 1
print("The number of lines not starting with any vowel –", count)

COUNTLINES()

87. Count E/e and T/t in File


-----------------------------
def ETCount():
with open("TESTFILE.TXT", "r") as f:
text = f.read()
print("E or e:", text.count('e') + text.count('E'))
print("T or t:", text.count('t') + text.count('T'))

ETCount()

88. Count 'Me' and 'My' Words in File


-------------------------------------
def MeMy():
with open("STORY.TXT", "r") as f:
text = f.read().lower().split()
count = sum(1 for w in text if w in ['me', 'my'])
print("Count of Me/My in file:", count)

MeMy()

89. Count 'A/a' and 'M/m' in File


---------------------------------
def AMCount():
with open("STORY.TXT", "r") as f:
text = f.read()
print("A or a:", text.lower().count('a'))
print("M or m:", text.lower().count('m'))

AMCount()

SQL
-- 1. Show all databases
SHOW DATABASES;

-- 2. Create Database
CREATE DATABASE XI;

-- 3. Use Database
USE XI;

-- 4. Show All Tables


SHOW TABLES;

-- 5. Create EMPLOYEE Table


CREATE TABLE EMPLOYEE (
Ecode INT(5) PRIMARY KEY,
Name VARCHAR(20) NOT NULL,
Dept VARCHAR(20) DEFAULT 'HR',
Date_of_birth DATE,
Gender CHAR(1),
Designation VARCHAR(20),
Salary INT(10)
);

-- 6. Show EMPLOYEE Structure


DESC EMPLOYEE;

-- 7. Insert Values
INSERT INTO EMPLOYEE VALUES
(101, 'Sunita', 'Sales', '1995-06-06', 'F', 'Manager', 25000),
(102, 'Neeru', 'Office', '1993-07-05', 'F', 'Clerk', 12000),
(103, 'Raju', 'Purchase', '1994-06-05', 'M', 'Manager', 26000),
(104, 'Neha', 'Sales', '1995-08-08', 'F', 'Accountant', 18000),
(105, 'Nishant', 'Office', '1995-10-08', 'M', 'Clerk', 10000),
(106, 'Vinod', 'Purchase', '1994-12-12', 'M', 'Clerk', 10000);

-- 8. Display All Employees


SELECT * FROM EMPLOYEE;

-- 9. Display Name, Salary, Gender


SELECT Name, Salary, Gender FROM EMPLOYEE;

-- 10. Employees who are Clerk or Manager


SELECT * FROM EMPLOYEE WHERE Designation IN ('Clerk', 'Manager');

-- 11. Add Contact_No Column


ALTER TABLE EMPLOYEE ADD Contact_No VARCHAR(30);

-- 12. Increase Salary of Female Employees by 10%


UPDATE EMPLOYEE SET Salary = Salary * 1.10 WHERE Gender = 'F';

-- 13. Delete Employees with Salary Between 12000–20000


DELETE FROM EMPLOYEE WHERE Salary BETWEEN 12000 AND 20000;

-- 14. Names Starting With N


SELECT Name, Designation FROM EMPLOYEE WHERE Name LIKE 'N%';

-- 15. Employees Sorted by Salary


SELECT * FROM EMPLOYEE ORDER BY Salary;

----------------------------------------------------

-- PRODUCT Table
CREATE TABLE PRODUCT (
P_ID VARCHAR(10) PRIMARY KEY,
PRODUCTNAME VARCHAR(50),
MANUFACTURER VARCHAR(50),
PRICE INT,
QUANTITY INT
);

-- Insert Data
INSERT INTO PRODUCT VALUES
('TP01', 'Talcom Powder', 'Ponds', 40, 50),
('TP02', 'Talcom Powder', 'Johnson', 80, 60),
('FW06', 'FaceWash', 'Lux', 45, 20),
('BS01', 'Bath Soap', 'Patanjali', 55, 40),
('SH06', 'Shampoo', 'Ponds', 120, 10),
('FW12', 'Face Wash', 'Patanjali', 90, 20);

-- Add Amount Column


ALTER TABLE PRODUCT ADD Amount INT;

-- Update Amount = Price * Quantity


UPDATE PRODUCT SET Amount = Price * Quantity;

-- Ascending by Amount
SELECT * FROM PRODUCT ORDER BY Amount;

-- Product, Amount, 10% Discount


SELECT PRODUCTNAME, Amount, Amount*0.1 AS Discount FROM PRODUCT;

-- Increase Price of Lux by 10%


UPDATE PRODUCT SET PRICE = PRICE * 1.10 WHERE MANUFACTURER = 'Lux';

-- Total Manufacturers
SELECT COUNT(DISTINCT MANUFACTURER) FROM PRODUCT;

-- Max and Min Quantities


SELECT MAX(QUANTITY), MIN(QUANTITY) FROM PRODUCT;

-- Manufacturer starting with P


SELECT PRODUCTNAME FROM PRODUCT WHERE MANUFACTURER LIKE 'P%';

-- Manufacturer is Lux or Ponds


SELECT PRODUCTNAME FROM PRODUCT WHERE MANUFACTURER IN ('Lux', 'Ponds');

-- Structure
DESC PRODUCT;

-- Total Amount
SELECT SUM(Amount) FROM PRODUCT;

-- Delete where P_ID ends with 6


DELETE FROM PRODUCT WHERE P_ID LIKE '%6';

----------------------------------------------------

-- TRAINER and COURSE


CREATE TABLE TRAINER (
TID INT PRIMARY KEY,
TNAME VARCHAR(50),
CITY VARCHAR(50),
HIREDATE DATE,
SALARY INT
);

CREATE TABLE COURSE (


CID VARCHAR(10) PRIMARY KEY,
CNAME VARCHAR(50),
FEES INT,
STARTDATE DATE,
TID INT,
FOREIGN KEY (TID) REFERENCES TRAINER(TID)
);

-- Trainer + Course queries


SELECT TNAME, CITY, SALARY FROM TRAINER ORDER BY HIREDATE DESC;

SELECT TNAME, CITY FROM TRAINER WHERE HIREDATE LIKE '2001-12%';

SELECT TNAME, HIREDATE, CNAME, STARTDATE


FROM TRAINER T
JOIN COURSE C ON T.TID = C.TID
WHERE FEES <= 10000;

SELECT CITY, COUNT(*) FROM TRAINER GROUP BY CITY;

UPDATE COURSE SET FEES = FEES * 1.10 WHERE FEES BETWEEN 5000 AND 12000;

SELECT TNAME, HIREDATE, SALARY FROM TRAINER WHERE TNAME LIKE 'M%';

DROP TABLE COURSE;

----------------------------------------------------

-- SUBJECTS and TEACHERS


CREATE TABLE SUBJECTS (
SCode VARCHAR(10) PRIMARY KEY,
Title VARCHAR(50),
Mark_Th INT,
Mark_Pr INT
);

CREATE TABLE TEACHERS (


TCode INT PRIMARY KEY,
Name VARCHAR(50),
SCode VARCHAR(10),
FOREIGN KEY (SCode) REFERENCES SUBJECTS(SCode)
);

-- Practical marks = 0
SELECT Title FROM SUBJECTS WHERE Mark_Pr = 0;

-- Teachers per subject


SELECT SCode, COUNT(*) FROM TEACHERS GROUP BY SCode;

-- Teachers in order of subject code


SELECT Name FROM TEACHERS ORDER BY SCode;

-- Subject details + total marks


SELECT *, (Mark_Th + Mark_Pr) AS Total_Marks FROM SUBJECTS;

-- JOIN teacher name and subject


SELECT T.Name, S.Title
FROM TEACHERS T
JOIN SUBJECTS S ON T.SCode = S.SCode;

----------------------------------------------------

-- TEACHER and STUDENT Tables


CREATE TABLE TEACHER (
Tno INT PRIMARY KEY,
Tname VARCHAR(20) NOT NULL,
Subject VARCHAR(20) DEFAULT 'Science',
Salary INT,
DateOfJoining DATE
);

CREATE TABLE STUDENT (


Rollno INT PRIMARY KEY,
Sname VARCHAR(20) NOT NULL,
Gender CHAR(1) DEFAULT 'F',
Marks INT,
Tno INT,
FOREIGN KEY (Tno) REFERENCES TEACHER(Tno)
);

-- Display Teacher and Student Names


SELECT Tname, Sname FROM TEACHER T JOIN STUDENT S ON T.Tno = S.Tno;

-- Remove students below 33


DELETE FROM STUDENT WHERE Marks < 33;

-- Teachers per subject


SELECT Subject, COUNT(*) FROM TEACHER GROUP BY Subject;

-- Insert Teacher record


INSERT INTO TEACHER VALUES (999, 'Demo Teacher', 'Math', 18000, '2001-01-01');

-- Display all students sorted by marks


SELECT * FROM STUDENT ORDER BY Marks;

----------------------------------------------------

-- FINAL QUERIES
-- Display structure
DESC TEACHER;

-- Display teachers joined 1978-1992


SELECT * FROM TEACHER WHERE DateOfJoining BETWEEN '1978-01-01' AND '1992-11-30';

-- Students in descending AGG


SELECT * FROM STUDENT ORDER BY AGG DESC;

-- Students taught by 101, 203


SELECT NAME, SCODE FROM STUDENT WHERE TCODE IN (101, 203);

-- Income Tax (25%)


SELECT TCODE, TEACHERNAME, BASIC * 0.25 AS TAX FROM TEACHER;

-- Update AGG
UPDATE STUDENT SET AGG = 82 WHERE NAME = 'Ravi Sahai';

-- Delete AGG < 40


DELETE FROM STUDENT WHERE AGG < 40;

-- Change STREAM and BASIC


UPDATE TEACHER SET STREAM = 'Humanities', BASIC = 21000 WHERE TEACHERNAME =
'Ananya Murty';

-- Add GRADE column


ALTER TABLE STUDENT ADD GRADE CHAR(1);

-- Update Grade
UPDATE STUDENT SET GRADE = 'A' WHERE AGG >= 70;
UPDATE STUDENT SET GRADE = 'B' WHERE AGG >= 40 AND AGG < 70;
UPDATE STUDENT SET GRADE = 'C' WHERE AGG < 40;

-- Humanities teachers ascending TCODE


SELECT TCODE, TEACHERNAME FROM TEACHER WHERE STREAM = 'Humanities' ORDER
BY TCODE;

-- Stream-wise, date descending


SELECT NAME, STREAM, DATEOFJOINING FROM TEACHER ORDER BY STREAM,
DATEOFJOINING DESC;

-- Max BASIC per stream


SELECT STREAM, MAX(BASIC) FROM TEACHER GROUP BY STREAM;

-- Grand total & average BASIC


SELECT SUM(BASIC), AVG(BASIC) FROM TEACHER;

-- Min AGG where TCODE > 200


SELECT MIN(AGG) FROM STUDENT WHERE TCODE > 200;

-- Number of Teachers
SELECT COUNT(*) FROM TEACHER;

-- AVG AGG per TCODE


SELECT TCODE, AVG(AGG) FROM STUDENT GROUP BY TCODE;

-- Number of Teachers per Stream


SELECT STREAM, COUNT(*) FROM TEACHER GROUP BY STREAM;

-- All unique STREAMs


SELECT DISTINCT STREAM FROM TEACHER;

-- Increase BASIC where DOJ < 1995


UPDATE TEACHER SET BASIC = BASIC + 1000 WHERE DATEOFJOINING < '1995-02-01';

-- Lowest BASIC where teachers ≥ 2 per stream


SELECT STREAM, MIN(BASIC) FROM TEACHER GROUP BY STREAM HAVING COUNT(*) >=
2;

-- Student names and their TEACHERS


SELECT S.NAME, T.TEACHERNAME
FROM STUDENT S
JOIN TEACHER T ON S.TCODE = T.TCODE;

-- Drop TEACHER Table


DROP TABLE TEACHER;

You might also like