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, thenscore = 99. - Python is dynamically typed: the same name can later hold a value of another type.
- Use
snake_casenames: lowercase words joined by underscores. A name cannot start with a digit, contain spaces or hyphens, or be a reserved word such asTrue. - 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.
Create a variable
Assign the text "Ada" to a variable named name, then print the variable.
Print exactly:
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:
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:
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:
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: