Programs
Programs
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:
contents = input_file.read()
output_file.write(contents)
except FileNotFoundError:
except Exception as 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.
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!")
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.
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 a hexagon
turtle.penup()
turtle.goto(100, 0) # Position for the hexagon
turtle.pendown()
draw_hexagon(100)
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.
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.
1. Create a Sample SQLite Database: First, let’s create a sample SQLite database and
a table to work with.
import sqlite3
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()
if __name__ == "__main__":
display_records()
Explanation
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.
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.
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!");
}
}
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.
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)
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.
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
Expected Output
Java Output:
Hello from Java!
This demonstrates how to call a Java program from a Python script, showcasing
interoperability between the two languages.