r/learnpython • u/vtuti • Oct 13 '24
My if statement doesnt work
Can anyone find any errors here? Im new to python so I dont know what I did wrong as every answer is responded with “it has 30 days”
month = input("Enter a month: ") month = month.upper() print(month) if month == "SEPTEMBER"or"APRIL"or"JUNE"or"NOVEMBER": print("it has 30 days") elif month == "JANUARY"or"MARCH"or"MAY"or"JULY"or"DECEMBER"or"AUGUST": print("it has 31 days") elif month == "FEBRUARY": print("it has 28 days, but 29 on a leap year") else: print("That's not a month")
This is what the output is like Enter a month: a A It has 30 days
10
u/Critical_Concert_689 Oct 13 '24
format your code for Reddit. 4 spaces in front of each line or just use your IDE to add a tab to the entire code...
month = input("Enter a month: ")
month = month.upper()
print(month)
if month == "SEPTEMBER"or"APRIL"or"JUNE"or"NOVEMBER":
print("it has 30 days")
elif month == "JANUARY"or"MARCH"or"MAY"or"JULY"or"DECEMBER"or"AUGUST":
print("it has 31 days")
elif month == "FEBRUARY":
print("it has 28 days, but 29 on a leap year")
else: print("That's not a month")Significantly improves readability for yourself and everyone helping you
4
u/ste_wilko Oct 13 '24
A tidier way would be to use lists and the in() operator
longMonth = ["JANUARY", "MARCH", "MAY", "JULY", "AUGUST", "OCTOBER", "DECEMBER"]
shortMonth = ["APRIL", "JUNE", "SEPTEMBER", "NOVEMBER"]
month = input("Enter a month: ").upper()
if month in longMonth:
print(f"{month} has 31 days")
elif month in shortMonth:
print(f"{month} has 30days")
elif month == "FEBRUARY":
print(f"{month} has 28 days (and 29 days in a leap year)")
else:
print(f"{month} is not a month")
1
u/FoolsSeldom Oct 13 '24
Why lists rather than tuples? Don't see a benefit.
4
u/nekokattt Oct 13 '24
Sets are the most appropriate thing though, not tuples or lists. Use of either implies that order is somehow important, and that the ability to hold duplicate values is somehow important.
As for the argument of lists versus tuples, it doesn't make any difference unless you are explicitly trying to mutate them, at which point that is a problem with your code, not the collections themselves. Using one datatype over another just because it helps you to write less dodgy code to me is more of an issue with how you are writing the code than the datatype itself, which has specific use cases.
For beginners, this can also confuse them into thinking tuples make everything readonly when they don't, they only apply on a shallow level.
Lists are "academically" more correct here than tuples because tuples are designed to be a holder of bits of data that relate to a single entity, and their size is expected to be consistent as a result. Lists are designed as a way of representing multiple unrelated things, such as possible values in a domain of elements. You can tell that this is the case by how typing.Tuple differs to typing.List.
The concept of lists versus tuples really roots itself in things like database theory. Your table would be a list of records. Your records would be tuples. That is also why namedtuple exists in Python in the way it does.
Abusing the mutability and immutability aspects IMO is not fantastic unless you already have very haphazard code. I don't think it is a solution to that either. It may prevent beginners shooting themselves in the foot initially but I don't feel like it lends itself to writing consistent code further down the line.
In a production codebase, I'd much rather see...
SHORT_MONTHS: Sequence[str] = ["APRIL", "JUNE", ...]...rather than...
SHORT_MONTHS = ("APRIL", "JUNE", ...)...purely because it shows intent more clearly. If I see a list, I know that I cannot make assumptions about the size of it before runtime. With a tuple, the size is expected to match the things stored in it, and changing the size results in the meaning being different (for example, destructuring).
1
2
u/pm4tt_ Oct 13 '24
Are 24 bytes and 1ns a benefit though ?No
0
u/FoolsSeldom Oct 13 '24
Not about performance so much as most appropriate data structures for beginners to learn.
EDIT: However, u/nekokattt has provided an excellent breakdown of the pros-and-cons of the options in this case.
2
u/pm4tt_ Oct 13 '24
You talked about "benefits" between tuples and lists, and I told you in practice there are none in this specific case. Neither for one nor other.
1
u/FoolsSeldom Oct 13 '24
I asked, and you focused on performance. Thank you for your sharing that information.
As I said, u/nekokattt provided more information that provided a broader perspective that I found very beneficial.
I would have gone for a
listas well but have previously been advised I should have used atupleso was interested in alternative views.1
u/nekokattt Oct 13 '24
Still worth noting a set that is hidden as a container is really the best thing to be using here. The set implies it is just a "bag" of unique things and hiding behind a Container as the interface means you're hiding how it actually works in practise.
That way, you can change it later and be happy knowing nothing will catch fire.
1
u/FoolsSeldom Oct 13 '24
Good point. It would be easy to jump to the assumption that order would be important because this is data that we often use in such a context.
I also would have usually used a
listbut have been challenged previously on not using atupleso was interested on hearing alternative views without poisoning the well.I don't use
setas often as I probably should, and there are a lot of benefits to it.
3
u/FoolsSeldom Oct 13 '24
You have made a mistake that is such a common error. there's an entry in the FAQ for this subreddit. Variable is One of Two Choices?.
2
u/nekokattt Oct 13 '24 edited Oct 13 '24
I reserve the point that the way Python's conditional operators work is overly confusing.
I personally think that or-ing a bool on the left hand side with a non bool on the right hand side for builtin types should raise a warning at runtime. In the tiny number of cases where you would want to say bool.__or__(str) or bool.__or__(list) or similar, it should be cast explicitly to bool to make it clear that it is the intention.
While it leads to more verbose code, I honestly think the way languages like Java restrict the use of conditions to only be boolean values is far more sensible in terms of reducing the number of ways to write confusing expressions.
if ("APRIL".equals(month) || "JUNE".equals(month) || ...) {
...
}In OPs case, a match statement would be a better way of dealing with this:
match month:
case "APRIL" | "JUNE" | "SEPTEMBER" | "NOVEMBER":
...
case "FEBRUARY":
...
case _:
...You could also use a dict, but I'd argue that this is logic rather than data, so using logic to represent it is more appropriate.
1
u/wbeater Oct 13 '24
if month == "SEPTEMBER" or "APRIL"and or or in an if statement do not extend the condition, they add a new condition.
It must say:
if month == "SEPTEMBER" or month == "APRIL1
Oct 13 '24
I had the same problem earlier.
Your mistake is in using the "or" operator or is used to separate different conditions. everytime you use it you should write a whole new condition.
in this case, take the line
if month == "SEPTEMBER"or"APRIL"or"JUNE"or"NOVEMBER": print("it has 30 days") ^^^
after "or" you have just written "APRIL", the python interpreter is taking "APRIL" as one condition and not checking whether month is equal to september or april or june or november.
the correct version would be
if month == "SEPTEMBER"or month == "APRIL"or month == "JUNE"or month == "NOVEMBER": print("it has 30 days") in this version after or there is a condition, in your code there is a string after "or". In python, a string alone as a condition just checks whether or not the string has characters. it returns true if it has any characters. Thus, your code was probably outputting "it has 30 days"
Even this isnt the fully corrected version of the code. it would look more like this if you know how to use "in".
if month in ["SEPTEMBER", "APRIL", "JUNE", "NOVEMBER"]:
print("it has 30 days") this checks whether the month inputted by the user is in the list with those months which have 30 days. if it is, which we will assume for this case as true, it will return True, making the condition true.
also i request you to write code properly when you are posting on reddit use code blocks or tabs or 3 backticks when posting code.
Thank you
0
u/Diapolo10 I write code for a living -- https://github.com/Diapolo10 Oct 13 '24
The others already beat me to explaining what happened, but I still want to suggest some improvements.
import calendar
import locale
# You presumably want English months, this makes
# sure of that; remove if you prefer localised names
locale.setlocale(locale.LC_ALL, 'en_GB')
MONTHS = list(map(str.upper, calendar.month_name))[1:]
month = input("Enter a month: ").strip().upper()
if month not in MONTHS:
print("That's not a month")
raise SystemExit
month_num = MONTHS.index(month) + 1
if month_num == 2:
print("it has 28 days, but 29 on a leap year")
elif month_num in {4, 6, 9, 11}:
print("it has 30 days")
else:
print("it has 31 days")This way you don't need to spell out the months yourself, there's a lot less typing involved, and it's trivial to add support for localised month names if you wish.
17
u/ssnoyes Oct 13 '24 edited Oct 13 '24
month == "SEPTEMBER" or "APRIL"does not mean the same thing asmonth == "SEPTEMBER" or month == "APRIL"The first one means: check if the month is September. If it is, return True. If not, then return the string "APRIL". Any non-empty string is "truthy" in an
ifstatement. So that first condition is always True.You probably would benefit from learning about the
in()operator.