Python Forum
Nested Conditionals - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Nested Conditionals (/thread-34386.html)



Nested Conditionals - shen123 - Jul-27-2021

Hi All Big Grin

I am new to python. I am doing this tutorial on nested conditions coding however I am stuck. I appreciate some help with it.

if already_fed:
    print('Already fed!')
else:
    if animal == 'Lion':
        print('Meat')
    elif animal == 'Zebra':
        print('Grass')
    else:
        print('Water')
I want to set already_fed to False and animal to 'Warthog' so that "Water" is printed to the terminal. i always ended with result as already fed.


RE: Nested Conditionals - eddywinch82 - Jul-27-2021

Hi shen123,

the following worked for me, is this the type of thing, you were thinking of ? :-

animal = ['Lion', 'Zebra', 'Warthog', 'Elephant', 'Tiger', 'Hyena']

animal = 'Warthog'

if animal == 'Lion':
        print('Meat')
elif animal == 'Zebra':
        print('Grass')
elif animal == 'Warthog':
        print('Water')
elif animal in ['Elephant', 'Tiger', 'Hyena']:
    print('Already fed!')
else:
    print('Animal not listed')

print()
If not, could you post the Full Code you have ?

Best Regards

Eddie Winch


RE: Nested Conditionals - menator01 - Jul-28-2021

What is already_fed? Guessing it's a variable set to True.
Here is one way using a dict

#! /usr/bin/env python3

animals = {
'Lion': ('meat', True),
'Zebra': ('grass', True),
}

animals['Warthog'] = ('grain', False)

for animal, already_fed in animals.items():
    if already_fed[1]:
        print(f'{animal} has been fed {already_fed[0]}')
    else:
        print(f'{animal} has not been fed. {animal} needs water')
Output:
Lion has been fed meat Zebra has been fed grass Warthog has not been fed. Warthog needs water



RE: Nested Conditionals - Yoriz - Jul-28-2021

Setting already_fed to False and animal to 'Warthog', "Water" is printed, I'm not sure how you ended with result as 'Already fed!'.
already_fed = False
animal = 'Warthog'

if already_fed:
    print('Already fed!')
else:
    if animal == 'Lion':
        print('Meat')
    elif animal == 'Zebra':
        print('Grass')
    else:
        print('Water')
Output:
Water