Variables (Python)

Variables

> Tutorial

Variables are a fundamental concept in every programming language. They are storage locations that keep values in memory so you can reuse them.

Variables can hold several types of values:

Declaring a variable

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

Using a variable

To use the value stored in a variable, you 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 and useWeapon methods.

Keeping a value from one turn to the next

Your code runs again from the top every turn, so a variable only lives for the duration of the turn. To keep a value from one turn to the next, define a turn() function: the code outside turn() runs only once (when the AI loads), while turn() runs again every turn. The global keyword lets turn() reassign a variable defined outside of it.

In the rest of the tutorial, we'll mostly write simple AIs (without turn()) that run in full every turn.

❓ Quiz

What is a variable?

A value that changes often A place to store a value

Which code declares a variable named foo?

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

Full AI