I have a small problem with True or False Boolean.
I have Defined a procedure weekend which takes a string as its input, and returns the Boolean True if 'Saturday' or 'Sunday' and False otherwise.
Here is my weekend function:
def weekend(day):
if day == 'Saturday' or day == 'Sunday':
return "True"
else:
return "False"
Here is my output:
>>>print weekend('Monday')
False
>>>print weekend('Saturday')
True
>>>print weekend('July')
False
But as you see in my code, I'm returning a string BUT I want to return a Boolean True or False.
How can I do that?
Thanks.
5 Answers 5
Try this:
def weekend(day):
if day == 'Saturday' or day == 'Sunday':
return True
else:
return False
Or this:
def weekend(day):
return day == 'Saturday' or day == 'Sunday'
Or even simpler:
def weekend(day):
return day in ('Saturday', 'Sunday')
Anyway: in Python the boolean values are True and False, without quotes - but also know that there exist several falsy values - that is, values that behave exactly like False if used in a condition. For example: "", [], None, {}, 0, ().
1 Comment
0. is also falsy (not to mention 0j and 0L).This is the shortest way to write the function and output a boolean
def weekend(day):
return day == 'Saturday' or day == 'Sunday'
or
def weekend(day):
return day in ('Saturday', 'Sunday')
Comments
Your problem was using " marks around True, remove those and it will work. Here are some more pythonic ways to write this method:
def weekend(day):
if day.lower() in ('saturday', 'sunday'):
return True
else:
return False
Using .lower() when checking is a good way to ignore case. You can also use the in statement to see if the string is found in a list of strings
Here is a super short way
def weekend(day):
return day.lower() in ('saturday', 'sunday')
Comments
def weekend(day):
if day == 'Saturday' or day == 'Sunday':
return True
else:
return False
you are doing return "True" and return "False" which make it a string rather than Boolean
Comments
If you want to return a Boolean instead of a String just get rid of the quotes '' around True and False.
Try This:
def weekend(day):
""" Return True if day is Saturday or Sunday otherwise False."""
return day in ('saturday', 'sunday'):
or as the others before me have said:
def weekend(day):
""" Return True if day is Saturday or Sunday otherwise False."""
return day == 'Saturday' or day == 'Sunday'
"True"/"False".