Variables (Python)

Variables

> Tutorial

Variables are a fundamental point in all programming languages. They are locations for storing values in memory in order to reuse them.

Variables can contain several types of values:

Declare a variable

In Python, you create a variable simply by assigning it a value with =. There is no keyword to write in front of it:

Use a variable

To use the value stored in a variable, we simply write its name:

Here me is your own leek, obtained with Fight.me, and enemy is the nearest enemy, obtained with Fight.getNearestEnemy(). We then pass enemy to the moveToward (move towards) and useWeapon (use the weapon) methods.

Keeping a value from one turn to the next

Your code is run again from the start at each turn, so a variable only lives for the current turn. To keep a value across turns, define a turn() function: the code outside turn() runs only once (when the AI loads), while turn() is replayed every turn. The global keyword lets turn() reassign a variable defined outside of it.

In the rest of the tutorial we will mainly write simple AIs (without turn()), which run entirely at each turn.

❓ Quiz

What is a variable?

A value that changes often A place to store a value

Which code declares a foo variable?

foo = 12 foo = "hello" let foo = 12 int foo = 12

Full AI