Operators (Python)

Operators

> Tutorial

Operators

Operators are used to perform mathematical calculations or manipulate data of all kinds.

Here are the main operators:

In an expression with several operators, the operators are applied according to the usual precedence rules: for example, * takes precedence over +.

Example with different operators:

# We perform some calculations:
a = 2 + 8   # a takes the value 10
a = 5 - 4   # a takes the value 1
a = 3 * 5   # a takes the value 15
a = 7 // 2  # a takes the value 3 (integer division)
a = 8 % 3   # a takes the value 2

# Operators can be combined:
a = 1 + 2 * 3  # a takes the value 7

You can also use parentheses, as in (5 + 7) * 2.

Assignment operators

In addition to the = operator, there are many assignment operators like +=, -=, *= etc., which combine a calculation and an assignment.

An example with *=, which performs a multiplication and stores the result in the same variable:

x = 5
x *= 3
# x is 15

A more complex healing condition

Our current healing condition makes us heal as soon as we have lost 1 life point. We can improve it by healing ourselves only when our life is

To display the value of a variable or an expression in the fight actions, use print(). Example: print(me.maxLife * 0.75).

❓ Quiz

What is the result of the code 10 + (5 * 7) - 20 // 4?

40 25 18 -30

What is the value of x at the end of the code x = 10; x *= 2; x += 5; x //= 5?

5 15 22 12

What is the result of the code (True and False) or (True and True)?

1 3 True False

Full AI

me = Fight.me

# We take the pistol if it isn't equipped
if me.weapon is None:
	me.setWeapon(Weapon.pistol)

# We get the nearest enemy
enemy = Fight.getNearestEnemy()

# We move toward the enemy
me.moveToward(enemy)

# Boosts, shield and heal
me.useChip(Chip.motivation)
me.useChip(Chip.protein)
me.useChip(Chip.helmet)

# We heal ourselves if our life is below 75% of our max life.
if me.life < me.maxLife * 0.75:
	me.useChip(Chip.bandage)

# We try to shoot at it!
me.useWeapon(enemy)