Variables and Data Types
How Python stores values, and the basic types: numbers, strings and Booleans.
Variables
We create a variable by assigning a value to a name:
age = 21 # int
height = 1.72 # float
name = "Ali" # str
is_student = True # bool
result = None # NoneTypeThe name must start with a letter or an underscore, and descriptive lower-case names with underscores (snake_case) are preferred.
Basic types
| Type | Example | Usage |
|---|---|---|
int | 42 | Integers |
float | 3.14 | Floating-point numbers |
str | "text" | Strings |
bool | True | Booleans |
NoneType | None | Absence of a value |
Finding the type and converting
type(3.0) # <class 'float'>
int("42") + 1 # 43
float("2.5") # 2.5
str(10) + "%" # '10%'Trying to add a string and a number directly, such as "5" + 1 causes the error TypeError, because Python does not convert types implicitly in this case.
Strings
Strings in Python 3 are Unicode, so they support Arabic directly. Useful operations include:
s = "Machine Learning"
len(s) # 16
s.lower() # 'machine learning'
s[0:7] # 'Machine'
f"Text length {len(s)}" # an f-string to embed valuesA note on floating-point numbers
Floating-point numbers are stored with an approximate binary representation, so the result of 0.1 + 0.2 is 0.30000000000000004. When comparing, use math.isclose instead of direct equality.
Lesson terms
- Dynamic typing
- Determining a variable's type at run time from the value assigned to it, without declaring the type in advance.
- Variable
- A name that refers to a value stored in memory, and can be rebound to another value.
Abstract
A variable in Python is a name that refers to an object in memory, and its type is determined dynamically from the value. The basic types are int, float, str, bool and NoneType; the type can be found with the type function and converted with functions such as int, float and str.
Review questions
-
What is the type of the value 3.0?
float.
-
What is the result of int("42") + 1?
43, because the string was converted to an integer before the addition.
Sources and references
Complete the lesson
You have completed all the lessons in the track! You can now request the track completion certificate.
Request the certificate