











Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Community
Ask the community for help and clear up your study doubts
Discover the best universities in your country according to Docsity users
Free resources
Download our free guides on studying techniques, anxiety management strategies, and thesis advice from Docsity tutors
Python practical for practice. Help to clear external practical examPython practical for practice. Help to clear external practical examPython practical for practice. Help to clear external practical examPython practical for practice. Help to clear external practical examPython practical for practice. Help to clear external practical exam
Typology: Cheat Sheet
1 / 19
This page cannot be seen from the preview
Don't miss anything!
2. a. Practical to based on Strings, Putting Two Strings Together, Joining Strings with the Print() Function, Putting Strings Together in Different Ways. #Putting Two Strings Together string1 = "Hello" string2 = "World" result = string1 + " " + string print(result) #Joining Strings with the Print() Function words = ["Hello", "World"] result = " ".join(words) print(result) #Putting Strings Together in Different Ways name = "Navin" age = 22 message = f"My name is {name} and I am {age} years old." print(message) #Repeat String text = "Python" repeated_text = text * 3 print(repeated_text) #use f-strings to embed variables name = "Navin" age = 22 message = f"My name is {name} and I am {age} years old." print(message) 2.b. Practical based on Simple statements using Variables, Built-in Data Types, Arithmetic operations #Built-in Data Types name = "Alice" # String age = 25 # Integer height = 5.8 # Float is_student = True # Boolean print(name) print(age) print(height) print(is_student) #Arithmetic Operations num1 = 10 num2 = 5 sum_result = num1 + num difference_result = num1 - num product_result = num1 * num division_result = num1 / num print("Sum:", sum_result) print("Difference:", difference_result)
print("Product:", product_result) print("Division:", division_result)
3. Variables, Tuples, Lists and Dictionaries a. Practical based on using Tuples, Lists, Dictionaries. #simple tuple thistuple = ("apple", "banana", "cherry", "apple", "cherry") print(thistuple) print(thistuple[0]) print(thistuple[1]) print(thistuple[2]) #length thistuple = ("apple", "banana", "cherry") print(len(thistuple)) #simple List thislist = ["apple", "banana", "cherry"] print(thislist) print(thislist[0]) print(thislist[1]) print(thislist[2]) #list length thislist = ["apple", "banana", "cherry"] print(len(thislist)) #Dictionaries thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } print(thisdict) 4. Making Decisions a. Programs based on decision and looping statements, for statement and the range function; interactively using the built-in functions len, sum, max, min. #MAX and MIN numbers = [34, 12, 89, 56, 21] maximum = max(numbers) minimum = min(numbers) print("Maximum value:", maximum) print("Minimum value:", minimum) #len user_input = input("Enter a word or phrase: ") length = len(user_input) print(f"The input has {length} characters.")
6. Classes and Objects a. Program to demonstrate Defining a Class and Object. class Dog: attr1 = "mammal" attr2 = "dog" def fun(self): print("I'm a", self.attr1) print("I'm a", self.attr2) Rodger = Dog() print(Rodger.attr1) Rodger.fun() 7. Organizing Programs a. Practical to Create, Import and use Package and Modules. #math_operations.py def add(a, b): return a + b def subtract(a, b): return a – b
defconcatenate_strings(str1, str2): return str1 + str defcapitalize_string(s): returns.capitalize() #main.py frommy_package import math_operations, string_operations result1 = math_operations.add(5, 3) result2 = math_operations.subtract(10, 4) result3 = string_operations.concatenate_strings("Hello, ", "World!") result4 = string_operations.capitalize_string("python") print("Addition:", result1) print("Subtraction:", result2) print("Concatenation:", result3) print("Capitalization:", result4) **8. Files and Directories a. Program to Writing Text Files, Appending Text to a File, Reading Text Files.
with open("example.txt", "w") as file: file.write("This is the first line.\n") file.write("This is the second line.\n") print("Text written to file.") # Appending Text to a File with open("example.txt", "a") as file: file.write("This is appended text.\n") print("Text appended to file.")
#Reading Text Files with open("example.txt", "r") as file: content = file.read() print("File content:") print(content) 8.b. Program to demonstrate Paths and Directories, File Information, Renaming, Moving, Copying, and Removing Files. Import os import shutil # Create a directory and a file os.mkdir("example_directory") with open("example_directory/example_file.txt", "w") as file: file.write("This is a sample file.") # Get the current working directory current_dir = os.getcwd() print(f"Current directory: {current_dir}") # List the files and directories in the current directory contents = os.listdir(current_dir) print(f"Contents of the current directory: {contents}") # Retrieve file information file_path = "example_directory/example_file.txt" file_size = os.path.getsize(file_path) file_mtime = os.path.getmtime(file_path) print(f"File size: {file_size} bytes") print(f"Last modified time: {file_mtime}") # Rename a file new_file_path = "example_directory/renamed_file.txt" os.rename(file_path, new_file_path) # Move a file to a different directory destination_path = "moved_directory/renamed_file.txt" os.mkdir("moved_directory") shutil.move(new_file_path, destination_path) # Copy a file to another directory copied_file_path = "moved_directory/copied_file.txt" shutil.copy(destination_path, copied_file_path) # Remove a file os.remove(copied_file_path) # Remove a directory and its contents
# Define the expected options and their possible arguments opts, args = getopt.getopt(argv, "hi:o:") except getopt.GetoptError: # Handle errors if there are any invalid options or missing arguments print("Usage: basic_example.py -i
print("Usage: basic_example.py -i
10. Building a Module
a. Practical based on Creating Modules and Packages. #math_operations.py def add(a, b): return a + b def subtract(a, b): return a – b
def concatenate_strings(str1, str2): return str1 + str defcapitalize_string(s): returns.capitalize() #main.py frommy_package import math_operations, string_operations result1 = math_operations.add(5, 3) result2 = math_operations.subtract(10, 4) result3 = string_operations.concatenate_strings("Hello, ", "World!") result4 = string_operations.capitalize_string("python") print("Addition:", result1) print("Subtraction:", result2) print("Concatenation:", result3) print("Capitalization:", result4) 10.b. Program based on Creating Classes, Extending Existing Classes. class Animal: def init(self, name, species): self.name = name self.species = species def speak(self): print(f"{self.name} makes a sound.") class Dog(Animal): def init(self, name, breed): super().init(name, species="Dog") self.breed = breed def speak(self): print(f"{self.name} barks.") class Cat(Animal): def init(self, name, color): super().init(name, species="Cat") self.color = color def speak(self): print(f"{self.name} meows.") dog = Dog("Buddy", "Golden Retriever") cat = Cat("Whiskers", "Gray")
label.pack() root.mainloop() 12.b. Programs Creating Layouts, Packing Order, Controlling Widget Appearances. import tkinter as tk # Create a new Tkinter window window = tk.Tk() window.geometry("400x300") window.title("GUI Widgets Example") # Create and configure a Label widget label = tk.Label(window, text="Hello, Tkinter!") label.pack() # Add the widget to the window # Create and configure an Entry widget entry = tk.Entry(window) entry.insert(0, "Default Text") entry.pack() # Create and configure a Button widget with a callback function defbutton_click(): user_text = entry.get() label.config(text=f"Hello, {user_text}!") button = tk.Button(window, text="Greet", command=button_click) button.pack() # Create and configure a Checkbutton widget check_var = tk.BooleanVar() checkbutton = tk.Checkbutton(window, text="Check me", variable=check_var) checkbutton.pack() # Create and configure a Radiobutton widget radio_var = tk.StringVar() radio_var.set("Option 1") # Default selection radio1 = tk.Radiobutton(window, text="Option 1", variable=radio_var, value="Option 1") radio2 = tk.Radiobutton(window, text="Option 2", variable=radio_var, value="Option 2") radio1.pack() radio2.pack() # Create and configure a Listbox widget listbox = tk.Listbox(window) for item in ["Item 1", "Item 2", "Item 3"]: listbox.insert(tk.END, item) listbox.pack() # Create and configure a Scale widget scale = tk.Scale(window, from_=0, to=100, orient="horizontal")
scale.pack() # Create and configure a Spinbox widget spinbox = tk.Spinbox(window, from_=0, to=10) spinbox.pack() # Start the main GUI loop window.mainloop()
13. Accessing Databases a. Practical based on using DBM - Creating Persistent Dictionaries and Accessing Persistent Dictionaries. #Creating a Persistent Dictionary: import dbm
with dbm.open("my_dbm.db", "c") as db: # Add key-value pairs to the persistent dictionary db[b'apple'] = b'red' db[b'banana'] = b'yellow' db[b'cherry'] = b'red' print("Database created and data added.") #Accessing the Persistent Dictionary: import dbm
with dbm.open("my_dbm.db", "r") as db: # Access and print values by key print("Color of apple:", db[b'apple'].decode()) print("Color of banana:", db[b'banana'].decode()) print("Color of cherry:", db[b'cherry'].decode()) **OUTPUT:
# Create a connection to a SQLite database (or create it if it doesn't exist) connection = sqlite3.connect("my_database.db") # Create a cursor object for executing SQL statements cursor = connection.cursor() # Begin a transaction cursor.execute("BEGIN") # Insert data into the 'students' table within a transaction cursor.execute("INSERT INTO students (name, age) VALUES (?, ?)", ('Alice', 25)) cursor.execute("INSERT INTO students (name, age) VALUES (?, ?)", ('Bob', 30)) # Commit the transaction to save the changes connection.commit() # Close the connection connection.close() print("Data inserted into the 'students' table within a transaction.") OUTPUT:
14. Using Python for XML 14.a. Program to demonstrate processing XML document, using XML Libraries. import xml.etree.ElementTree as ET # Sample XML data as a string xml_data = '''
for person in root.findall('person'): name = person.find('name').text age = person.find('age').text print(f"Name: {name}, Age: {age}")
14.b. Program to demonstrate HTML Parsing. from html.parser import HTMLParser class Parser(HTMLParser):
defhandle_starttag(self, tag, attrs): global start_tags start_tags.append(tag)
defhandle_endtag(self, tag): global end_tags end_tags.append(tag)
defhandle_data(self, data): global all_data all_data.append(data)
defhandle_comment(self, data): global comments comments.append(data) start_tags = [] end_tags = [] all_data = [] comments = []
parser = Parser()
parser.feed('
' 'I love Tea.
<' '/body>') print("start tags:", start_tags) print("end tags:", end_tags) print("data:", all_data) print("comments", comments) Practical Name : Python Program To Swap Two Variable Using Temp Variable x= y= temp=x x=y y=temp print("the value of x after swapping : {}".format(x)) print("the value of y after swapping : {}".format(y)) Python Program to swap two variable without using temp variable x= y= x,y=y,xif p==1: print("\n" +str(n)+ " is not a Prime Number") else: print("\n" +str(n)+ " is a Prime Number") Practical Name :Python Program Based on List(even , odd) numlist = list() evenlist = list() oddlist = list() for i in range(0,10): n=int(input("enter the numbers")) numlist.append(n) print(numlist) for j in range(0,10): if numlist[j] % 2 == 0: evenlist.append(numlist[j]) else: oddlist.append(numlist[j]) print("The Original numbers are: ",numlist) print("The Even numbers are: ",evenlist) print("The Odd numbers are: ",oddlist) Pratical Name: Factorial Number ( In Range ) n=int(input("enter the number: ")) fact= if n <0 : print("enter positive number") elif n==1: print("factorial is 1") else: for i in range(1,n+1): fact=fact*i print("factorial of given number is :",fact) Pratical Name: Write A Python Program To Demonstrate Given Number Is Even Or Odd num=int(input("enter the number")) if(num%2)==0: print("the number is even") else: print("the number is odd") PraticalName :PracticalBased On Simple Statements Using Variables, Built-In Data Types, Arithmetic Operations, Etc. num1 = input("enter first number") num2 = input("enter second number") sum = float(num1) + float(num2) min = float(num1) - float(num2) mul = float(num1) * float(num2) div = float(num1) / float(num2) print("the sum of {0} and {1} is {2}".format(num1,num2,sum));
print("the substraction of {0} and {1} is {2}".format(num1,num2,min)); print("the multiplication of {0} and {1} is {2}".format(num1,num2,mul)); print("the division of {0} and {1} is {2}".format(num1,num2,div)); *Db. import sqlite conn = sqlite3.connect('test.db') print("Opened database successfully") conn.execute('''CREATE TABLE COMPANY (ID INT PRIMARY KEY NOT NULL, NAME TEXT NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(50), SALARY REAL);''') print("Table created successfully") conn.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (1, 'Paul', 32, 'California', 20000.00 )"); conn.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (2, 'Allen', 25, 'Texas', 15000.00 )"); conn.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (3, 'Teddy', 23, 'Norway', 20000.00 )"); conn.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 )"); conn.commit() print ("Records created successfully") cursor = conn.execute("SELECT id, name, address, salary from COMPANY") for row in cursor: print("ID = ", row[0]) print("NAME = ", row[1]) print("ADDRESS = ", row[2]) print("SALARY = ", row[3], "\n") conn.execute("UPDATE COMPANY set SALARY = 25000.00 where ID = 1") conn.commit print("Total number of rows updated :", conn.total_changes) cursor = conn.execute("SELECT id, name, address, salary from COMPANY") for row in cursor: print("ID = ", row[0]) print("NAME = ", row[1])
cursor.close() connection.close()