Bootstrap FreeKB - Python (Scripting) - if elif else statements
Python (Scripting) - if elif else statements

Updated:   |  Python (Scripting) articles

An if statement in Python has the following structure.

if <condition> :
  <do something>
elif <condition>:
  <do something>
else:
  <do something>

 

For example.

if foo == "Hello":
  print("foo equals Hello")
elif foo == "World":
  print("foo equals World")
else:
  print("foo does not equal Hello or World")

 

Following are command if statements.

If variable or boolean is definedsee try except else NameError
If boolean is True or Falsesee Getting Started with Booleans
If the foo variable or list is empty

if foo == "":

or

if len(foo) == 0:

If the foo dict is empty

if bool(foo):

or

if len(foo) == 0:

If foo variable equals the bar variableif foo == bar:
If foo variable does not equal the bar variableif foo != bar:
Greater thanif foo > 12345:
Less thanif foo < 12345:
Greater than or equal toif foo >= 12345:
Less than or equal toif foo <= 12345:
If file or directory exists

import os.path

if os.path.exists("/path/to/file.txt"):

If file or directory does not exist

import os.path

if not os.path.exists("/path/to/file.txt"):

If file is empty

import os.path

if os.path.getsize("/path/to/file.txt") == 0:

If a variable does or does not containsee re.match
If list containssee if string in list
if list does not containsee if string in list
If the foo variable begins with Hello

see re.match

if re.match('^Hello', foo):

match every other item (e.g. first item will be if, next item will be else - see this example)if (item % 2):

 

Multiple conditions

Multiple conditions can be evaluated by separating each condition with and or or.

if foo == "Hello" or foo == "World":
  print("foo equals Hello or World")
else :
  print("foo does not equal Hello or World")

 

Or like this, using and.

if foo == "Hello" and bar == "World":
  print("foo equals Hello and bar equals World")
else :
  print("foo does not equal Hello or bar does not equal World")

 

Here is another example.

if foo == "Hello" and (bar == "World" or bar == "Earth"):
  print("foo equals Hello and bar equals World or Earth")
else :
  print("foo does not equal Hello or bar does not equal World or Earth")

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 7f86f1 in the box below so that we can be sure you are a human.