DEV Community

Cover image for Python If-Else Condition
pavanbaddi
pavanbaddi

Posted on • Edited on • Originally published at thecodelearners.com

3

Python If-Else Condition

Conditioning is the most basic operator in any programming language. Python provides some of the built-in additional tools which we'll be learning in the section of our python tutorial.

Example: To create a simple if statement.

    a=10 
    b=5

    if a > b:
        print("Yes the value of a is greater than b value.") 

    #PYTHON OUTPUT
    Yes the value of a is greater than b value.

If Else Conditional Statement

Example

    a=10
    b=11

    if a >= b:
        print("Yes the value of a is greater than b value.") 
    else:
        print("Yes the value of b is greater than a value.") 

    #PYTHON OUTPUT
    Yes the value of b is greater than a value.

Elif Conditional Statement

    user_role = 'STAFF'

    if user_role == 'ADMIN':
        print("Welcome Administrator")
    elif user_role == 'STAFF':
        print("Welcome Staff")

    #PYTHON OUTPUT
    Welcome Staff

Nested if-elif in python

Example: To check greater of 3 nos.

    a=10
    b=11
    c=9

    if a > b:
        if a > c:
        print('A is greater')
        else:
        print('C is greater')
    elif b > c:
        print("B is greater")
    else:
        print('C is greater')

    #PYTHON OUTPUT
    B is greater

Example: Short-Hand If Condition

    a=12
    b=14

    if b>a: print(b)

    #PYTHON OUTPUT
    14

Example: Short-Hand if-else condition

    a=15
    b=16

    print(a) if a>b else print(b)

    #PYTHON OUTPUT
    16

Example: Multiple conditioning use AND OR operator.

    a=35
    b=25
    c=33    
    if a>b and a>c:
        print('A is greater than B and C')
    // PYTHON OUTPUT
    A is greater than B and C
    a=30
    b=25
    c=33    
    if a>b or a>c:
        print('Because A is greater than B') #if any one condition is True
    // PYTHON OUTPUT
    Because A is greater than B

Top Python Posts

This article is taken from the code learners python conditional statements

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (2)

Collapse
 
waylonwalker profile image
Waylon Walker

quick DEV tip. Put the language after your ` backticks to get nice syntax highlighting.

`\ python

try it out

print("hello world")
Collapse
 
pavanbaddi profile image
pavanbaddi

Thank you for suggesting.

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay