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 defined

see try except else NameError

If boolean is True or False see Getting Started with Booleans
If the foo variable or list is empty

if foo == "":

or

if len(foo) == 0:

If foo variable equals the bar variable

if foo == bar:

If foo variable does not equal the bar variable

if foo != bar:

Greater than

if foo > 12345:

Less than

if foo < 12345:

Greater than or equal to

if foo >= 12345:

Less than or equal to

if foo <= 12345:

If file exists

import os.path

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

If file does not exist

import os.path

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

If a variable does or does not contain

see re.match

If list contains

see if string in list

if list does not contain see if string in list
If the foo variable begins with Hello

import re

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 15193c in the box below so that we can be sure you are a human.