Python

Python Menu

Python Conditions

Python supports the usual logical conditions from mathematics:

  • Equals: a == b
  • Not Equals: a != b
  • Less than: a < b
  • Less than or equal to: a <= b
  • Greater than: a > b
  • Greater than or equal to: a >= b

These conditions can be used in several ways, most commonly in "if statements" and loops.

x = 2 print(x == 2) # prints out True print(x == 3) # prints out False print(x < 3) # prints out True

Boolean operators

The "and" and "or" boolean operators allow building complex boolean expressions.

name = "John" age = 23 if name == "John" and age == 23: print("Your name is John, and you are also 23 years old.") if name == "John" or name == "Rick": print("Your name is either John or Rick.")

The "in" operator could be used to check if a specified object exists within an iterable object container, such as a list:

name = "John" age = 23 if name in ["John", "Rick"]: print("Your name is either John or Rick.")

A statement is evaluated as true if one of the following is correct:

  • The "True" boolean variable is given, or calculated using an expression, such as an arithmetic comparison.
  • An object which is not considered "empty" is passed.

Here are some examples for objects which are considered as empty:

  • An empty string: ""
  • An empty list: []
  • The number zero: 0
  • The false boolean variable: False

The 'is' operator

Unlike the double equals operator "==", the "is" operator does not match the values of the variables, but the instances themselves.

x = [1,2,3] y = [1,2,3] print(x == y) print(x is y)

The "not" operator

print(not False) # Prints out True print((not False) == (False)) # Prints out False

Exercise

Change the variables in the first section, so that each if statement resolves as True.

# change this code number = 10 second_number = 10 first_array = [] second_array = [1,2,3]
if number > 15: print("1")
if first_array: print("2")
if len(second_array) == 2: print("3")
if len(first_array) + len(second_array) == 5: print("4")
if first_array and first_array[0] == 1: print("5")
if not second_number: print("6")
# change this code number = 16 second_number = 0 first_array = [1,2,3] second_array = [1,2]
if number > 15: print("1")
if first_array: print("2")
if len(second_array) == 2: print("3")
if len(first_array) + len(second_array) == 5: print("4")
if first_array and first_array[0] == 1: print("5")
if not second_number: print("6")
test_output_contains("1") test_output_contains("2") test_output_contains("3") test_output_contains("4") test_output_contains("5") test_output_contains("6") success_msg("Excellent!")

Introduction

Python Basics

Python Advance

Data Science Python Tutorials

Python Functions and Methods