4. Variables

A variable is a name bound to a value. You create or update it with name = value; = assigns, it is not equality.

  • Reassigning replaces the value: score = 1, then score = 99.
  • Python is dynamically typed: the same name can later hold a value of another type.
  • Use snake_case names: lowercase words joined by underscores. A name cannot start with a digit, contain spaces or hyphens, or be a reserved word such as True.
  • An f-string puts values inside text: f"Hello {name}".
  • A type annotation documents the expected type: age: int = 36. It does not change the value.

Coming from JavaScript? There is no let, const or var: assigning a name creates it, and it can be reassigned to another type. Type annotations are optional and not enforced at runtime, unlike TypeScript.

#01

Create a variable

Assign the text "Ada" to a variable named name, then print the variable.

Print exactly:

Output
Run your code to see the output here.
#02

Reassign a variable

Assign 1 to score, then assign 99 to the same variable and print it. The second value replaces the first.

Print exactly:

Output
Run your code to see the output here.
#03

Put variables inside text

An f-string starts with f. Inside it, {name} is replaced by the value of the variable name.

Create name = "Ada" and age = 36, then print Ada is 36 with a single f-string.

Print exactly:

Output
Run your code to see the output here.
#04

Annotate the type

A type annotation writes the expected type after the name, separated by :. The syntax is name: type = value.

Create age with the annotation int and the value 36, then print it.

Print exactly:

Output
Run your code to see the output here.
#05

Use snake_case

Variable names are written in snake_case: lowercase words joined by underscores. Create a variable named user_name with the value "ada" and print it.

Print exactly:

Output
Run your code to see the output here.