If Statements

In the heart of programming logic, we have the if statement in Python. The if statement is a conditional that, when it is satisfied, activates some part of code. Often partnered with the if statement are else if and else. However, Python’s else if is shortened into elif. If statements are generally coupled with variables to produce more dynamic content. Let’s cut to an example really quick.

Example

Result

else

So, we have the variable a that equals twenty. Now, we run it through our if statement that checks to see if a is greater than or equal to 22. It isn’t. So, we skip past the inner print statement and continue to the elif statement. This conditional checks if a is greater than or equal to 21. It isn’t either, which brings us to the final leg of our expanded if statement. The else is the catch all, which means if the previous conditionals are not satisfied, we will run the code inside it. So, we run the print(“else”), and we see in the results, the string else.

The If Syntax

The most important thing you might have missed in the example above is how Python’s syntax is a lot cleaner than other languages. However, this also means it is very picky and tends to bite beginners with errors. After every conditional we have a colon. Next, you must proceed to a new line with 4 spaces to tell Python you only want this code with 4 spaces to be run when the previous conditional is satisfied. Ok, well it doesn’t have to be 4 spaces, but you must be consistent with the spaces you use to indent. You can use 3 every time if you want, but 4 is kind of a standard. Also, if you wanted to run more than one statement after the conditional is satisfied, you must have a new line with the same number of spaces before the next statement.

If you enjoyed this resource, support me by sharing this page with others.
Share on Facebook
Facebook
Share on Google+
Google+
Share on StumbleUpon
StumbleUpon
Digg this
Digg
Tweet about this on Twitter
Twitter
Share on Reddit
Reddit

Leave a Comment

  1. @Will H my guess is you use idle ? then try this : IDLE > options > General > at startup Open Edit window .
    restart idle and you can fill in the example. F5 to run the module

  2. Dan c, mine was like this
    >>> if a >=22:
    print ("if")
    elif a >= 21:

    SyntaxError: invalid syntax

    then I changed it to this and it worked:

    >>> if a >=22: print ("if")
    elif a >= 21: print ("elif")

  3. worked perfectly for me and got a little creative 😉

    print "type a number greater than 25"
    a =raw_input(":")

    if a > 25:
    print("good job")
    elif a == 25:
    print("that’s not greater")
    elif a < 25:
    print("try again")
    else:
    print("input a number please")

  4. ”’
    This are my code
    that I tried. It’s 2:27 AM and I needed something to
    keep me awake, hence the subject of my code. 🙂
    ”’

    sex = 55
    if sex >= 100:
    print(‘Too many!’)
    elif sex <= 1:
    print(‘Get laid!’)
    elif sex == 20:
    print(‘Just right.’)
    else:
    print(‘else’)

  5. c=input("Enter Your Marks:")
    c=int(c)
    if c>50:
    print("GooD")
    elif c<50:
    print("BaD!")
    else:
    print("Enter Your marks correctly")

  6. works like a charm:
    >>> x= 55
    >>> if x >=56:
    print (‘too high’)
    elif x <= 54:
    print (‘too low’)
    elif x <= 33:
    print (‘Im flattered’)
    elif x >= 80:
    print (‘your taking the piss’)
    else:
    print (‘you guessed correct’)

    answer you guessed correct

  7. I guess the only suggestion I could come up with would be a color coded shell. It would be nice to see but, not absolutely needed.

  8. This is a great site so far. It seems to teach Python at a good, slow rate. I’m also learning Java/Android at the same time and it’s just not clicking yet. I know this site is for web site development, but maybe it could pick up some mobile development in the future.

  9. Very interesting to work with the conditional if statement. It’s a great step to understand how it is working with Python.

  10. that was quite good but i have a little question, what if i wanted to execute this as a program.
    How can i start an input for the user?
    regards!

  11. Hello there guys, i am trying to learn python and this is honestly really helping me. Thank you very much 😀

  12. Darren, am new here but I saw u made a mistake, if I am write; Let’s see if am right:
    x= 55
    if x >=56:
    print (‘too high’)
    elif x <= 54: <—— first rule
    print (‘too low’)
    elif x <= 33: <—— here it will always take the first rule you`ve made where x<=54 and
    print (‘Im flattered’) will never print this even X is lower than 33 cause is also lower than 54!
    elif x >= 80:
    print (‘your taking the piss’)
    else:
    print (‘you guessed correct’)

  13. While running an "If Statement" in Python and following these directions I was getting an error "SyntaxError: multiple statements found while compiling a single statement" if this is happening to you, heres what you need to do.

  14. While running an "If Statement" in Python and following these directions I was getting an error "SyntaxError: multiple statements found while compiling a single statement" if this is happening to you, here’s what you need to do. 1. open up your IDLE (Python GUI) write your code 2. Go to "Run" click "Run module. 3. save file under folder scripts 4. it should run it successfully. Copying and pasting to modules doesn’t work like you think it would.

  15. I do this in IDLE

    if a>=22:
    print”if”
    elif a>=21:

    and I get this error

    File ““, line 3
    elif a>=21:
    ^
    IndentationError: unindent does not match any outer indentation level
    please help me understand where I am going wrong

  16. HEY, just made an account to say thanks. I never new why I was getting a synthax error every time I made an IF ELSE statement, after I looked at you code I realized that after you finish an IF statement, and move onto the else, you have to hit space again THEN write the else. I know other OOP languages, but this never occurred to me that in PY you need a space. MY noob ass teacher never even mentioned this, so I was stuck on my assignment until now. Thanks again.

  17. When i type
    >>> a = 20
    >>> if a >=22:
    print(“if”)
    elif a >= 21:
    As soon as hit enter after the 21:
    I get an error
    SyntaxError: unindent does not match any outer indentation level
    I’m using 3.2

  18. blueBerryHeight = 10
    if blueBerryHeight >= 20:
    print(“Adult”)
    elif blueBerryHeight >= 25:
    print(“Aged”)
    else:
    print(“sapling”)

    #My outcomes don’t make sense lol, but this programming stuff is fun 😉

  19. i have been programming in C and C++. I jus love the simplicity of Python in terms of syntax. I will be going a long way with this. #addictive

  20. I’m using IDLE Python 3.2, I typed in the exact code shown in the tutorial. After typing “elif a >= 21:” it immediately tells me I’ve made a syntax error.

    How do I fix this? Do I need to close of the original ‘if’ statement somehow?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.