Skip to content

New slip 10 #3

@Aksh12002

Description

@Aksh12002

Here are the Python programs tailored to run on Thonny IDE (common for Raspberry Pi users). Each script follows the tasks you've specified.

a) Print a name 'n' times (using for and while loops)

Using a for loop

name = input("Enter a name: ")
n = int(input("Enter the number of times to print the name: "))
print("Using for loop:")
for i in range(n):
print(name)

Using a while loop

print("Using while loop:")
i = 0
while i < n:
print(name)
i += 1

b) Handle Divide by Zero Exception

try:
numerator = float(input("Enter the numerator: "))
denominator = float(input("Enter the denominator: "))
result = numerator / denominator
print("Result:", result)
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")

c) Print current time for 10 times with an interval of 10 seconds

import time
from datetime import datetime

for i in range(10):
print("Current time:", datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
time.sleep(10)

Note: In Thonny IDE, using time.sleep(10) will delay the output by 10 seconds between each print. You’ll see the current time printed every 10 seconds until 10 outputs are displayed.

d) Read a file line by line and print the word count of each line

file_path = input("Enter the file path: ")

try:
with open(file_path, 'r') as file:
line_number = 1
for line in file:
words = line.split()
word_count = len(words)
print(f"Line {line_number} has {word_count} words.")
line_number += 1
except FileNotFoundError:
print("Error: File not found. Please check the file path.")

Note: You’ll need to provide the path to the file (e.g., /home/pi/yourfile.txt) in Thonny’s input prompt when running this script.

These scripts should be fully compatible with Thonny IDE, and each will execute as expected. Let me know if you need any adjustments!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions