While loop is breaking too early. - python

import datetime
def main():
date_string = input('Enter a date in mm/dd/yy format: ')
date_list = date_string.split('/')
month = int(date_list[0])
day = int(date_list[1])
year = int(date_list[2])
while month < 1 or month > 12:
print('Month entered is out of range')
date_string = input('Re-enter a date in mm/dd/yy format: ')
date_list = date_string.split('/')
month = int(date_list[0])
day = int(date_list[1])
year = int(date_list[2])
while day < 1 or day > 31:
print('Day entered is out of range')
date_string = input('Re-enter a date in mm/dd/yy format: ')
date_list = date_string.split('/')
month = int(date_list[0])
day = int(date_list[1])
year = int(date_list[2])
while year != 13:
print('Year does not represent 2013')
date_string = input('Re-enter a date in mm/dd/yy format: ')
date_list = date_string.split('/')
month = int(date_list[0])
day = int(date_list[1])
year = int(date_list[2])
print(month, day, year)
main()
When I run the program and enter months and days that are invalid, it progresses down until the year validation and will keep posting that prompt even if the input is invalid for one of the other inputs.

You could arrange this differently:
while True:
date_string = input('Enter a date in mm/dd/yy format: ')
date_list = date_string.split('/')
month = int(date_list[0])
day = int(date_list[1])
year = int(date_list[2])
if month < 1 or month > 12:
print('Month entered is out of range')
elif day < 1 or day > 31:
print('Day entered is out of range')
elif year != 13:
print('Year does not represent 2013')
else:
break
print(month, day, year)

Start again.
You don't want three little while loops. You want one big while loops ( while not success ) with three if statement to make the three checks and if any one fails, set success to false.

Related

How do find the top of a row using pandas

First of all I would just like to mention - I am a beginner, I am still learning. This code is probably an abomination and I might be missing something obvious, please be nice.
My question is this. I have written a for loop to find the highest earning employee but I would like for the user to select a start and end date for their earnings to be calculated.
So for example my program should be able to calculate an employees earning from 01/05/2021 to 09/05/2021.
The only thing I'm struggling with is how to reference the date, I've been googling for an hour but the responses are just too complicated for me.
import pandas as pd
import matplotlib.pyplot as plt
from datetime import datetime as dt
df = pd.read_csv('Task_4a_data.csv', index_col='ID')
#main menu
def menu():
print("\t\t****MAIN MENU****")
print('1) Enter sales records')
print('2) Run reports')
x = int(input(""))
return x
#reports menu
def menu2():
print("**** Reports Dashboard ****")
print("1. Individual Employee Report")
print("2. Show employees with the highest sales value")###########
x = int(input(""))
return x
def ind_emp_check(df_r, id, date1, date2):
df_r = df_r.loc[df.index == id]
df_r = df_r.T[3:]
df_r.reset_index(inplace=True)
df_r['ID1'] = pd.to_datetime(df_r['index'], format='%d/%m/%Y')
date1 = pd.to_datetime(date1, format='%d/%m/%Y')
date2 = pd.to_datetime(date2, format='%d/%m/%Y')
mask = (df_r['ID1'] >= date1) & (df_r['ID1'] <= date2)
df_search = df_r.loc[mask]
print(df_search)
print('Total by id = {} is {}'.format(id, sum(df_search[id])))
plt.bar(df_search['index'], df_search[id])
plt.xticks(rotation=90)
plt.show()
y = menu()
while y == 1 or y == 2:
if y == 1:
try:
ID = int(input("Enter the Staff ID "))
if ID not in df.index.values:
print('yes')
date1 = input("Enter Date in dd/mm/yy: ")
day, month, year = date1.split("/")
date1 = datetime.date(int(year), int(month), int(day))
if datetime.datetime.strptime(date1.strftime('%d/%m/%Y'), '%d/%m/%Y') > datetime.datetime.strptime(
dt.today().strftime('%d/%m/%Y'), '%d/%m/%Y'):
print("Date is in the future")
else:
cost = float(input("Enter the cost : "))
df.loc[ID, date1.strftime('%d/%m/%Y')] = cost
# df.to_csv('test2.csv')
except:
print("\n\nError Occurred Please try again\n\n")
y = menu()
if y == 2:
x = menu2()
if x == 1:
try:
id = int(input("Enter the Employee Id : "))
s_date = input("Enter Starting Date in dd/mm/yyyy: ")
day, month, year = s_date.split("/")
s_date = datetime.date(int(year), int(month), int(day))
e_date = input("Enter End Date in dd/mm/yyyy: ")
day, month, year = e_date.split("/")
e_date = datetime.date(int(year), int(month), int(day))
s_date = datetime.datetime.strptime(s_date.strftime('%d/%m/%Y'), '%d/%m/%Y')
e_date = datetime.datetime.strptime(e_date.strftime('%d/%m/%Y'), '%d/%m/%Y')
ind_emp_check(df, id, s_date, e_date)
except:
print("\n\nError Occurred Please try again\n\n")
x = menu2()
elif x == 2:
s_date = input("Enter Starting Date in dd/mm/yyyy: ")
e_date = input("Enter End Date in dd/mm/yyyy: ")
total = 0
totals = []
for r in df.index:
for i in (df.loc[r]):
if PLACEHOLDER == e_date:
break
try:
total+=i
total = int(total)
except:
pass
totals.append(total)
total=0
largest_number = totals[0]
for number in totals:
if number > largest_number:
largest_number = number
print(largest_number)
else:
x = menu2()
else:
x = menu()
x = menu()```

Convert a date into an integer in python

I'am trying to convert a date to an integer for a comparison.
# Python3 code to calculate age in years
import datetime
from datetime import date
date_entry = input('Enter your birthdate in YYYY/MM/DD format: ')
year, month, day = map(int, date_entry.split('/'))
date1 = datetime.date(year, month, day)
def calculateAge(birthDate):
today = date.today()
age = today.year - birthDate.year - \
((today.month, today.day) < (birthDate.month, birthDate.day))
return age
# Driver code
print(calculateAge(date1), "years")
if date1 < 18:
print('You are under age')
exit()
I have an error in my if statement because date1 is not an integer.
How can I solve this?
Thanks.
you can edit as below.
if calculateAge(date1) < 18:
print('You are under age')
exit()
enter image description here

want to show month name and leap year in python

The program should prompt the user to enter the month and year (as integers) and display the number of days in the month, showing the month name. For example, if the user entered month 2 and the year 2000, the program should display:
Enter a month as an integer (1-12): 2
Enter a year: 2000
There are 29 days in February of 2000
def numberOfDays(month, year):
daysInMonths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if month > len(daysInMonths) or year < 0 or month < 0:
return "Please enter a valid month/year"
return daysInMonths[month-1] + int((year % 4) == 0 and month == 2)
def main():
year = int(input("Enter a year: "))
month = int(input("Enter a month in terms of a number: "))
print(month, year, "has", numberOfDays(month, year) , "days")
if __name__ == '__main__':
main()
In this program, I want to show the month's name and print it in the last.
How would the program be then? What should I do?
For example, if the input is 1, then 1 should be assigned as January and also be printed.
Use a dictionary:
dict_month = {1:"January", 2: "February"} # and so on ...
print(dict_month.get(month), year, "has", numberOfDays(month, year) , "days")
You may use the calendar module to get this done:
import calendar
months = list(calendar.month_name) #gets the list of months by name
obj = calendar.Calendar()
y, m = int(input('Enter year: ')), int(input('Enter a month as an integer (1-12): '))
days = calendar.monthrange(y, m)[1]
print(f'There are {days} days in {months[m]} of {y}')
And if all you want to do is to check if year is leap:
import calendar
print(calendar.isleap(int(input('Enter year: '))))

Cannot operate on year value of regular expression

This is my first question here so please forgive and educate on any formatting errors. I am new to Python and going through automate the boring stuff. Decided to expand the date detection project by using the clipboard and formatting some things also. The problem I have is in any operation taken on the year part of the REGEX.
I have commented out my last attempt to validate the year and gave up and changed the REGEX to only find dates from 1000 to 2999 and skipped code validation of the dates.
I now need to validate leap years but I'm back to having to work with the year variable, but once again no operation has any effect.
Basically the problem is I can extract the year value and display it but I cannot modify it or do checks against it.
#! python3
#! detect dates in a block of text
import pyperclip
import re
#!import numpy as np
text = str(pyperclip.paste())
def datedetection(text):
dateRegex = re.compile(
r"""(
(\d|\d\d) #! match day
(/{1}) #! match /
(\d|\d\d) #! match month
(/{1}) #! match /
([1|2][0-9][0-9][0-9]) #! match year
)""",
re.VERBOSE,
)
matches = []
for groups in dateRegex.findall(text):
day = str(groups[1])
slash1 = str(groups[2])
month = str(groups[3])
slash2 = str(groups[4])
year = str(groups[5])
month_range_30 = ["04", "06", "09", "11"]
month_range_31 = ["01", "03", "05", "07", "08", "10", "12"]
month_range_Feb = ["02"]
#!year_range = np.arange(1000, 3000, 1).tolist()
if len(day) == 1:
day = "0" + day
else:
day = day
if len(month) == 1:
month = "0" + month
else:
month = month
if month in month_range_31:
if int(day) > 31:
day = "Too many days in a month with only 31 days."
slash1 = month = slash2 = year = ""
elif month in month_range_30:
if int(day) > 30:
day = "Too many days in a month with only 30 days."
slash1 = month = slash2 = year = ""
elif month in month_range_Feb:
if int(day) > 29:
day = "Too many days in February."
slash1 = month = slash2 = year = ""
elif int(month) > 12:
day = "Found an invalid month."
slash1 = month = slash2 = year = ""
elif month in month_range_Feb:
if (
int(day) == 29
and (int(year) % 4 == 0)
and (int(year) % 400 == 0)
and (int(year) % 100 == 0)
):
day = day
elif month in month_range_Feb:
if (
int(day) == 29
and (int(year) % 4 == 0)
and (int(year) % 100 != 0)
):
day = "Found an invalid leap year."
slash1 = month = slash2 = year = ""
#!elif year not in year_range:
#!day = "Year is out of range."
#!slash1 = month = slash2 = year = ""
dates = "".join([day, slash1, month, slash2, year])
matches.append(dates)
if len(matches) > 0:
pyperclip.copy("\n".join(matches))
print("Copied to clipboard:")
print("\n".join(matches))
else:
print("No dates found.")
datedetection(text)
In my approach to this project, I considered validating the days, months, and year ranges as part of the regular expression. I then defined functions to check for the leap year, and validate the number of days according to the months.
I found that way simpler and easier to understand and follow. As below:
dateRegex = re.compile(r'([0-3][0-9])/([0-1][0-9])/([1-2][0-9]{3})')
def is_leap_year(year):
year = int(year)
if year % 4 == 0:
if year % 100 == 0:
return year % 400 == 0
else:
return True
else:
return False
def is_valid_date(day, month, year):
if month == '02':
if is_leap_year(year):
return int(day) <= 29
else:
return int(day) <= 28
elif month in ['04', '06', '09', '11']:
return int(day) <= 30
else:
return int(day) <= 31
You can find the rest of my code below.
https://gist.github.com/alialbusaidi/f56e4c9342f622434f8bff0549f94884
The problem was the operations before the year operations. The day and month operations were overwriting the year values. Not entirely sure how or why at this point, but moving the year code above the day and month code has started to fix the issue.

how do you program a calendar that can tell you the days ago/ from now (past/future dates) of a specific date you enter in

I am trying to program a calendar that checks how many days from now/ ago (past and present) from raw_input. I need a loop that counts the days through the current year and adds it to a variable called: Total_days and this loop has to go through each year until it hits the current date that the code ran on. The end result is that the output gives you the date you entered in a complete sentence: eg. "10/08/1700 was ___ days ago" Basically my teacher explained that the past days has to add up until it hits that certain date using a loop(loops are required. This is an assignment, i cant use any other functions like delta, but loops and datetime stuff is good!) and then for the future it has to say how many days from now until that futuristic date happens using loops. I am very stumped and i need your guys' help.
Heres what i got so far:
import datetime
input_date = raw_input("Enter in full format (mm/dd/yyyy):")
year = input_date[6:10]
yeara = int(year)
montha = int(input_date[1:2])
daya = int(input_date[4:5])
from datetime import datetime
from datetime import date
now = datetime.now()
year = now.year
month = now.month
day = now.day
def isleapYear(year):
if year % 4 == 0:
check = True
if year % 100 == 0:
check = False
if year % 400 == 0:
check = True
total_days = 0
n = 12
moNum = [0,31,28,31,30,31,30,31,31,30,31,30,31]
while n > montha:
if yeara > year:
if year == isleapYear(year):
total_days += 366
elif year != isleapYear(year):
total_days += 365
if montha == month:
break
total_days += int(moNum[n])
if n == 02:
if isleapYear(year) == True:
total_days += 1
n -= 1
ny = 365
h = total_days
if yeara > year:
if year == isleapYear(year):
total_days += 366
elif year != isleapYear(year):
total_days += 365
if yeara>year:
time = "future"
if yeara<year:
time = "past"
if yeara==year:
if montha>month:
time = "future"
if montha<month:
time = past
if montha == month:
if daya>day:
time = "future"
if daya<day:
time = "past"
if daya==day:
time = "present"
print str(h.days) + " days in the " + str(time)
Thanks for helping out! i appreciate your help :)
Must you use a loop? Else, you can build from the following:
refdatestr = "2010/08/23"
refdate = datetime.strptime(refdatestr, "%Y/%m/%d")
now = datetime.now()
difference_days = (now-refdate).days
difference_days is a datetime.timedelta object. If refdate (or refdatestr) was in the future, this would be negative.
Here is an updated code, with everything fixed:
import datetime
input_date = raw_input("Enter in full format (mm/dd/yyyy):")
year = input_date[6:10]
yeara = int(year)
montha = int(input_date[1:2])
daya = int(input_date[4:5])
from datetime import datetime
from datetime import date
now = datetime.now()
year = now.year
month = now.month
day = now.day
def isleapYear(year):
if year % 4 == 0:
check = True
if year % 100 == 0:
check = False
if year % 400 == 0:
check = True
end_date = input_date
start_date = now
delta = date(year,month,day)
delta2 = date(yeara,montha,daya)
h = delta-delta2
if yeara>year:
time = "future"
if yeara<year:
time = "past"
if yeara==year:
if montha>month:
time = "future"
if montha<month:
time = past
if montha == month:
if daya>day:
time = "future"
if daya<day:
time = "past"
if daya==day:
time = "present"
print str(h.days) + " in the " + str(time)
The most important thing that you forgot is that there are functions in datetime that will automatically find the number of days till the input...
Hope this helps!!!

Categories