Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Nested if Statement help
#1
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')
Reply
#2
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.
Reply
#3
Not only can you do >= but also <=, !=, is, and is not.

https://docs.python.org/3/library/stdtyp...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')
Reply
#4
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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  must the if statement in the following tutorial be nested? hsunteik 3 6,097 Dec-24-2016, 11:48 AM
Last Post: Yoriz

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020
This forum uses Lukasz Tkacz MyBB addons.
Forum use Krzysztof "Supryk" Supryczynski addons.