Basic Data Types and Values
Let's look at some of the basic data types in Python:
- 8 is an integer
- 3.14 is a floating point number, or float for short
- "Hello" is a string
They are values - one of the fundamental things that a program manipulates.
New vocabulary:
Python refers to these values as objects.
These objects are classified into different classes and are more specifically called data types. In later chapters, we will see how to create our own "types" using classes.
If you are not sure what data type/class a value falls into, Python's built-in function type()
will return a value's data type/class.
With the help of print()
function we can find out a value's type:
print(type(8)) # <class 'int'> (8 is an `integer`)
print(type(8.5)) # <class 'float'>, (a `floating point` number)
print(type("Hello")) # <class 'str'> ( a `string`)
Type conversion
float()
converts an integer or a number string into a floating point number.
str()
converts a number into a string.
int()
converts other types into integer (if applicable)
print(float(10) # 10.0 (an integer to a float)
print(float('12') # 12.0 (a string to a float)
print(int(15/2)) # 7 (a float to an integer)
print(int('8')) # 8 (a string to an integer)
print(type(str(15))) # <class 'str'> ( a number to a string)
print(float('seven')) # error message (not applicable)
print(int('eight')) # error message
Data types in CodeCraft
int()
is frequently used in CodeCraft:
Calling int()
on a float value will remove the decimal part and return only a full number, or integer.
f = 3.14
print(int(f)) # 3
column_m(0, -10, int(f), 1) # a brick column of height 3 blocks
Calling int()
on a string value will convert the string into an integer if applicable
y = "4" # this is a string
print(y)
print(type(y))
block_m(0, int(y), -10, 2) # a cobblestone block
Console result:
3
4
<class 'str'>
See the brick column and the cobblestone block at the top: