CMPE 150

Introduction to Computing

Fall 2021

Created by Gökçe Uludoğan

### Comparison Operators ![](https://www.devopsschool.com/blog/wp-content/uploads/2020/08/relational-operator-in-python.png)
### Logic Operators | Operator | Example | Meaning | |----------|---------|---------------------------------------------------------------------------| | not | not x | True if x is False. False if x is True | | or | x or y | True if either x or y is True. False otherwise | | and | x and y | True if both x and y are True. False otherwise |
### Conditional Statements * Change the order of execution with conditional statements. * `If` * `Elif` * `Else`

if Statement

  • Syntax:
    
    if test_expression:
          statement(s)      
        
  • test_expression: condition
  • If the condition is satisfied, statement(s) is executed.
  • Otherwise, statement(s) is skipped over.
### Example ```python num = int(input()) if num > 0: print(num, "is a positive number.") print("This is always printed.") ``` * For num = 10, the output is: ``` 10 is a positive number. This is always printed. ``` * For num = -3, the output is: ``` This is always printed. ```

if..else Statement

  • Syntax:
    
    if test expression:
        statements of if
    else:
        statements of else 
        
  • test_expression: condition
  • If the condition is satisfied, statement(s) of if is executed.
  • Otherwise, statement(s) of else is executed.
### Example ```python num = int(input()) if num >= 0: print(num, "is positive or zero.") else: print(num, "is negative.") ``` * For num = 10, the output is: ``` 10 is a positive or zero. ``` * For num = -3, the output is: ``` -3 is negative. ```

if..elif..else Statement

  • Syntax:
    
    if test expression:
        statements of if
    elif other test expression:
        statements of elif
    else:
        statements of else 
        
  • elif: stands for else if
  • Allows to check multiple conditions
  • The if block can have multiple elif blocks but only one else block.
#### Example ```python num = int(input()) if num > 0: print("Positive number.") elif num == 0: print("Zero.") else: print("Negative number.") ``` * For num = 10, : ``` Positive number. ``` * For num = -3, : ``` Negative number. ``` * For num = 0, : ``` Zero ```

Nested if Statements

  • Conditional statements can be nested inside one another.
  • num = int(input())
    if num >= 0:
        if num == 0:
            print("Zero.")
        else:
            print("Positive number.")
    else:
        print("Negative number")

Execution

References

  1. https://pythontutor.com/
  2. https://www.programiz.com/python-programming/if-elif-else