• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
PythonForBeginners.com

PythonForBeginners.com

Learn By Example

  • Home
  • Learn Python
    • Python Tutorial
  • Categories
    • Basics
    • Lists
    • Dictionary
    • Code Snippets
    • Comments
    • Modules
    • API
    • Beautiful Soup
    • Cheatsheet
    • Games
    • Loops
  • Python Courses
    • Python 3 For Beginners
You are here: Home / Basics / Python If…Elif…Else Statement

Python If…Elif…Else Statement

Author: PFB Staff Writer
Last Updated: May 22, 2020

What are Conditions?


Conditions tests if a something is True or False, and it uses Boolean values
(type bool) to check that. 

You see that conditions are either True or False (with no quotes!).
2 < 5
3 > 7
x = 11
x > 10
2 * x < x
type(True)

The results of these tests decides what happens next. 

When to use a Condition?


If you want to check if the user typed in the right word or to see if a number
is higher / lower than 100. 

Syntax Explained


First, lets look at Pythons if statement code block. 

Rememeber, to indicate a block of code in Python, you must indent each line
of the block by the same amount.
If ...else

    if condition:
        statements

    elif condition:
 statements

    else:
 statements

If, elif and else are keywords in Python.

A condition is a test for something ( is x less than y, is x == y etc. )

The colon (:) at the end of the if line is required. 

Statements are instructions to follow if the condition is true. 

These statements must be indented and is only being run when the if condition
is met. 

Typical conditions are: xy, x<=y, x>=y, x!=y and x==y. 

If you want more choices, you will have to include at least two conditions . 

The "else" MUST be preceded by an if test and will ONLY run when condition of
the if statement is NOT met. 

else will run if all others fail. 

If you only have two choices in your construction, use if ..else 

If there are more than two options, use if ..elif ..else.. that will make
it easier to read

elif is short for "else if"

Conditional Tests


An If statement sets an condition with one or more if statement that will be
used when a condition is met.

There can be zero or more elif parts, and the else part is optional. 

The keyword 'elif' is short for 'else if', and is useful to avoid excessive
indentation.

An if ... elif ... elif ... sequence is a substitute for the switch or case
statements found in other languages.
x = raw_input("What is the time?")

if x < 10:
 print "Good morning"

elif x<12: 
 print "Soon time for lunch"

elif x<18: 
  print "Good day"

elif x<22: 
 print "Good evening"

else: 
  print "Good night"

You can also use it to control that only specified users can login to a system.
# Allowed users to login
allowed_users = ['bill', 'steve']

# Get the username from a prompt
username = raw_input("What is your login? :  ")
 
# Control if the user belongs to allowed_users

if username in allowed_users:
    print "Access granted"

else:
    print "Access denied"

Python If statement Code Block


To get an easy overview of Pythons if statement code block
if :
    [do something]
    ....
    ....
elif [another statement is true]:
    [do something else]
    ....
    ....
else:
    [do another thing]
    ....
    ....

For more reading, please see Python's official documentation. 

Related

Recommended Python Training

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

Enroll Now

Filed Under: Basics Author: PFB Staff Writer

More Python Topics

API Argv Basics Beautiful Soup Cheatsheet Code Code Snippets Command Line Comments Concatenation crawler Data Structures Data Types deque Development Dictionary Dictionary Data Structure In Python Error Handling Exceptions Filehandling Files Functions Games GUI Json Lists Loops Mechanzie Modules Modules In Python Mysql OS pip Pyspark Python Python On The Web Python Strings Queue Requests Scraping Scripts Split Strings System & OS urllib2

Primary Sidebar

Menu

  • Basics
  • Cheatsheet
  • Code Snippets
  • Development
  • Dictionary
  • Error Handling
  • Lists
  • Loops
  • Modules
  • Scripts
  • Strings
  • System & OS
  • Web

Get Our Free Guide To Learning Python

Most Popular Content

  • Reading and Writing Files in Python
  • Python Dictionary – How To Create Dictionaries In Python
  • How to use Split in Python
  • Python String Concatenation and Formatting
  • List Comprehension in Python
  • How to Use sys.argv in Python?
  • How to use comments in Python
  • Try and Except in Python

Recent Posts

  • Count Rows With Null Values in PySpark
  • PySpark OrderBy One or Multiple Columns
  • Select Rows with Null values in PySpark
  • PySpark Count Distinct Values in One or Multiple Columns
  • PySpark Filter Rows in a DataFrame by Condition

Copyright © 2012–2025 · PythonForBeginners.com

  • Home
  • Contact Us
  • Privacy Policy
  • Write For Us