Ternary Operators & Codewars
Tags: python, chatgpt, beginners
Published: 2023-08-11 01:28:42

## Ternary Operators

> 
ray: I'm learning about ternary operators in python. I want to return a value based on a condition. How do you use 'return' in this case?

> 
meg: Hey Ray! Ternary operators in Python are a concise way to write conditional expressions. They allow you to return a value based on a condition without using a full if-else statement. The basic syntax of a ternary operator is:

```python
value_if_true if condition else value_if_false
```

> 
You can use the `return` keyword in combination with a ternary operator to directly return a value based on a condition.

---

## Codewars

### Kata
Create a function that takes an integer as an argument and returns "Even" for even numbers or "Odd" for odd numbers.

#### My approach 
```python
def even_or_odd(number):
    return "Even" if number % 2 == 0 else "Odd"
```

The `even_or_odd` function uses a ternary operator to determine whether the input `number` is even or odd, and then immediately returns the corresponding string.

#### Interesting Variation
I thought this approach was pretty cool. I didn't understand what was happening at first.

```python
def even_or_odd(number):
  return ["Even", "Odd"][number % 2]
```
> 
ray: Explain this approach...

> 
meg: Certainly, Ray! The approach you provided is a compact way to achieve the same result as using a ternary operator. This method relies on the fact that Python allows indexing of a list using boolean values (where `False` is equivalent to `0` and `True` is equivalent to `1`). 

Let's break down the code:

1. The function `even_or_odd` takes a single argument, `number`, which is the number you want to check.

2. `number % 2` calculates the remainder when `number` is divided by `2`. If the remainder is `0`, it means the number is even. If the remainder is `1`, it means the number is odd.

3. `["Even", "Odd"]` creates a list containing two elements: `"Even"` at index `0` and `"Odd"` at index `1`.

4. The expression `[number % 2]` is used as an index to this list. If `number % 2` is `0`, it will access the element at index `0` (`"Even"`), and if `number % 2` is `1`, it will access the element at index `1` (`"Odd"`).

5. The value retrieved from the list (either `"Even"` or `"Odd"`) is then immediately returned by the `return` statement.

So, in essence, this approach uses the remainder of the division to index the list of strings, directly returning the appropriate string based on whether the number is even or odd. It's a creative way to achieve the same result as a ternary operator, but it might be less intuitive for readers who are not familiar with this technique.

#### Rank Up Challenge

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Finish the solution so that it returns the sum of all the multiples of 3 or 5 below the number passed in. Additionally, if the number is negative, return 0 (for languages that do have them).

Note: If the number is a multiple of both 3 and 5, only count it once.

_Courtesy of projecteuler.net (Problem 1)_


I've completed this before so I decided to try another approach.
```python
# Original Approach
def multiplesOf3and5(number):
     multiples = [] # initialize array

     # loop through numbers and append to array if multiples of 3 or 5
     for x in range(1,number):
          if x % 3 == 0 or x % 5 == 0:
               multiples.append(x)

     print(sum(multiples))

multiplesOf3and5(1000)
```


```python
# New Approach
def solution(number):
   # loop through numbers and append to array if multiples of 3 or 5
    multiples = [x for x in range(1,number) if x % 3 == 0 or x % 5 == 0]

    return sum(multiples)
```

This way uses a list comprehension to iterate through numbers from 1 to number - 1, appending those that are multiples of 3 or 5 to the multiples list. This approach directly constructs the desired list without the need for separate appending operations.

---

## Take Aways
- Ternary operators are best suited for simple conditional expressions. If your condition involves complex logic, it might be clearer to use a traditional if-else statement.
- List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list.