Rashi FYIT B 093 Python Journal
Rashi FYIT B 093 Python Journal
PRACTICAL 1
Variables
Aim:
Declare Variables and implement Implicit and Explicit
Typecasting, understand errors.
Source Code:
print("IMPLICIT TYPE Casting")
a=19
print(type(a))
b=19.5
print(type(b))
c="raya"
print(type(c))
d=True
print(type(d))
e=3+5j
print(type(e))
print("EXPLICIT TYPE CASTING")
R="21"
print(type(R))
print(chr(89))
J=int(R)
print(type(J))
M=float(R)
print(M)
print(type(M))
Y=str(R)
print(Y)
print(type(Y))
f=3.143
g=int(f)
print(g)
alphabet=ord('Y')
number=ord('1')
print("Ascii Value of Character Y is:" ,alphabet)
print("Ascii Value of character digit 1 is:" ,number)
dec=1921
print("The Value of ",dec, "in other number system")
print(bin(dec),"in binary number")
print(oct(dec),"in octal")
print(hex(dec),"in hexadecimal")
Output;
Conclusion:
The code is executed successfully.
PRACTICAL 2
Conditions
A.
Aim:
Write a Python program that:
a. Declares an int type variable num.
b. Assign a random value to the num between 1-100.
c. Program should check and displays the following messages.
if:
i. The num is an even number
ii. The num is multiple of 4
iii. The num is greater than 50
Source Code:
import random
num = random.randint(1, 100)
print(f"Random number: {num}")
if num % 2 == 0:
print(f"{num} is an even number.")
else:
print(f"{num} is not an even number.")
if num % 4 == 0:
print(f"{num} is a multiple of 4.")
else:
print(f"{num} is not a multiple of 4.")
if num > 50:
print(f"{num} is greater than 50.")
else:
print(f"{num} is not greater than 50.")
Output:
Conclusion:
The code is executed successfully.
B.
Aim:
Write a program in python to find whether a string is
PALINDROME or not.
Source Code:
def is_palindrome(s):
return s == s[::-1]
if is_palindrome(string):
print(f"'{string}' is a palindrome.")
else:
print(f"'{string}' is not a palindrome.")
Output:
Conclusion:
The code is executed successfully.
PRACTICAL 3
Loops
A.
Aim:
Write Processing code that declares an integer variable called
limit and assigns a random value between 1 and 50. Your
program should, then, calculate the sum of all the squares of the
integers from 1 to limit (inclusive) using a loop. The result should
be assigned to a variable named result. Print the value of both
variables limit and result to check the correctness of your
program.
Source Code:
import random
print("Limit:", limit)
print("Sum of squares:", result)
Output:
Conclusion:
The code is executed successfully.
B.
Aim:
A common mathematical problem is to find a solution of arithmetic
series. An arithmetic series is the sum of the terms of an
arithmetic sequence. Write a Python program to find the answer A
of the following arithmetic series.
𝐴=𝑎0+ ∑(𝑎coscos𝑛𝜋𝑥𝐿+𝑏sinsin𝑛𝜋𝑥𝐿)30𝑛=5
Source Code:
import math
a0,a,b,L,n = 7.86,16.67,76.667,99,5
A=0
x=int(input("Enter an positive integer:"))
for n in range(5,31):
A += (a*math.cos((n*math.pi*x)/L)**2 +
b*math.sin((n*math.pi*x)/L)**2)
A += a0
print(A)
Output:
Conclusion:
The code is executed successfully.
C.
Aim:
Write a program to declare an integer type variable number.
Display the cube of all integers from 1 to number. For example, if
a number is 5, then expected output is as:
Number is : 1 and cube of the 1 is :1
Number is : 2 and cube of the 2 is :8
Number is : 3 and cube of the 3 is :27
Number is : 4 and cube of the 4 is :64
Number is : 5 and cube of the 5 is :125
Source Code:
number = int(input("Enter a number: "))
Conclusion:
The code is executed successfully.
D.
Aim:
Trace how many times the statement will be executed in each of
the following the following loops? Afterwards, replace the
statement with println(j) and type the statements to check how
many times the value of the variable j was printed. Note: convert
into python from java.
1.for(int i=1;i<=10;i++)
for (int j = 1; j <= 10; j++)
statement;
2.for(int i=1;i<=10;i++)
for (int j = 1; j <= i; j++)
statement;
3.for(int i=1;i<=5;i++)
for (int j = 10; j > i; j--)
statement
Source Code:
count = 0
for i in range(1, 11):
for j in range(1, 11):
print(j)
count += 1
print("Total executions:", count)
count = 0
for i in range(1, 11):
for j in range(1, i + 1):
print(j)
count += 1
print("Total executions:", count)
count = 0
for i in range(1, 6):
for j in range(10, i, -1):
print(j)
count += 1
print("Total executions:", count)
Output:
Conclusion:
The code is executed successfully.
E.
Aim:
Write a loop that output the following pattern of numbers.
a. 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 6 6 6 6 6 6
b. 1 1 1 1 1 1 2 2 2 2 2 3 3 3 3 4 4 4 5 5 6
c. 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 1 2 3 4 5 6
Source Code:
print("Pattern a:")
for i in range(1, 7):
for j in range(i):
print(i, end=" ")
print()
print("Pattern b:")
for i in range(1, 7):
for j in range(6 - i + 1):
print(i, end=" ")
print()
print("Pattern c:")
for i in range(1, 7):
for j in range(1, i + 1):
print(j, end=" ")
print()
Output:
Conclusion:
The code is executed successfully.
PRACTICAL 4
Functions
A.
Aim:
User Defined function
Write a user defined function when passed a value of type int,
returns true if the value is multiple of 3 and returns false
otherwise. (Multiples of 3 are 3, 6, 9, 12 ……)
Source Code:
def mul_3(n):
return n % 3 == 0
n=int(input("Enter a number: "))
print(mul_3(n))
Output:
Conclusion:
The code is executed successfully.
B.
Aim:
Keyword as Argument
Write a function that when passed an int type number as an
argument, returns the binary equivalent as a string of 0s and 1s.
For example, if we pass the value 13 to that function, should
return “1101”.
Source Code:
def binary(n):
return bin(n)[2:]
n=int(input("Enter a number: "))
print(binary(n))
Output:
Conclusion:
The code is executed successfully.
C.
Aim:
Boolean Function
Write a Boolean function that when passed a number should
return wether true or false after checking if that number is an
“Armstrong” number or not. An integer number is called
Armstrong number if sum of the cubes of its digits is equal to the
number itself. For example, 371 is an Armstrong number since
3*3*3 + 7*7*7 + 1*1*1 = 371.
Note: 153, 370, 371, 407 are all Armstrong numbers. You can use
these values to check correctness of your function.
Source Code:
def armst(n):
return n==sum(int(digit)**3 for digit in str(n))
n=int(input("Enter a number: "))
print(armst(n))
Output:
Conclusion:
The code is executed successfully.
D.
Aim:
Recursive Function
Write a Python Recursive function to calculate the factorial of a
number (a non-negative integer). The function accepts the
number as an argument
Source Code:
def fact(n):
if n==0:
return 1
return n*fact(n-1)
n=int(input("Enter a number: "))
print(fact(n))
Output:
Conclusion:
The code is executed successfully.
PRACTICAL 5
Strings
A.
Aim:
Write a program that declares a String variable called name and
initializes it with your full name. Print the value of that variable in
reverse order using a loop.
Source Code:
Conclusion:
The code is executed successfully.
B.
Aim:
Write a program to count the total number of words in a String.
For example, the string “Welcome to SOMAIYA” has 3 words.
Source Code:
text="Welcome to Somaiya"
words=len(text.split())
print("Total no. of words are",words)
Output:
Conclusion:
The code is executed successfully.
C.
Aim:
Write a program that declares a String variable called password
and initializes it with some value. The program should then check
if the password meets the following criteria or not. The program
should print an error message if the password does not meet the
criteria.
Criteria-
i. The length of password should be at least 8 characters
ii. The password should have at least 1 digit
iii. The password should have at least 1 capital letter.
Source Code:
def check_pass(password):
if len(password) < 8:
print("Error! Password must be at least 8 characters long.")
return False
if not any(char.isdigit() for char in password):
print("Error! Password must contain at least one digit.")
return False
if not any(char.isupper() for char in password):
print("Error! Password must contain at least one uppercase
letter.")
return False
print("Password is valid")
return True
password = "Rashi@8905"
check_pass(password)
Output:
Conclusion:
The code is executed successfully.
D.
Aim:
Compute a function palindrome that when passed a String value
returns true if the value is palindrome and false otherwise.
Source Code:
def palindrome(s):
return s == s[::-1]
print(palindrome("racecar"))
print(palindrome("hello"))
Output:
Conclusion:
The code is executed successfully.
PRACTICAL 6
Lists
A.
Aim:
The following java code assigns random values (0-10) to each
element of array “myArray”.
int[] myArray = new int[8];
for(int i = 0; i < myArray.length; i++) {
myArray[i] = (int)random(11);
}
Convert the above base code into python and write a piece of
code in python that computes, and display the
following on screen.
i. Print the values of each element in myArray ii.
The total of all items in myArray
iii. The number of items in myArray that are greater than 5
iv. The maximum value in array myArray
Source Code:
import random
Conclusion:
The code is executed successfully.
B.
Aim:
The following java program declares an int array with 10elements,
each initialized to a random value between (0-30).
int[] arr = new int[10];
for (int i=0; i< arr.length; i++) {
arr[i] = (int)random(31);
print(arr[i]+" ");
}
Convert the above base code in Python and write a program to
sort elements of this array in ascending order.
Source Code:
import random
arr.sort()
print("Sorted array:", arr)
Output:
Conclusion:
The code is executed successfully.
C.
Aim:
Write a program to remove duplicate items from a list.
Source Code:
num=(1,2,2,3,4,4,5)
print(set(num))
Output:
Conclusion:
The code is executed successfully.
D.
Aim:
Write a program to find common items in 2 lists.
Source Code:
num1=(1,2,3,4,5)
num2=(3,4,5,6,7)
print(set(num1) & set(num2))
Output:
Conclusion:
The code is executed successfully.
PRACTICAL 7
A.
Aim:
Create and perform the following -
1.An empty tuple
2.Tuple with integers
3.Tuple with mixed data types
4.Nested tuple.
5.Using a while loop print the middle element of the tuple
created in 3.
Source Code:
empty_tuple=()
print(empty_tuple)
int_tuple=(1,2,3)
print(int_tuple)
mixed_tuple=(1,"Hello",3.14,True)
print(mixed_tuple)
nested_tuple=((1,2,3),("A","B","C"))
print(nested_tuple)
index=len(mixed_tuple)//2
print("Middle Element:",mixed_tuple[index])
Output:
Conclusion:
The code is executed successfully.
B.
Aim:
Join 2 tuples after creation. Find the first and last element of the
joined tuple. Swap the elements. Perform slicing between 2nd to
2nd last elements.
Source Code:
tuple1=(1,2,3)
tuple2=("a","b","c")
joined_tuple=tuple1+tuple2
print("Joined Tuple:",joined_tuple)
first_element=joined_tuple[0]
last_element=joined_tuple[-1]
print(first_element)
print(last_element)
swapped_tuple=(last_element,)+joined_tuple[1:-1]+(first_element,
)
print("Swapped Tuple:",swapped_tuple)
sliced_tuple=joined_tuple[1:-1]
print("Sliced Tuple:",sliced_tuple)
Output:
Conclusion:
The code is executed successfully.
C.
Aim:
Create a dictionary named dict-
1.Using a for loop print all the key values one by one.
2.Using a while loop print all values in dict.
3.Make 3 more dictionaries inside dict named as dict1,
dict2, dict3; add values to it.
4.Remove the last inserted key value pair.
5.Copy the dict to a dictionary named ditto.
Source Code:
dict_={"Name":"Rashi","Age":19,"Gender":"Female"}
print("Keys in dictionary:")
for key in dict_:
print(key)
print("Values in dictionary:")
values=list(dict_.values())
i=0
while i<len(values):
print(values[i])
i+=1
dict_["dict1"]={"a":1,"b":2}
dict_["dict2"]={"x":10,"y":20}
dict_["dict3"]={"p":"Hello","q":"World"}
dict_.popitem()
print(dict_)
ditto=dict_.copy()
print(ditto)
Output:
Conclusion:
The code is executed successfully.
D.
Aim:
Create a dictionary named Batch having the names as keys and
Number of practical attended as value, of the students of this
Batch of SYIT. Make a list of defaulters named default; for the
students who have attended 3 or less practicals. Total number of
practicals conducted are 6.
Source Code:
batch={"Rashi":6,"Yashraj":1,"Raya":2}
default=[name for name,attend in batch.items() if attend<=3]
print(default)
Output:
Conclusion:
The code is executed successfully.
PRACTICAL 8
File Handling
A.
Aim:
Create a file named ‘py.txt’ and write the various file handling
methods in it such as- x, a, r, w, r+, w+, a+, rb, rb+, wb, wb+, ab,
ab+ ; as content to this file. Now perform all these operations on
the file py.txt and print the various outputs.
Source Code:
Output:
Conclusion:
The code is executed successfully.
B.
Aim:
Write on the file above using with() function. Use a for loop to print
each line in py.txt. Now split the content of the file using split()
function and print the output.
Source Code:
with open("py.txt","w") as f:
f.write("x, a, r, w, r+, w+, a+, rb, rb+, wb, wb+, ab, ab+ \n This
is a Second line")
print("Reading each line:")
with open("py.txt", "r") as f:
for line in f:
print(line.strip())
with open("py.txt", "r") as f:
content=f.read()
words=content.split()
print("\nSplitting File Content")
print(words)
Output:
Conclusion:
The code is executed successfully.
PRACTICAL 9
A.
Aim:
Create a Class named Person, use the __init__() function to
assign values for name, age and gender Create an object and
print the values.
Source Code:
class Person:
def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
def display_info(self):
print("My name is", self.name)
print("My age is", self.age)
print("My gender is", self.gender)
obj = Person("Rashi", 19, "Female")
obj.display_info()
Output:
Conclusion:
The code is executed successfully.
B.
Aim:
Create a Child Class Student of the above Class Person which
will inherit it's properties and methods. Use __init__ () function
and add a few properties and methods such as fname and lname
to Student Class. Check if the Child Class function overrides the
function of Parent Class Person. If this happens then add a call to
the parent's __init__() function OR use the super() function for the
same task.
Source Code:
class Person:
def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
def display_info(self):
print("My name is", self.name)
print("My age is", self.age)
print("My gender is", self.gender)
class Student(Person):
def __init__(self, name, age, gender, fname, lname):
super().__init__(name, age, gender)
self.fname = fname
self.lname = lname
def display_student_info(self):
self.display_info()
print("My First name is", self.fname)
print("My Last name is", self.lname)
obj.display_student_info()
Output:
Conclusion:
The code is executed successfully.
PRACTICAL 10
Regular Expressions
A.
Aim:
Add a property graduationyear to the student class using self and
pass a value 2023 to it. Add a method called welcome() to the
student class, which prints ( "Welcome", fname, lname, "to the
class of" , graduationyear )
Source Code:
class Student:
def __init__(self, fname, lname, graduation_year=2023):
self.fname = fname
self.lname = lname
self.graduation_year = graduation_year
def welcome(self):
print("Welcome", self.fname, self.lname, "to the class of",
self.graduation_year)
Conclusion:
The code is executed successfully.
B.
Aim:
Import re, Use RegEx methods findall(), search() or match() to
check and print if the fname ot lname has 'a' in it, also check if
graduationyear has '0' in it.
Source Code:
import re
class Student:
def __init__(self, fname, lname, graduation_year=2023):
self.fname = fname
self.lname = lname
self.graduation_year = str(graduation_year)
def check_name(self):
if re.search(r"a",self.fname,re.IGNORECASE) or
re.search(r"a",self.lname,re.IGNORECASE):
print("The name contains the letter 'a'")
else:
print("The name does not contain the letter 'a'")
def check_num(self):
if re.findall(r"0",self.graduation_year):
print("The graduation year contains the digit '0'")
else:
print("The graduation year does not contain the digit
'0'")
def welcome(self):
print("Welcome", self.fname, self.lname, "to the class of",
self.graduation_year)
student1=Student("Rashi","Sawardekar")
student1.welcome()
student1.check_name()
student1.check_num()
Output:
Conclusion:
The code is executed successfully.
PRACTICAL 11
Aim:
Create an admission form to display all the elements of tkinter
module, validate the user input (password and username through
a textbox)
Source Code:
import tkinter as tk
from tkinter import messagebox
def validate_login():
username = user_entry.get()
password = pass_entry.get()
if username == "admin" and password == "1234":
messagebox.showinfo("Login", "Login successful,
Welcome to the Admission System")
else:
messagebox.showerror("Login", "Invalid username or
password")
pl=tk.Tk()
pl.title("Admission Page")
pl.geometry("300x200")
user_label=tk.Label(pl,text="username:")
user_label.grid(row=0,column=0,pady=10,padx=5)
user_entry=tk.Entry(pl)
user_entry.grid(row=0,column=1)
pass_label=tk.Label(pl,text="Password:")
pass_label.grid(row=1,column=0,pady=10,padx=5)
pass_entry=tk.Entry(pl,show="*")
pass_entry.grid(row=1,column=1)
btn=tk.Button(pl,text="Login",command=validate_login)
btn.grid(row=2,column=0,columnspan=2,pady=10)
pl.mainloop()
Output:
Conclusion:
The code is executed successfully.
PRACTICAL 12
Aim:
Using a connector of MySql establish a database connection
and using cursor Create, Update, and Delete database entries for
Student_id, name, class, year, CGPA, gender.
Source Code:
import mysql.connector
conn = mysql.connector.connect(
host='localhost',
user='root',
password='yashraj@123',
database='testdb'
)
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS students (
student_id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(250),
student_class VARCHAR(250),
year INT,
CGPA FLOAT,
gender VARCHAR(25)
)
""")
conn.commit()
print("Table 'students' is ready.")
def delete_student(student_id):
cursor.execute("DELETE FROM students WHERE
student_id = %s", (student_id,))
conn.commit()
print(f" Student Record Deleted! ID: {student_id}")
def fetch_students():
cursor.execute("SELECT * FROM students")
students = cursor.fetchall()
print("\n Student Records:")
for student in students:
print(student)
update_student(2, 9.85)
delete_student(1)
delete_student(3)
fetch_students()
cursor.close()
conn.close()
print("Database Connection Closed.")
Output:
Conclusion:
The code is executed successfully.