I'm writing a program where the user will input 3 numbers the day month and year and it will output in the format 2nd January 2014. So far i have done this
year =input("what year is it")
month=int(input("what is the numerical value of the month"))
day=input("what number day is it")
if month == 1:
January = str(month)
if day == 1 or 21 or 31:
print (day+"st January",year)
elif day == 2 or 22:
print (day+"nd January",year)
elif day ==3 or 23:
print (day+"rd January",year)
elif day == 4 or 5 or 6 or 7 or 8 or 9 or 10 or 11 or 12 or 13 or 14 or 15 or 16 or 18 or 19 or 20 or 24 or 25 or 26 or 27 or 28 or 29 or 30:
print (day+"th January",year)
the problem i have run into is that when i input a day such as 4 it will ouput as 4st January 2014.
I am using python 3 and have learnt for and while loops and also if statements if that helps
Use the libraries and dictionaries, a good rule to remember is if you need more than two ifs a dictionary might be better.
from datetime import date
ext_dir = {1:'st.', 2:'nd.', 3:'rd.',
21:'st.', 22:'nd.', 23:'rd.',
31:'st.' } # all the rest are th
# prompt for the year month day as numbers remember to int them
thedate = date(year, month, day)
ext = ext_dir.get(day, 'th.')
datestr = thedate.strftime('%%d%s %%M %%Y' % ext)
The problem you are running in to is that when you perform the check:
if day == 1 or 21 or 31:
operator precedence in python makes this statement act something like this:
if (day == 1) or (21) or (31):
and in python, like many other languages, non-null/non-zero values are "true", so you always evaluate to true in the first test. To fix this, modify the if statement, and all of the following tests to look more like the following:
if (day == 1) or (day == 21) or (day == 31):
year =input("what year is it")
month=int(input("what is the numerical value of the month"))
day=input("what number day is it")
if month == 1:
January = str(month)
if day == 1 or day == 21 or day == 31:
print (day+"st January",year)
elif day == 2 or day == 22:
print (day+"nd January",year)
elif day ==3 or day == 23:
print (day+"rd January",year)
else:
print (day+"th January",year)
Related
I'm teaching myself python to ATBS. Instead of spending 45 minutes typing out a bunch of repetitive data in excel I've spent the past 90 failing to write a simple calendar script.
Starting with the values "2012-09-01" and "2012-09-30" I want to each line to increase the month value by 1 it hits 12 and at which point the year value advances by 1, until the date 2018-12-31.
e.g.
"2012-09-01 2012-09-30
2012-10-01 2012-10-31
2012-11-01 2012-11-30
2012-12-01 2012-12-31"
Here's my code, which stops at 2012-12-31.
import datetime
year = 2012
month = 9
day_start = 1
day_end = 31
while year <= 2018:
while month <= 12:
if month == 4 or month == 6 or month == 9 or month == 11:
day_end = 30
else:
day_end = 31
print(datetime.date(year, month, day_start), " ", datetime.date(year, month, day_end))
month = month + 1
year = year + 1
Any help is much appreciated!
Check this out. Using the calendar library to detect leap years.
import datetime
import calendar
year = 2012
month = 9
day_start = 1
day_end = 31
while year <= 2018:
while month <= 12:
if month == 4 or month == 6 or month == 9 or month == 11:
day_end = 30
elif month == 2:
day_end = 29 if calendar.isleap(year) else 28
else:
day_end = 31
print(datetime.date(year, month, day_start), " ", datetime.date(year, month, day_end))
month = month + 1
year = year + 1
month = 1
Line
if month == 4 or month == 6 or month == 9 or month == 11:
can be abbreviated to:
if month in (4, 6, 9, 11):
Given a week number, (1st, 2nd, …), the day on which the 1st of the month falls (1 for Monday, 2 for Tuesday, …), and the number of days in the month: return a string consisting of the day of the month for each day in that week, starting with Monday and ending with Sunday. Week number represents the weeks in the months.
I have done the following functions:
My code for these functions are below.
import datetime
from datetime import datetime
import calendar
from datetime import date
def week(week_num, start_day, days_in_month):
week_string = ""
if week_num == 1:
if start_day == 1:
week_string = "1 2 3 4 5 6 7"
elif start_day == 2:
week_string = " 1 2 3 4 5 6"
elif start_day == 3:
week_string = " 1 2 3 4 5"
elif start_day == 4:
week_string = " 1 2 3 4"
elif start_day == 5:
week_string = " 1 2 3"
elif start_day == 6:
week_string = " 1 2"
elif start_day == 7:
week_string = " 1"
elif week_num == 2:
if start_day == 1:
week_string = "8 9 10 11 12 13 14"
elif start_day == 2:
week_string = "7 8 9 10 11 12 13"
elif start_day == 3:
week_string = "6 7 8 9 10 11 12"
elif start_day == 4:
#carry on in the above way, but this doesn't seem efficient
return week_string
def main():
month_name = input("Enter month:\n")
year = eval(input("Enter year:\n"))
if __name__=='__main__':
main()
Does anyone have any ideas on how to do the function? I need to return a string value
Another idea I had:
def week(week_num, start_day, days_in_month):
week_string = ""
if week_num == 1:
week_string = ""
day = start_day
for i in range(1, 8 -start_day+1):
week_string = week_string + str(i) + " "
week_string = "{0:<20}".format(week_string)
return week_string
An example of the input and output of this function:
week(1, 3, 30)
returns the string
' 1 2 3 4 5'
week(2, 3, 30)
returns the string
' 6 7 8 9 10 11 12’
edit: you heavily altered your question, I'll update my response once I'll understand what you need
datetime and calendar modules should supply you with all you need
from datetime import datetime
import calendar
# is leapyear
calendar.isleap(2020) # True
# just add +1 if you need it in the format that you want
datetime.strptime('25.2.2020', '%d.%m.%Y').weekday() # = 1 = Tuesday
# from name to month number
datetime.strptime('february', '%B').month # = 2
# days in month and weekday of starting month
# with the starting weekday you can easily calculate the number of weeks
calendar.monthrange(2020,2) # = (5, 29), 5=saturday, 29 days in month
Some general remarks to your code:
You can use 'January'.upper() to convert it to 'JANUARY' and only need to check month_name=='JANUARY' and save you the redundant comparison
You can use if month_num in [1,3,5,7,8,10,12]: to make it more readable
I have a dataframe with a column that includes individuals' birthdays. I would like to map that column to the individuals' astrology sign using code I found (below). I am having trouble writing the code to creat the variables.
My current dataframe looks like this
birthdate answer YEAR MONTH-DAY
1970-03-31 5 1970 03-31
1970-05-25 9 1970 05-25
1970-06-05 3 1970 06-05
1970-08-28 2 1970 08-28
The code I found that creates a function to map the dates is available at this website: https://www.geeksforgeeks.org/program-display-astrological-sign-zodiac-sign-given-date-birth/
Any tips would be appreciated.
Change previous answer by Series.dt.month_name with lowercase strings:
def zodiac_sign(day, month):
# checks month and date within the valid range
# of a specified zodiac
if month == 'december':
return 'Sagittarius' if (day < 22) else 'capricorn'
elif month == 'january':
return 'Capricorn' if (day < 20) else 'aquarius'
elif month == 'february':
return 'Aquarius' if (day < 19) else 'pisces'
elif month == 'march':
return 'Pisces' if (day < 21) else 'aries'
elif month == 'april':
return 'Aries' if (day < 20) else 'taurus'
elif month == 'may':
return 'Taurus' if (day < 21) else 'gemini'
elif month == 'june':
return 'Gemini' if (day < 21) else 'cancer'
elif month == 'july':
return 'Cancer' if (day < 23) else 'leo'
elif month == 'august':
return 'Leo' if (day < 23) else 'virgo'
elif month == 'september':
return 'Virgo' if (day < 23) else 'libra'
elif month == 'october':
return 'Libra' if (day < 23) else 'scorpio'
elif month == 'november':
return 'scorpio' if (day < 22) else 'sagittarius'
dates = pd.to_datetime(astrology['birthdate'])
y = dates.dt.year
now = pd.to_datetime('now').year
astrology = astrology.assign(month = dates.dt.month_name().str.lower(),
day = dates.dt.day,
year = y.mask(y > now, y - 100))
print (astrology)
birthdate answer YEAR MONTH-DAY month day year
0 1970-03-31 5 1970 03-31 march 31 1970
1 1970-05-25 9 1970 05-25 may 25 1970
2 1970-06-05 3 1970 06-05 june 5 1970
3 1970-08-28 2 1970 08-28 august 28 1970
astrology['sign'] = astrology.apply(lambda x: zodiac_sign(x['day'], x['month']), axis=1)
print (astrology)
birthdate answer YEAR MONTH-DAY month day year sign
0 1970-03-31 5 1970 03-31 march 31 1970 aries
1 1970-05-25 9 1970 05-25 may 25 1970 gemini
2 1970-06-05 3 1970 06-05 june 5 1970 Gemini
3 1970-08-28 2 1970 08-28 august 28 1970 virgo
You can apply the zodiac_sign function to the dataframe as -
import pandas as pd
from io import StringIO
# Sample
x = StringIO("""birthdate,answer,YEAR,MONTH-DAY
1970-03-31,5,1970,03-31
1970-05-25,9,1970,05-25
1970-06-05,3,1970,06-05
1970-08-28,2,1970,08-28
""")
df = pd.read_csv(x, sep=',')
df['birthdate'] = pd.to_datetime(df['birthdate'])
df['zodiac_sign'] = df['birthdate'].apply(lambda x: zodiac_sign(x.day, x.strftime("%B").lower()))
print(df)
Output:
birthdate answer YEAR MONTH-DAY zodiac_sign
0 1970-03-31 5 1970 03-31 aries
1 1970-05-25 9 1970 05-25 gemini
2 1970-06-05 3 1970 06-05 Gemini
3 1970-08-28 2 1970 08-28 virgo
I'm doing a task in Python, which is to create a zodiac calendar judging by input month and day of the month.
I've made a successful calendar, however, I have no idea how to solve the problem, if I input an incorrect month name or nonexistent date.
I have tried tons of things: to create a different hierarchy, or under each zodiac sign I wrote else: print ('Entering an incorrect date'). I even tried to register with if day <0 and day> 31 or month! = 'March' or month! = 'April', etc... It turned out to be a huge useless function in the end, and nothing worked either.
I feel that there is a one-line solution here to detect days < 0 and > 31 and incorrect month name, but I just can't understand it. Could somebody help, please?
month = input('Enter the month: ')
day = int(input ('Enter the date of month: '))
if day >= 21 and day <= 31 and month.lower() == 'march' or day >=1 and day <= 19 and month.lower() == 'april':
zodiac='Aries'
if day >= 20 and day <= 30 and month.lower() == 'april' or day >=1 and day <= 19 and month.lower() == 'may':
zodiac='Taurus'
if day >= 21 and day <= 31 and month.lower() == 'may' or day >=1 and day <= 20 and month.lower() == 'june':
zodiac='Gemini'
if day >= 21 and day <= 30 and month.lower() == 'june' or day >=1 and day <= 22 and month.lower() == 'july':
zodiac='Cancer'
if day >= 23 and day <= 31 and month.lower() == 'july' or day >=1 and day <= 22 and month.lower() == 'august':
zodiac='Leo'
if day >= 23 and day <= 31 and month.lower() == 'august' or day >=1 and day <= 22 and month.lower() == 'september':
zodiac='Virgo'
if day >= 23 and day <= 30 and month.lower() == 'september' or day >=1 and day <= 22 and month.lower() == 'october':
zodiac='Libra'
if day >= 23 and day <= 31 and month.lower() == 'october' or day >=1 and day <= 21 and month.lower() == 'november':
zodiac='Scorpio'
if day >= 22 and day <= 30 and month.lower() == 'november' or day >=1 and day <= 21 and month.lower() == 'december':
zodiac='Sagittarius'
if day >= 22 and day <= 31 and month.lower() == 'december' or day >=1 and day <= 19 and month.lower() == 'january':
zodiac='Capricorn'
if day >= 20 and day <= 31 and month.lower() == 'january' or day >=1 and day <= 18 and month.lower() == 'february':
zodiac='Aquarius'
if day >= 19 and day <= 28 and month.lower() == 'february' or day >=1 and day <= 20 and month.lower() == 'march':
zodiac='Pisces'
print('Conclusion:')
print(zodiac)
You might want to look into the datetime module. With it, you can do comparisons between dates and times easily without the need for extraneous if statements.
For example, if one were to do something like:
import datetime
dt = datetime.datetime.today()
print dt.month
Then you would get:
3
So instead of reading in input for months in a string format, you could simply ask for the number of the month to help create a datetime object more easily. Alternatively, you could do something like this:
month_input = input("What is the month?")
months = ["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"]
month_input = month_input.lower().strip() #convert to lowercase and remove whitespace
month_num = months.index(month_input) + 1 #Add one because lists start at index 0
That way you can get the number of the month to use a datetime object to do your comparisons and evaluations from there.
I'm trying to write a program that shows the days in a month when you type the number that corresponds to the month.
Ex. 1 = January, would print "31"
This is what I have and it seems logical to me. Although I'm just over a month into this and I have no idea what I'm doing.
def calcDaysInMonth():
(list,(range,(1, 12)))
a = raw_input()
int(a)
jan = 1
feb = 2
mar = 3
apr = 4
may = 5
june = 6
july = 7
aug = 8
sept = 9
octo = 10
nov = 11
dec = 12
if jan is True:
print("31")
using static number wont help you get correct result. because Feb days in leap year is different than normal. so use
$Year = 2017
$month = 08`
echo cal_days_in_month(CAL_GREGORIAN, (int)$month, $Year);
The reason your code isn't working is because you're assigning the input to a but you're never checking the value of a and using that to determine what should be printed (you're simply assigning integers to variables called jan, feb etc)
You're looking for something like this:
a = int(raw_input())
if a == 1:
print("31 days")
elif a == 2:
print("28 days")
# just repeat with elif until december/12
You could try to get clever with it with dictionaries to map months to days or something, but really a more sensible solution would be the following...
Due to February having a different number of days given leap years, it makes more sense to just use calendar.monthrange to get the number of days in a month for any given year:
from calendar import monthrange
year = 2017
a = int(raw_input())
num_days = monthrange(year, a)[1]
print("{} days".format(num_days))
Thank you for all your help guys.
My class now has an answer for what we were doing. What was wanted:
month = int(raw_input())
day = 0
def calcDays(month):
if month ==1:
days = 31
print 31
if month==2:
days = 28
print 28
if month == 3:
days = 31
print 31
if month == 4:
days = 30
print 30
if month==5:
days = 31
print 31
if month ==6:
days = 30
print 30
if month==7:
days = 31
print 31
if month ==8:
days = 31
print 31
if month==9:
days = 30
print 30