---
# System prepended metadata

title: Conditionals and Recursion

---

# Conditionals and Recursion

## Conditionals

**Boolean Expressions** - either True or False
**Relational operators:**
```python=
x == y # x is equal to y
x != y # x is not equal to y
x > y # x is greater than y
x < y # x is less than y
x >= y # x is greater than or equal to y
x <= y # x is less than or equal to y
```
**Logical Operators**
```python=
x and y
x or y
not x
```

### Conditional Execution
```python=
if condition:
    #code to run
```

### Alternative Execution
```python=
if condition:
    #code to run
else:
    #code to run if condition is not met
```

### Chained Conditionals
```python=
if condition1:
    #code to run
elif condition2: #elif stands for else if
    #code to run
else:
    #fallback
```

> Note! You can nest conditionals


## Recursion

> Concept where a function calls itself preferrably with a base case to prevent memory stack overflow and infinite recursive calls.

```python=
def print_n(s,n):
    if n<=0:
        return
    print(s)
    print_n(s,n-1)
```
This function is a recursive function that prints a string `s` `n` number of times.

### Stack diagram 
![](https://i.imgur.com/9Fp3uOx.png)


## Terms 
**floor division:** An operator, denoted //, that divides two numbers and rounds down (toward negative infinity) to an integer.

**modulus operator:** An operator, denoted with a percent sign (%), that works on integers
and returns the remainder when one number is divided by another.

**boolean expression:** An expression whose value is either True or False.

**relational operator:** One of the operators that compares its operands: ==, !=, >, <, >=, and
<=.

**logical operator:** One of the operators that combines boolean expressions: and, or, and
not.

**conditional statement:** A statement that controls the flow of execution depending on some
condition.

**condition:** The boolean expression in a conditional statement that determines which
branch runs.

**compound statement:** A statement that consists of a header and a body. The header ends
with a colon (:). The body is indented relative to the header.

**branch:** One of the alternative sequences of statements in a conditional statement.

**chained conditional:** A conditional statement with a series of alternative branches.

**nested conditional:** A conditional statement that appears in one of the branches of another
conditional statement.

**return statement:** A statement that causes a function to end immediately and return to the
caller.

**recursion:** The process of calling the function that is currently executing.

**base case:** A conditional branch in a recursive function that does not make a recursive call.

**infinite recursion:** A recursion that doesn’t have a base case, or never reaches it. Eventually, an infinite recursion causes a runtime error.
