Cobra/Keywords/if: различия между версиями

Материал из Викиучебника — открытых книг для открытого мира
Содержимое удалено Содержимое добавлено
Строка 40: Строка 40:
print 'x and y are the same'
print 'x and y are the same'
</source></font>
</source></font>
<font face="verdana">

<source lang="python">
# Example 1
# Example 1
print if(x>y, x, y)
print if(x>y, x, y)
Строка 55: Строка 56:
# Example 5
# Example 5
foo = if(condition, 'x', 5) # type is Object
foo = if(condition, 'x', 5) # type is Object
</source></font>

Версия от 06:33, 18 декабря 2012

If

if оператор используется для выполнения кода в случае удовлетворению условию.

Синтаксис

if-statement =
    if <expression>
        <statements>
    (else if <expression>
        <statements>)*
    [else
        <statements>]

if(<condition>, <texpr>, <fexpr>)

Пример

“if-блок” выражений выполняется если условие истинно, иначе выполняется другой “else-блок”. Может выполняться только один блок выражений. “else-блок” является не обязательным.
Допустимо использовать оператор if внутри другого оператора условия и так далее.

# Example 1
if name
    print 'Hello, [name].'

# Example 2
if name
    print 'Hello, [name].'
else
    print "I don't know your name."

# Example 3
if x < y
    print 'x is smaller'
else if x > y
    print 'x is larger'
else
    print 'x and y are the same'

# Example 1 
print if(x>y, x, y) 

# Example 2 
print if(value, 'yes', 'no') # type is String 

# Example 3 
total += if(direction==DirectionEnum.Long, +1, -1) * amount 

# Example 4 
foo = if(condition, 'x', nil) # type is String? 

# Example 5 
foo = if(condition, 'x', 5) # type is Object