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:
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
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.
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 to0
andTrue
is equivalent to1
).
Let's break down the code:
The function
even_or_odd
takes a single argument,number
, which is the number you want to check.number % 2
calculates the remainder whennumber
is divided by2
. If the remainder is0
, it means the number is even. If the remainder is1
, it means the number is odd.["Even", "Odd"]
creates a list containing two elements:"Even"
at index0
and"Odd"
at index1
.The expression
[number % 2]
is used as an index to this list. Ifnumber % 2
is0
, it will access the element at index0
("Even"
), and ifnumber % 2
is1
, it will access the element at index1
("Odd"
).The value retrieved from the list (either
"Even"
or"Odd"
) is then immediately returned by thereturn
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.
# 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)
# 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.
Top comments (0)