I am writing a code that allows the user to enter a month and date and the program will tell them what season it will be given the information that the user entered. What I currently have working is that when you enter certain months that have the season in all their days it will display the season. But when I enter a month and date that has 2 seasons it gives me an error. This is the season guide that I am following:
Spring: March 20 - June 20
Summer: June 21 - September 21
Autumn: September 22 - December 20
Winter: December 21 - March 19
What I am trying to figure out is why the program is not printing out stuff when certain dates are entered. For example if I enter March 25th it should print out spring but it doesnt.
This is my code:
input_month = input('Enter a month: ')
input_day = input('Enter a date: ')
month_lower = input_month.lower()
seasons = ()
if month_lower == 'january' or month_lower == 'febuary' or month_lower == 'march' and input_day <19:
seasons = 'winter'
elif month_lower == 'march' and input_day <=19 or month_lower == 'april' or month_lower == 'may' or month_lower == 'june' and input_day < 21:
seasons = 'spring'
elif month_lower == 'july' or month_lower == 'august' or month_lower == 'september' and input_day <22:
seasons = 'summer'
elif month_lower == 'october' or month_lower == 'november' or month_lower == 'december' and input_day <20:
seasons = 'autumn'
else:
print('Please enter a valid date')
print(seasons)
You have a problem in the spring condition, you should check if the day is strictly superior to 19:
elif month_lower == 'march' and input_day > 19 or month_lower == 'april' or month_lower == 'may' or month_lower == 'june' and input_day < 21:
seasons = 'spring'
I supposed you're getting input not an int error when entering date since you compare input_day to an int, quick fix for this is to change all input_day to int(input_day).
But if your problem is that march 25 not printing out what you want but instead gave out please enter valid date then that'd be because you've not gave it a condition just yet, all above condition are average less than 20 but none talk about 22-30
Related
This question already has answers here:
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
How to test multiple variables for equality against a single value?
(31 answers)
Closed 5 months ago.
def daysOfMonth():
month = input('Input the name of Month: ')
if month == 'January' or 'March' or 'May' or 'July' or 'August' or 'October' or 'December ':
print('No. of days: 31 days')
elif month == 'February':
print('No. of days: 28 days')
elif month == 'April' or "June" or 'September' or 'November':
print('No. of days: 30 days')
I Input April and it says 31 days
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 2 years ago.
This is a follow up question (?) to a post I made yesterday: Python pandas df.loc not being found in a table
I'm trying to I'm trying to find a certain row and column in a given .csv file with pandas. Here is a snapshot of the table: Table
The table goes from 1/1/2015 to 12/31/2017. I've located the specific column and date I want to use from the csv file, and printing it so I can see if it's working properly. This is the code I have thus far:
months = {'January': 1, 'February': 2, 'March': 3, 'April': 4, 'May': 5, 'June': 6,
'July': 7, 'August': 8, 'September': 9, 'October': 10, 'November': 11, 'December': 12}
month = str(input('Enter a month: '))
year = str(input('Enter a year: '))
if not (2015 <= float(year) <= 2017):
print('Enter a year bewteen 2015 and 2017, both included and try again')
exit()
day = 1
df1 = df.set_index(['Date'])
if (month == 'January' or 'March' or 'May' or 'July' or 'August' or 'October' or 'December'):
while day < 32:
find = df1.loc[[str(months[month]) + '/' + str(day) + '/' + str(year)], ['Temp Low']]
print(find)
day += 1
elif (month == 'April' or 'June' or 'September' or 'November'):
while day < 31:
find = df1.loc[[str(months[month]) + '/' + str(day) + '/' + str(year)], ['Temp Low']]
print(find)
day += 1
elif (month == 'February'):
if year == '2016':
while day < 29:
find = df1.loc[[str(months[month]) + '/' + str(day) + '/' + str(year)], ['Temp Low']]
print(find)
day += 1
else:
while day < 28:
find = df1.loc[[str(months[month]) + '/' + str(day) + '/' + str(year)], ['Temp Low']]
print(find)
day += 1
This code is working correctly for months with 31 days, but breaks for any other month. For example if I enter "June" for the month (no quotations), the code works until it reaches day 30, then tries to look for day 31. Why is this happening? It seems to be searching for day 31 in the date column even though I've restricted it to be less than 31.
Picture of error code:
Error
Your or statements are plain wrong.
if (month == 'January' or 'March' or 'May' or 'July' or 'August' or 'October' or 'December'):
always evaluates to true; you'll want to replace that idiom with e.g.
if month in ('January', 'March', 'May', 'July', 'August', 'October', 'December'):
It's as simple as changing your if and elif statements.
if (month == 'January' or 'March' or 'May' or 'July' or 'August' or 'October' or 'December'):
think of the or statement as another if: you have to compare it to the month again.
In other words: in your if statement, you're literally saying "if month is equal to January or if march or if May or if July ..." As we know, If 'July' really doesn't mean anything.
try : if month in ('January', 'March', 'May', 'July', 'August', 'October', 'December'):
I have a table that has one column as day of birth and another as month of birth of students. I need to transform it into their zodiac signs.
I have found a function on the internet that transforms month and day of birth into zodiac signs, but it takes inputs. What if it's from two columns of a table?
def signo(table): #from https://www.w3resource.com/python-exercises/python-conditional-exercise-38.php
month = int(table.iloc[:,1])
day = int(table.iloc[:,2])
astro_sign = 0
if month == 12:
astro_sign = 'sagittarius' if (day < 22) else 'capricorn'
elif month == 1:
astro_sign = 'capricorn' if (day < 20) else 'aquarius'
elif month == 2:
astro_sign = 'aquarius' if (day < 19) else 'pisces'
elif month == 3:
astro_sign = 'pisces' if (day < 21) else 'aries'
elif month == 4:
astro_sign = 'aries' if (day < 20) else 'taurus'
elif month == 5:
astro_sign = 'taurus' if (day < 21) else 'gemini'
elif month == 6:
astro_sign = 'gemini' if (day < 21) else 'cancer'
elif month == 7:
astro_sign = 'cancer' if (day < 23) else 'leo'
elif month == 8:
astro_sign = 'leo' if (day < 23) else 'virgo'
elif month == 9:
astro_sign = 'virgo' if (day < 23) else 'libra'
elif month == 10:
astro_sign = 'libra' if (day < 23) else 'scorpio'
elif month == 11:
astro_sign = 'scorpio' if (day < 22) else 'sagittarius'
return astro_sign
I tried using iloc or naming the column, but it does not work (and honestly, I don't know if it should work).
What I get when using iloc is:
NameError: ("name 'table' is not defined", 'occurred at index CO_CURSO')
Instead of trying to work with the entire table in your function signo, you can modify it to work on a single row of your DataFrame and then transform your entire dataset using apply:
First let's create some sample data:
import numpy as np
import pandas as pd
np.random.seed(28)
df = pd.DataFrame(
data={
"birth_month": np.random.randint(1, 12, 10),
"birth_day": np.random.randint(1, 30, 10)
}
)
print(df)
Output:
birth_month birth_day
0 2 24
1 10 13
2 6 13
3 7 6
4 5 9
5 1 25
6 4 19
7 8 12
8 1 29
9 4 25
Then we modify the function signo to work row by row:
def signo(row):
month = int(row[0])
day = int(row[1])
astro_sign = 0
if month == 12:
astro_sign = 'sagittarius' if (day < 22) else 'capricorn'
elif month == 1:
astro_sign = 'capricorn' if (day < 20) else 'aquarius'
elif month == 2:
astro_sign = 'aquarius' if (day < 19) else 'pisces'
elif month == 3:
astro_sign = 'pisces' if (day < 21) else 'aries'
elif month == 4:
astro_sign = 'aries' if (day < 20) else 'taurus'
elif month == 5:
astro_sign = 'taurus' if (day < 21) else 'gemini'
elif month == 6:
astro_sign = 'gemini' if (day < 21) else 'cancer'
elif month == 7:
astro_sign = 'cancer' if (day < 23) else 'leo'
elif month == 8:
astro_sign = 'leo' if (day < 23) else 'virgo'
elif month == 9:
astro_sign = 'virgo' if (day < 23) else 'libra'
elif month == 10:
astro_sign = 'libra' if (day < 23) else 'scorpio'
elif month == 11:
astro_sign = 'scorpio' if (day < 22) else 'sagittarius'
return astro_sign
Finally apply the function and create a new column in the DataFrame:
df['sign'] = df.apply(signo, axis=1)
print(df)
Output:
birth_month birth_day sign
0 2 24 pisces
1 10 13 libra
2 6 13 gemini
3 7 6 cancer
4 5 9 taurus
5 1 25 aquarius
6 4 19 aries
7 8 12 leo
8 1 29 aquarius
9 4 25 taurus
I am assuming when you say table, you mean python dataframe.
You can iterate across each row using iterrows method
import pandas as pd
data = [{'month': 1, 'day': 10}, {'month': 4, 'day': 11},{'month': 5, 'day': 17},{'month': 11, 'day': 20}]
df = pd.DataFrame(data)
for index, row in df.iterrows():
month = row['month']
day = row['day']
And rest follows the logic to convert into zodiac signs
This question already has answers here:
How to get the last day of the month?
(44 answers)
Closed 4 years ago.
I have made a program that prints the each date of year. Is it possible to add a counter that will allow to limit the printable dates? I would print for example every 7 days. Thanks for any advice.
The original code below.
def main():
for month in range(1, 13):
daymax = 32
if month == 2:
daymax = 29
elif month == 4:
daymax = 31
elif month == 6:
daymax = 31
elif month == 9:
daymax = 31
elif month == 11:
daymax = 31
for day in range(1, daymax):
print(day,".", month,".", sep="")
main()
Just use another counter variable, and check if it's a multiple of 7.
def main():
counter = 0
for month in range(1, 13):
daymax = 32
if month == 2:
daymax = 29
elif month == 4:
daymax = 31
elif month == 6:
daymax = 31
elif month == 9:
daymax = 31
elif month == 11:
daymax = 31
for day in range(1, daymax):
if counter % 7 == 0:
print(day,".", month,".", sep="")
counter += 1
if day % 7 == 0
that should work. Try it.
2001-10-18
I want to calculate weekday e.g. Monday, Tuesday from the date given above. is it possible in python?
Here is one way to do this:
dt = '2001-10-18'
year, month, day = (int(x) for x in dt.split('-'))
answer = datetime.date(year, month, day).weekday()
There is the weekday() and isoweekday() methods for datetime objects.
Python doc
Here's what I have that got me if a leap year and also days in a given month (accounts for leap years). Finding out a specific day of the week, that I'm also stuck on.
def is_year_leap(year):
if (year & 4) == 0:
return True
if (year % 100) == 0:
return False
if (year % 400) == 0:
return True
return False
def days_in_month(year, month):
if month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12:
return 31
if month == 2:
if is_year_leap(year):
return 29
else:
return 28
if month == 4 or month == 6 or month == 9 or month == 11:
return 31