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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.