In JavaScript, if..else is the most basic condition statement, it consists of three parts:condition, statement1, statement2, like this:
if condition: statementa
else: statementb
It means that if the condition is true, then execute the statementa, otherwise execute the statementb.If the statementa or statementb more than one line, you need to add { and } at the head and tail of statement in JS, to keep the same indentation on Python and to put a end in Ruby where it indeed ends.
An example, if we want to judge whether a number is odd or even, we can write code like this:
def odd_even(n):
if n%2: return "odd number"
else: return "even number"
If there is more than one condition to judge, we can use the compound if...else statement. an example:
def old_young(age):
if age<16: return "children"
elif (age<50): return "young man" #use "else if" if needed
else: return "old man"
This function returns a different value depending on the parameter age.
Looks very complicated? Well, JS and Ruby also support the ternary operator and Python has something similar too:
statementa if condition else statementb
Condition and statement separated by "?", different statement separated by ":" in both Ruby and JS; in Python you put the condition in the middle of two alternatives. The two examples above can be simplified with ternary operator:
def odd_even(n):
return "odd number" if n%2 else "even number"
def old_young(age):
return "children" if age<16 else "young man" if age<50 else "old man"
Task:
Complete function saleHotdogs/SaleHotDogs/sale_hotdogs, function accept 1 parameters:n, n is the number of customers to buy hotdogs, different numbers have different prices (refer to the following table), return a number that the customer need to pay how much money.
number | price (cents) |
---|---|
n < 5 | 100 |
n >= 5 and n < 10 | 95 |
n >= 10 | 90 |
Solution:
def get_price(func):
def wrapper(number: int):
price = (number < 5 and 100) or (number >= 10 and 90) or 95
return func(number, price)
return wrapper
@get_price
def sale_hotdogs(number: int, price: int) -> int:
return number * price
'나는 이렇게 학습한다 > Algorithm & SQL' 카테고리의 다른 글
0907. Count by X (0) | 2022.09.07 |
---|---|
0906. The Coupon Code (0) | 2022.09.06 |
0904. No zeros for heros (0) | 2022.09.04 |
0903. L1: Bartender, drinks! (0) | 2022.09.03 |
0902. Simple multiplication (0) | 2022.09.02 |