Variables and types¶
~15 min ยท prerequisite: Showing output and reading input
What you will be able to do¶
- Create a variable, give it a value, and change that value later.
- Name variables so they follow Python's rules.
- Use
typeto find out which kind of value a variable holds, and convert betweenint,float, andstr.
The idea¶
A variable is a name that refers to a value. You create one with an assignment, which is written with a single equals sign. The line score = 10 does not ask whether score equals 10. It tells Python to store 10 under the name score. Think of a labeled box: the label is the name, and the box holds the value. You can put a different value in the same box later, and the label stays the same.
Names must follow a few rules. A name may contain letters, digits, and underscores. It may not start with a digit, so 1st is not allowed, but first_1 is. It may not be one of Python's reserved keywords, such as class or if. Names are case-sensitive, which means Total, total, and TOTAL are three different names. A common style is lowercase words joined by underscores, such as total_price.
Every value has a type, which tells Python what kind of value it is and what operations make sense for it. These are the four types you will meet first:
- An integer, written
int, is a whole number such as7or-3. - A float is a number with a decimal point, such as
2.5. - A string, written
str, is text in quotes, such as"Ada". The quotes are not part of the text. - A boolean, written
bool, has one of two values,TrueorFalse.
The function type tells you the type of any value. Python decides the type from the value you assign, so you do not declare it in advance. A variable can even change type if you assign a new value of a different type, although doing that often makes code harder to read.
Types also limit what you can do. You can add two integers, but adding an integer and a string is not allowed. You can convert between types with int, float, and str. Conversion creates a new value of the requested type. For example, int("42") gives the integer 42, and str(42) gives the text "42".
Two values can look the same on screen and still be different. The text "2" and the integer 2 are not equal. Keep this in mind, because it causes many of the errors in this course.
Worked example¶
city = "Lagos"
population = 1000
area = 2.5
is_capital = False
print(type(city))
print(type(population))
print(type(area))
print(type(is_capital))
Line by line, this is what Python does:
city = "Lagos"stores the string"Lagos"under the namecity. The quotes mark the value as text.population = 1000stores the integer1000.area = 2.5stores the float2.5, because the value has a decimal point.is_capital = Falsestores the booleanFalse. Note the capital letter, which Python requires.- Each
print(type(...))line asks for the type of one variable and shows it. The output is<class 'str'>,<class 'int'>,<class 'float'>, and<class 'bool'>. The wordclassis how Python displays a type.
Now the same idea with conversion.
The conversion turns "3" into the integer 3, so the addition works and the output is 4.
Try it¶
The first block checks the type of each kind of value. The second block shows reassignment and conversion. The third block checks name rules that Python accepts.
Common mistakes¶
-
Using
=to compare.=stores a value. To check equality, use==. Writingassert score = 15gives aSyntaxError: invalid syntaxmessage, and the check should beassert score == 15. -
Starting a name with a digit. Writing
1st = 5gives:Rename it to
firstorfirst_1. -
Using a keyword as a name. Writing
class = 5gives:Choose a different name, such as
grade_class. -
Expecting
"2"to equal2. The following check fails:The text
"2"and the integer2are different types. Useint(x)to convert first. -
Using a variable before it exists. Writing
print(total)before any line createstotalgives:
Practice¶
- Create a variable named
citythat holds your home town as a string. Usetypeto check it is astr. - Create a variable
temperaturewith the value21.5. Add anassertthat checks its type isfloat. - Create
countwith the value5. Then add 3 to it and assert the new value is 8. - Convert the string
"100"to an integer, add 1, and assert the result is 101. - Stretch: create
price_text = "7". Convert it to an integer, multiply it by 3, convert the result back to a string, and assert that the final value equals"21".
Solution
python city = "Berlin" assert type(city) is str
Replace Berlin with your home town.
-
python temperature = 21.5 assert type(temperature) is float -
python count = 5 count = count + 3 assert count == 8 -
python number = int("100") assert number + 1 == 101 -
python price_text = "7" price = int(price_text) total = price * 3 final = str(total) assert final == "21"
Recap¶
=stores a value under a name.==compares two values.- Names may contain letters, digits, and underscores, cannot start with a digit, and are case-sensitive.
- Use
typeto see a value's type, andint,float, orstrto convert between them.
Sources¶
- Python tutorial: an informal introduction to Python
- Python reference: identifiers and keywords
- Python reference: assignment statements
- Python standard types: numeric types, int, float
- Python standard types: text sequence type, str
- Python standard types: boolean values
- Python built-in functions: type