10 методов для условных операторов в Python: объяснено на примерах

Вот некоторые часто используемые методы Python для условных операторов, использующих if-else:

  1. Простой оператор if-else:

    if condition:
       # code to execute if condition is true
    else:
       # code to execute if condition is false
  2. Вложенный оператор if-else:

    if condition1:
       # code to execute if condition1 is true
    elif condition2:
       # code to execute if condition1 is false and condition2 is true
    else:
       # code to execute if both condition1 and condition2 are false
  3. Трнарный оператор:

    value = true_value if condition else false_value
  4. Несколько условий:

    if condition1 and condition2:
       # code to execute if both condition1 and condition2 are true
    if condition1 or condition2:
       # code to execute if either condition1 or condition2 is true
  5. Цепочечные сравнения:

    if min_value < x < max_value:
       # code to execute if x is between min_value and max_value
  6. Использование оператора «in»:

    if item in my_list:
       # code to execute if item is present in my_list
  7. Использование оператора «не»:

    if not condition:
       # code to execute if condition is false
  8. Использование оператора is для сравнения объектов:

    if obj1 is obj2:
       # code to execute if obj1 and obj2 refer to the same object
  9. Использование функции isinstance():

    if isinstance(obj, type):
       # code to execute if obj is an instance of the given type
  10. Использование else в циклах:

    for item in my_list:
        if condition:
            # code to execute if condition is true
            break
    else:
        # code to execute if condition is false for all items in my_list