python_mini_projeler
python_mini_projeler copied to clipboard
python
Your Name: Hajra Chughtai
Program Name: Hajra-Homework3A.py
What the program does: This program tests if a date is a Magic Date or not.
Function to check if a date is a Magic Date
def is_magic_date(day, month, year): return day * month == int(str(year)[-2:])
Input from the user
day = int(input("Enter the day (1-31): ")) month = int(input("Enter the month (1-12): ")) year = int(input("Enter the year (4-digit): "))
Check if the entered date is a Magic Date
if is_magic_date(day, month, year): print(f"{day}/{month}/{year} is a Magic Date!") else: print(f"{day}/{month}/{year} is not a Magic Date.")
input('Press Enter to exit')
To create a "magic date" function in Python that takes input from the user, you can use the datetime module. A magic date is a date where the day multiplied by the month equals the two-digit year.
Here's an example of how you can implement this function:
from datetime import datetime
def is_magic_date(date_string):
try:
date = datetime.strptime(date_string, "%m-%d-%y")
day = date.day
month = date.month
year = date.year % 100
if day * month == year:
return True
else:
return False
except ValueError:
return False
# Get date input from the user
date_input = input("Enter a date in MM-DD-YY format: ")
# Check if the date is magic
if is_magic_date(date_input):
print("It's a magic date!")
else:
print("It's not a magic date.")
In this code, you define the is_magic_date
function that takes a date string in the "MM-DD-YY" format as input. It tries to parse the date using datetime.strptime
. If the parsing is successful, it extracts the day, month, and two-digit year from the parsed date.
The function then checks if the day multiplied by the month equals the year. If they are equal, it returns True
, indicating that it's a magic date. Otherwise, it returns False
.
Finally, we get the date input from the user using the input
function and pass it to the is_magic_date
function to check if it's a magic date. The result is printed accordingly.
def is_magic_date(date_str): try: # Split the date string into day, month, and year components day, month, year = map(int, date_str.split('/'))
# Calculate the last two digits of the year
last_two_digits = year % 100
# Check if the date is magic
if day * month == last_two_digits:
return True
else:
return False
except ValueError:
# Handle invalid date format
return False
Get the date input from the user
date_input = input("Enter a date in the format DD/MM/YY: ")
Check if it's a Magic Date and print the result
if is_magic_date(date_input): print(f"{date_input} is a Magic Date!") else: print(f"{date_input} is not a Magic Date.")