'How to make a simple Boolean condition

What am I doing wrong with my code?

I'm trying to get it so when I run happy_home it comes out true when there is at least one cat and no dogs.

cat_count = 2
dog_count = 0

if cat_count > 0:
    has_cat = True

if dog_count > 0:
    has_dog = False

happy_home = (has_cat and has_dog)

happy_home


Solution 1:[1]

Why would you have has_cat and has_dog attributes with two if statements? You can simply check both of them at the same if statement. Please check out the code at below:

#!/bin/python3

cat_count = 2
dog_count = 0

happy_home = False

if cat_count > 0 and dog_count == 0:
    happy_home = True

print(happy_home)

Solution 2:[2]

You really only need this.

cat_count = 2
dog_count = 0

print(cat_count > 0 and dog_count == 0)

Solution 3:[3]

The originally posted code does not define the has_dog variable, as shown by the following error message:

python

Python 2.7.10 (default, Jul 15 2017, 17:16:57)
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.31)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
    >>> cat_count = 2
    >>> dog_count = 0
    >>>
    >>> if cat_count > 0:
    ...     has_cat = True
    ...
    >>> if dog_count > 0:
    ...     has_dog = False
    ...
    >>> happy_home = (has_cat and has_dog)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    NameError: name 'has_dog' is not defined
    >>>

Here is the fixed code:

cat_count = 2
dog_count = 0

if cat_count > 0:
    has_cat = True
else:
    has_cat = False


if dog_count > 0:
    has_dog = False
else:
    has_dog = True


happy_home = (has_cat and has_dog)

happy_home

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 BGForDevelopers
Solution 2
Solution 3 Peter Mortensen