Python Forum
Nested if Statement help - 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 if Statement help (/thread-32579.html)



Nested if Statement help - olliej - Feb-19-2021

Hello All,

I understand this is probably a very basic question but I would appreciate any help.

I am working on the logic for some code and created the script below to figure out the syntax. The code show below works fine using different values for the variables and I think it is self explanatory.

I am trying to insert a condition in the "if g > h" block to also check if "g == h" and generate an output using a print statement. I have tried different structures but I cannot seem to get it to work.

Could someone please provide the correct syntax to add a condition in the "if g > h" block to also check if "g == h" and generate an output using a print statement?

Thank you in advance.
Oliver

a = 4
b = 5
c = 6
d = 5
e = 6
f = 5
g = 6
h = 5

if a > b: 
   print ('a is greater than b')

elif a == b: 
    if c > d: 

      if e > f: 
         print ('Yes')
      else:
         print('No')


      if g > h: 
         print ('True')
                            # <<<--------- Need to insert a condition here [when g==h / print('Neutral')]
      else:
         print('False')

else:
    print ('a not greater than b')



RE: Nested if Statement help - BashBedlam - Feb-19-2021

if g > h : will only execute that code block if g is greater than h so if you test if g == h : inside of that block, it will always fail because g had to be not equal to h in order to get there.
You can use :
if g >= h :
or put your test for equality outside of that code block, depending on the logic that you are looking for.


RE: Nested if Statement help - deanhystad - Feb-19-2021

Not only can you do >= but also <=, !=, is, and is not.

https://docs.python.org/3/library/stdtypes.html?highlight=comparison

You can also combine two comparisons:
if 3 <= x < 7:
Which is the same as:
if x >= 3 and x < 7:
But looking at your original question I don't think you want ">=". You want separate actions for g < h, g > h and g == h. You already do this with a and b. You have one action if a < b, a different action if a == b, and a third action if a > b. What I think you want for g and h is:
if g > h:
    print('True'):
elif g < h:
    print('False')
else:
    print('Neutral')



RE: Nested if Statement help - olliej - Feb-19-2021

Thank you everyone for the help.....

@deanhystad - your solution worked ......

I am almost positive I had tried the "elif" statement and I believe I got a syntax error... anyhow it works now.

Thanks