Michael
Michael

Reputation: 16142

Return a Boolean instead of a string containing True or False in Python

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.

Upvotes: 1

Views: 11062

Answers (5)

Marcellinov
Marcellinov

Reputation: 301

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' 

Upvotes: 0

Stephan
Stephan

Reputation: 18001

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')

Upvotes: 1

Óscar López
Óscar López

Reputation: 236112

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, ().

Upvotes: 7

Alok Agarwal
Alok Agarwal

Reputation: 3099

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

Upvotes: 0

Noel Evans
Noel Evans

Reputation: 8536

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')

Upvotes: 2

Related Questions