[go: up one dir, main page]

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

Time Sheet Problem

The document describes functions to record employee time sheets by date and month, and calculate total hours worked in a month. It also describes functions to create, add/remove items from, and display shopping lists stored in text files.

Uploaded by

instructor Amer
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views7 pages

Time Sheet Problem

The document describes functions to record employee time sheets by date and month, and calculate total hours worked in a month. It also describes functions to create, add/remove items from, and display shopping lists stored in text files.

Uploaded by

instructor Amer
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Time sheet problem:

• Write a subroutine that asks the user for a date in the format dd/mm and
hours worked. These details are recorded in a set of serial files, one for each
month.
• New data is appended to the correct file. E.g. if the user enters 22/04 and 5,
the file called April.txt will have the number 5 added to it.
• Write another subroutine that takes a month as a parameter and outputs
the total hours for that month.
Coding and Discussion:
def record_hours_for_date():
try:
date = input("Enter the date (dd/mm): ")
hours_worked = float(input("Enter hours worked: "))
# Extract month from the date
month = date.split('/')[1].capitalize()
# Open the file for the corresponding month in append mode
with open(f"{month}.txt", "a") as file:
file.write(f"{date} {hours_worked}\n")
print(f"Hours worked on {date} recorded successfully.")
except Exception as e:
print(f"An error occurred: {e}")
Notes:
• date.split('/'): This part uses the split method on the date string. It splits the string into a
list of substrings using '/' as the delimiter. For example, if date is "22/october", this
operation results in the list ['22', '04'].
• [1]: This part retrieves the second element (index 1) from the list obtained after the split
operation. In Python, list indices start from 0, so [1] gets the element at index 1. In the
example, this results in 'October'.
#Continue:
def total_hours_for_month(month):
try:
# Open the file for the specified month in read mode
with open(f"{month.capitalize()}.txt", "r") as file:
total_hours = sum(float(line.split()[1]) for line in file)

print(f"Total hours worked in {month}: {total_hours} hours.")


except FileNotFoundError:
print(f"No data available for {month}.")
except Exception as e:
print(f"An error occurred: {e}")
Notes:
total_hours = sum(float(line.split()[1]) for line in file) is to calculate the total hours
worked by summing up the second column (index 1) of each line in the file, where
the values represent hours worked
• for line in file: This is a generator expression that iterates over each line in
the file (file). It reads each line and assigns it to the variable line.
• line.split(): This part splits the line into a list of substrings using whitespace
as the default delimiter. For example, if the line is "22/October 5.5",
line.split() results in ['22/04', '5.5'].
• line.split()[1]: This extracts the second element (index 1) from the list
obtained after the split operation. In the example, this gets the string '5.5'.
• float(line.split()[1]): This converts the extracted string to a floating-point
number. In the example, it converts '5.5' to the float value 5.5.
• sum(...): This calculates the sum of all the floating-point numbers generated
by the expression. It adds up the total hours worked from all lines in the file
#Continue:
def main():
while True:
print("\n1. Record hours for a date")
print("2. Calculate total hours for a month")
print("3. Quit")

choice = input("Enter your choice (1/2/3): ")


if choice == '1':
record_hours_for_date()
elif choice == '2':
month = input("Enter the month (e.g., January): ")
total_hours_for_month(month)
elif choice == '3':
print("Exiting the program. Goodbye!")
break
else:
print("Invalid choice. Please enter 1, 2, or 3.")

if __name__ == "__main__":
main()
Shopping List:
def create_shopping_list():
try:
file_name = input("Enter a name for your new shopping list: ")
with open(f"{file_name}.txt", "w") as file:
print(f"New shopping list '{file_name}' created.")

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

def add_item_to_list():
try:
file_name = input("Enter the name of the shopping list: ")
item = input("Enter the item to add: ")
with open(f"{file_name}.txt", "a") as file:
file.write(f"{item}\n")
print(f"{item} added to '{file_name}'.")

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

def remove_item_from_list():
try:
file_name = input("Enter the name of the shopping list: ")
item_to_remove = input("Enter the item to remove: ")

with open(f"{file_name}.txt", "r") as file:


items = [line.strip() for line in file if line.strip() != item_to_remove]

with open(f"{file_name}.txt", "w") as file:


file.write("\n".join(items))

print(f"{item_to_remove} removed from '{file_name}'.")

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

def display_shopping_list():
try:
file_name = input("Enter the name of the shopping list: ")
with open(f"{file_name}.txt", "r") as file:
print(f"Shopping list '{file_name}':")
for line in file:
print(line.strip())

except FileNotFoundError:
print(f"Shopping list '{file_name}' not found.")
except Exception as e:
print(f"An error occurred: {e}")

def main():
while True:
print("\n1. Create a new shopping list")
print("2. Add item to a shopping list")
print("3. Remove item from a shopping list")
print("4. Display a shopping list")
print("5. Quit")

choice = input("Enter your choice (1/2/3/4/5): ")

if choice == '1':
create_shopping_list()
elif choice == '2':
add_item_to_list()
elif choice == '3':
remove_item_from_list()
elif choice == '4':
display_shopping_list()
elif choice == '5':
print("Exiting the program. Goodbye!")
break
else:
print("Invalid choice. Please enter 1, 2, 3, 4, or 5.")

if __name__ == "__main__":
main()

You might also like