Operators

Operators allow calculating, comparing and combining conditions.

Arithmetic#

OperatorActionExample
+ - *Addition, subtraction, multiplication5 + 3 → 8
/Division with decimals15 / 2 → 7.5
//Integer division15 // 2 → 7
%Remainder15 % 2 → 1
**Power2 ** 3 → 8
print 10 + 5 * 2    # 20
print (10 + 5) * 2  # 30
print 10 / 3        # 3.3333...
print 10 // 3       # 3
print 10 % 3        # 1
print 2 ** 4        # 16
String addition

You don’t need to convert strings to numbers, arithmetic operators will do it for you.

x = "5"
y = "5.5"
print x + 3     # 8
print x + 0     # 5
print y + x     # 10.5

Comparison#

These operators compare two values and return true or false:

OperatorActionExampleResult
==Equal to5 == 5true
!=Not equal to5 != 3true
<Less than3 < 5true
>Greater than5 > 3true
<=Less than or equal5 <= 5true
>=Greater than or equal18 >= 18true

Use them in conditions:

age = 18
if age >= 18
  print "You are of legal age"

print "Is 5 equal to 10? " 5 == 10  # false
print "Is 12 an even number? " 12 % 2 == 0  # true

Logical#

They combine conditions or invert them:

OperatorAlternative formActionExampleResult
and&&Are both conditions true?true and falsefalse
or||Is at least one true?true or falsetrue
not!Invert itnot truefalse

Practical example:

age = 25
has_license = true
if age >= 18 and has_license
  print "You can drive"
Logical short circuit

The and and or operators use short-circuit evaluation, which means they don’t execute the second condition if the first already determines the result.

# If the first condition is false, the second is not executed
if false and input("This input will not execute") 
  print "This will not be printed"

# If the first condition is true, the second is not executed
if true or input("This input will not execute") 
  print "This will be printed"

How does it work? and and or become pure conditional jumps, that is, they are equivalent to using conditional blocks.

Concatenation#

The . operator (with spaces around it) joins values as text:

x = 4
y = 1.05
result = "The number is " . x . y
print result # "The number is 41.05"
Interpolation vs concatenation
  • Interpolation is usually more readable and efficient, review the Strings section.
  • For multiline literals, consider Templates.

Reading#

The <- operator asks for a value that the user must enter manually.

name <- "Enter your name: "
age <- "Enter your age: "
print "Hello " name ", you are " age " years old"

Compound assignment#

Modify a variable in a single line:

OperatorActionExampleEquivalent to
+=Add to variablecounter += 5counter = counter + 5
-=Subtract from variablecounter -= 3counter = counter - 3
*=Multiply variableprice *= 2price = price * 2
/=Divide variableprice /= 2price = price / 2
++Add 1counter++counter = counter + 1
--Subtract 1counter--counter = counter - 1

Example:

counter = 0
counter += 5
counter++
print counter   # 6