2. Data Types
See: https://www.w3schools.com/python/python_datatypes.asp
Data Type |
Example |
Description |
---|---|---|
Integers |
|
Positive and negative whole numbers |
Floats |
|
Numbers with a decimal point |
Strings |
|
Characters enclosed by single or double quotation marks |
Booleans |
|
Values representing true and false values |
Some common built-in data types are:
Text Type: |
str |
Numeric Types: |
int, float |
Sequence Types: |
list, tuple, range |
Mapping Type: |
dict |
Set Types: |
set, frozenset |
Boolean Type: |
bool |
None Type: |
NoneType |
2.1. Strings
2.2. Numbers
2.3. Booleans
Booleans have the value True
or False
.
2.4. Types
The type() function can be used to get the data type for a variable.
# String
print(type('hello')) # <class 'str'>
# Integer
print(type(1)) # <class 'int'>
# Float
print(type(1.64)) # <class 'float'>
# Boolean
print(type(True)) # <class 'bool'>
# None
print(type(None)) # <class 'NoneType'>
Questions
Predict the output from
print(type('123'))
.Predict the output from
print(type(123))
.Predict the output from
print(type('False'))
.
2.5. Type casting
See: https://www.w3schools.com/python/python_casting.asp
team = 'Richmond'
premierships = 11
print(team + ' has won ' + str(premierships) + ' premierships.')
int() converts a string consisting of an integer to an integer number
c = int("3") # c will be 3
float() converts a string consisting of a decimal to a decimal number
g = float("4.23") # g will be 4.23
str() converts a number to a string with a number in it
j = str(3.01) # j will be "3.01"
Questions
Predict the output from
print(int(2.5))
.Predict the output from
print(int("3"))
.Predict the output from
print(float(1))
.Predict the output from
print(float("4.23"))
.Predict the output from
print(str(3.01))
.