Part 3: Python Programming
Part 3: Python Programming — read through each chapter in order. Diagrams, tables and worked examples included.
2. Variables, Values & Dynamic Typing
Variables, Values & Dynamic Typing
A program is not very useful if it can only work with fixed numbers and text. We need a way to store information and refer to it later. That is what variables are for. A variable is a name that points to a value stored in the computer's memory.
Assignment
You create a variable by writing a name, an equals sign, and a value. This is called assignment:
The equals sign does not mean "equal" as in mathematics. It means "take the value on the right and store it under the name on the left." You can read age = 25 as "age becomes 25."
Changing a variable
A variable can be reassigned at any time. Each new assignment replaces the old value:
Here Python first works out score + 5 (which is 15) and then stores that result back into score.
Naming rules
Variable names must follow a few rules, and some conventions make your code easier to read:
- Names may contain letters, digits, and underscores, but cannot start with a digit.
total2is fine;2totalis an error. - Names are case-sensitive:
Ageandageare two different variables. - You cannot use Python's reserved keywords (such as
if,for,class) as names. - By convention, use lowercase words joined by underscores, like
first_nameortotal_price. This style is called snake_case. - Choose meaningful names.
ntells a reader little;number_of_studentstells them a lot.
Dynamic typing and the type() function
Every value in Python has a type, which describes what kind of data it is. You can ask Python for the type of any value using the built-in type() function:
Python is dynamically typed. This means you never have to declare what type a variable will hold; Python figures it out from the value you assign. It also means the same variable can hold different types at different times:
This flexibility is convenient, but be careful: a variable you think holds a number might have been changed to text elsewhere.
The core built-in types
You will meet these five fundamental types constantly. Here they are with example values.
| Type | Name | Example value | Meaning |
|---|---|---|---|
int | Integer | 25, -3, 0 | Whole numbers, positive or negative |
float | Floating point | 9.99, -0.5, 3.0 | Numbers with a decimal point |
str | String | "Ada", 'hi' | Text, written inside quotes |
bool | Boolean | True, False | A truth value, used for decisions |
NoneType | None | None | "Nothing here" / absence of a value |
Notice that True and False start with capital letters, and None is written with a capital N. These are special values built into the language.
With variables you can now label and reshape data as your program runs. Practice by storing your own name, age, and favourite number in variables, then printing each with its type.