Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Python practical for practice. Help to clear external practical exam, Cheat Sheet of Programming Languages

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

2022/2023

Uploaded on 11/29/2023

pavan-8
pavan-8 🇮🇳

1 document

1 / 19

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
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 + " " + string2
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 + num2
difference_result = num1 - num2
product_result = num1 * num2
division_result = num1 / num2
print("Sum:", sum_result)
print("Difference:", difference_result)
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13

Partial preview of the text

Download Python practical for practice. Help to clear external practical exam and more Cheat Sheet Programming Languages in PDF only on Docsity!

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

string_operations.py

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.

Writing 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 -o ") sys.exit(2) # Process the options and their arguments for opt, arg in opts: if opt == '-h':

Display a help message and exit if the user specifies -h

print("Usage: basic_example.py -i -o ") sys.exit() elif opt == '-i': # Store the input file name when -i is specified input_file = arg elif opt == '-o': # Store the output file name when -o is specified output_file = arg # Perform some operation using input_file and output_file print("Input file:", input_file) print("Output file:", output_file) if name == "main": # Call the main function with command-line arguments excluding the script name main(sys.argv[1:]) 9.d. Program based on using Threads. import threading import time def task1(): for i in range(5): print("Task 1 - Iteration", i) time.sleep(1) def task2(): for i in range(5): print("Task 2 - Iteration", i) time.sleep(1) thread1 = threading.Thread(target=task1) thread2 = threading.Thread(target=task2) thread1.start() thread2.start() thread1.join() thread2.join() print("Both threads have finished.")

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

string_operations.py

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

Create a new DBM database or open an existing one

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

Open the existing DBM database

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:

  1. b. Practical based on using Relational Database - Writing SQL Statements, Defining Tables, Setting Up a Database.** import sqlite # Connect to or create an SQLite database (e.g., my_database.db) connection = sqlite3.connect("my_database.db") # Create a cursor object for executing SQL statements cursor = connection.cursor() # Create a table named 'employees' cursor.execute(''' CREATE TABLE IF NOT EXISTS employees (

# 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 = ''' Alice 30 Bob 25 ''' # Parse the XML data into an ElementTree object root = ET.fromstring(xml_data)

Extract and print information from the XML

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):

method to append the start tag to the list start_tags.

defhandle_starttag(self, tag, attrs): global start_tags start_tags.append(tag)

method to append the end tag to the list end_tags.

defhandle_endtag(self, tag): global end_tags end_tags.append(tag)

method to append the data between the tags to the list all_data.

defhandle_data(self, data): global all_data all_data.append(data)

method to append the comment to the list comments.

defhandle_comment(self, data): global comments comments.append(data) start_tags = [] end_tags = [] all_data = [] comments = []

Creating an instance of our class.

parser = Parser()

Poviding the input.

parser.feed('Satyam Blog

' '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,x

if 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])

7. Close the cursor and connection when done

cursor.close() connection.close()