0% found this document useful (0 votes)
6 views7 pages

Programs

The document provides several Python scripts for different tasks, including copying file contents, handling exceptions, drawing graphics with Turtle, displaying database records using SQLite, and executing a Java program from Python. Each section includes code examples, explanations of how the code works, and instructions for running the scripts. The document serves as a comprehensive guide for beginners to understand basic programming concepts in Python and Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views7 pages

Programs

The document provides several Python scripts for different tasks, including copying file contents, handling exceptions, drawing graphics with Turtle, displaying database records using SQLite, and executing a Java program from Python. Each section includes code examples, explanations of how the code works, and instructions for running the scripts. The document serves as a comprehensive guide for beginners to understand basic programming concepts in Python and Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

7.write a script named copyfile.py.

This script should prompt the user for the names of two text
file.The contents of the first file should be input and written to the second file.

def copy_file_contents():

# Prompt the user for the names of the input and output files

input_file_name = input("Enter the name of the input file (with .txt extension): ")

output_file_name = input("Enter the name of the output file (with .txt extension): ")

try:

# Open the input file and read its contents

with open(input_file_name, 'r') as input_file:

contents = input_file.read()

# Write the contents to the output file

with open(output_file_name, 'w') as output_file:

output_file.write(contents)

print(f"Contents copied from '{input_file_name}' to '{output_file_name}' successfully.")

except FileNotFoundError:

print(f"Error: The file '{input_file_name}' was not found.")

except Exception as e:

print(f"An error occurred: {e}")

if __name__ == "__main__":

copy_file_contents()

How It Works:

1. User Input: The script prompts the user to enter the names of the input and output
text files.
2. File Handling:
o It attempts to open the input file in read mode.
o If successful, it reads the contents of the input file.
o It then opens the output file in write mode and writes the contents to it.
3. Error Handling: The script handles potential errors, such as the input file not being
found.

Running the Script

1. Save the code above into a file named copyfile.py.


2. Make sure you have a text file to read from.
3. Run the script using Python:

python copyfile.py

4. Follow the prompts to enter the input and output file names.

Example

 If your input file is source.txt and you want to copy it to destination.txt, simply
input those names when prompted. The contents of source.txt will be copied to
destination.txt.

8. Demonstrate a python code to print try, except and finally block statements.
def divide_numbers():
try:
# Prompt the user for two numbers
numerator = float(input("Enter the numerator: "))
denominator = float(input("Enter the denominator: "))

# Perform division
result = numerator / denominator
print(f"The result of {numerator} divided by {denominator} is:
{result}")

except ZeroDivisionError:
print("Error: You cannot divide by zero!")

except ValueError:
print("Error: Please enter valid numbers!")

finally:
print("Execution completed. Thank you!")

# Run the function


if __name__ == "__main__":
divide_numbers()

Explanation

1. Try Block:
o Prompts the user to input two numbers.
o Attempts to divide the numerator by the denominator and prints the result.
2. Except Blocks:
o ZeroDivisionError: Catches and handles the case where the user tries to
divide by zero.
o ValueError: Catches and handles the case where the user inputs invalid
numbers (e.g., letters instead of numbers).
3. Finally Block:
o Executes regardless of whether an exception occurred, ensuring that the
message "Execution completed. Thank you!" is printed at the end.

Running the Code

1. Save the code in a file named try_except_finally.py.


2. Run the script using Python:

python try_except_finally.py
Follow the prompts to enter the numerator and denominator. You can test the code with valid
numbers, zero, and invalid input to see how each scenario is handled.

9. write a 2D Graphics program for the following (a) Draw a star (b) Draw a letter (c) Draw a
hexagon with color.
import turtle

def draw_star(size):
"""Draws a star with the specified size."""
for _ in range(5):
turtle.forward(size)
turtle.right(144) # angle to create a star shape

def draw_letter():
"""Draws the letter 'A'."""
turtle.penup()
turtle.goto(-50, -50)
turtle.pendown()
turtle.setheading(75) # angle to start the letter
turtle.forward(100)
turtle.setheading(-75)
turtle.forward(100)
turtle.setheading(0)
turtle.forward(40)
turtle.setheading(75)
turtle.forward(40)

def draw_hexagon(size):
"""Draws a hexagon filled with color."""
turtle.fillcolor("blue") # Set fill color
turtle.begin_fill() # Start filling the color
for _ in range(6):
turtle.forward(size)
turtle.right(60)
turtle.end_fill() # End filling the color

def main():
turtle.speed(3) # Set the drawing speed

# Draw a star
turtle.penup()
turtle.goto(-150, 100) # Position for the star
turtle.pendown()
draw_star(100)

# Draw the letter 'A'


turtle.penup()
turtle.goto(-50, 100) # Position for the letter 'A'
turtle.pendown()
draw_letter()

# Draw a hexagon
turtle.penup()
turtle.goto(100, 0) # Position for the hexagon
turtle.pendown()
draw_hexagon(100)

# Complete the drawing


turtle.hideturtle()
turtle.done()

if __name__ == "__main__":
main()

Explanation

1. draw_star(size): Draws a star using a for loop to create the five points of the star.
The angle of 144 degrees creates the star shape.
2. draw_letter(): Draws the letter "A" using simple lines and angles.
3. draw_hexagon(size): Draws a hexagon with a specified size and fills it with blue
color.
4. main():
o Sets the drawing speed.
o Positions the turtle to draw the star, letter, and hexagon.
o Calls the respective drawing functions.

Running the Code

1. Save the code to a file named turtle_graphics.py.


2. Run the script using Python:

python turtle_graphics.py
A new window will open displaying the star, letter "A," and hexagon. You can adjust the sizes and
positions in the main() function as needed!

10. write a python program for display the database records from SQL.

To display database records from an SQL database using Python, you typically use the
sqlite3 module for SQLite databases or libraries like mysql-connector-python for
MySQL databases. Below, I'll provide an example using SQLite, as it’s simple and requires
no additional setup.

Example Python Program to Display Database Records Using SQLite

1. Create a Sample SQLite Database: First, let’s create a sample SQLite database and
a table to work with.

import sqlite3

# Create a sample database and table


def create_sample_db():
conn = sqlite3.connect('sample.db') # Connect to the database (creates
it if it doesn't exist)
cursor = conn.cursor()

# Create a sample table


cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
age INTEGER NOT NULL
)
''')

# Insert sample records


cursor.execute("INSERT INTO users (name, age) VALUES ('Alice', 30)")
cursor.execute("INSERT INTO users (name, age) VALUES ('Bob', 25)")
cursor.execute("INSERT INTO users (name, age) VALUES ('Charlie', 35)")

conn.commit() # Save (commit) the changes


conn.close() # Close the connection

create_sample_db()
2.Display Database Records: Now, here’s how you can read and display records from the users
table.
import sqlite3

def display_records():
conn = sqlite3.connect('sample.db') # Connect to the database
cursor = conn.cursor()

# Execute a query to retrieve all records


cursor.execute("SELECT * FROM users")

# Fetch all results


rows = cursor.fetchall()

# Print the records


print("ID\tName\tAge")
print("-" * 30)
for row in rows:
print(f"{row[0]}\t{row[1]}\t{row[2]}")

conn.close() # Close the connection

if __name__ == "__main__":
display_records()

Explanation

1. Creating a Sample Database:


o The create_sample_db function creates an SQLite database named
sample.db and a table named users.
o It inserts a few sample records into the table.
2. Displaying Records:
o The display_records function connects to the SQLite database and retrieves
all records from the users table.
o It then prints the records in a tabular format.
Running the Program

1. Save both parts of the code into a single file, say display_records.py.
2. Run the script using Python:

python display_records.py

This program will create the database, populate it with sample data, and then display the records.
You can modify the SQL queries to suit your needs or adapt the code for different databases (e.g.,
MySQL, PostgreSQL) by using the appropriate libraries.

12.write a python program to demonstrate the use of java program.

To demonstrate how to run a Java program from Python, you can use the subprocess
module in Python. This allows you to execute shell commands, including running Java
programs.

Here's a simple example that involves creating a Java program that prints "Hello from Java!"
and then calling that program from Python.

Step 1: Create a Java Program

First, create a Java file named HelloJava.java with the following content:

// HelloJava.java
public class HelloJava {
public static void main(String[] args) {
System.out.println("Hello from Java!");
}
}

Step 2: Compile the Java Program

You need to compile the Java program before you can run it. Open your terminal (or
command prompt) and navigate to the directory where HelloJava.java is located, then run:

javac HelloJava.java

This command will create a HelloJava.class file, which is the compiled Java bytecode.

Step 3: Create the Python Script

Now, create a Python script named run_java.py that will execute the Java program:

import subprocess

def run_java_program():
try:
# Run the Java program
result = subprocess.run(['java', 'HelloJava'], capture_output=True,
text=True)

# Check if the program executed successfully


if result.returncode == 0:
print("Java Output:")
print(result.stdout) # Print the output from the Java program
else:
print("Error executing Java program:")
print(result.stderr) # Print any error messages

except Exception as e:
print(f"An error occurred: {e}")

if __name__ == "__main__":
run_java_program()

Explanation

1. Java Program: The Java program simply prints "Hello from Java!" to the console.
2. Python Script:
o The script uses subprocess.run() to execute the Java program.
o It captures the output and errors, allowing you to display them in Python.
o The capture_output=True and text=True options ensure that the output is
captured as text.

Running the Programs

1. Ensure that both HelloJava.java and run_java.py are in the same directory.
2. Compile the Java program if you haven't done so already:

javac HelloJava.java

3.Run the Python script:


python run_java.py

Expected Output

When you run the Python script, it should print:

Java Output:
Hello from Java!

This demonstrates how to call a Java program from a Python script, showcasing
interoperability between the two languages.

You might also like