Conditionals

Conditionals are often used in data science since you can branch the program. The most frequently used one is the if statement. It works more or less the same as in other programming languages. Here's an example of it:

def is_positive(val):  if val< 0:  print ("It is negative")  elif val> 0:  print ("It is positive")  else:  print ("It is exactly zero!") is_positive(-1) is_positive(1.5) is_positive(0) # Prints: # It is negative # It is positive # It is exactly zero!

The first condition is checked with if. If there are any other conditions, they are defined with elif (this stands for else...if). Finally, the default behavior is handled by else.

Note that elif and else are not essentials.

Get Python Data Science Essentials - Third Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.