In this article we’ll discuss the Basic Data Types in Python:
- about the basic numeric, string, and Boolean types that are built into Python.
- an overview of Python’s built-in functions.
I suggest that you first read an Introduction to Python.
What is a Data Type?
In particular, a variable can contain any data type. Since Python is a dynamically typed language, the data type of a variable can be left undeclared at the point at which it is used. This is clearly shown in the following examples. For example, by changing the value of the variable, print the value of the variable will output the last value assigned to that variable.
>>>num=5 >>>num=15 >>>print(num) 15Code language: PHP (php)
Alternatively, we can also see an example of changing the data type of a variable and the last value will also be output by the interpreter.
>>>age=20 >>>age='twenty' >>>print(age) 'twenty'Code language: PHP (php)
Objects and Data Type Classes in Python
In Python, any value stored in memory is considered an object. Since every value has an underlying data type, the object will be an instance of the data type class. However, the type will only be determined during runtime. Basically, as long as you perform valid operations for the type the interpreter won’t complain.
By the end of this tutorial, you’ll see how the objects of these types look like.
Basic Data Types in Python
Briefly, the basic data types in Python are:
- Floating-Point Numbers
- Complex Numbers
We’ll now discuss the basic data types in Python one by one in more detail.
The integer can be used for basic Python operations such as addition, subtraction, division, and multiplication.
>>> print(5-2) 3 >>>print(5+2) 7 >>>print(20/2) 10 >>>print(5*2) 10Code language: PHP (php)
If you add no prefix (0 plus letters b, o, or x), then the interpreter assumes that the integer is decimal (with a base 10). Otherwise, a prefix of 0b or 0B should be used for Binary, 0o or 0O for Octal, and 0x or 0X for Hexadecimal.
>>> print(0o10) 8Code language: PHP (php)
In Python 3, there is no limit to the length of an integer value, of course except the computer’s memory. This makes it much more simple to use since unlike other languages you don’t have multiple data types with different ranges to remember.
Any integer object in Python is an object of type “int”. For example:
>>> print(type(10)) <class 'int'> >>> print(type(0o10)) <class 'int'> >>> print(type(0x10)) <class 'int'>Code language: HTML, XML (xml)
>>>print(isinstance(10,int)) TrueCode language: PHP (php)
To express numbers that are too large or too small, you can use scientific notation by appending the character e or E followed by a positive or negative integer.
>>> 4.3 4.3 >>> print(type(4.3)) <class 'float'> >>> 4. 4.0 >>> .3 0.3 >>> .4e7 4000000.0 >>> type(.4e7) <class 'float'> >>> 4.3e-4 0.00043Code language: HTML, XML (xml)
>>>print(isinstance(4.0,float)) True >>>print(isinstance(4.0,int)) FalseCode language: PHP (php)
Python float values have 64–bit double-precision values with a maximum value of 1.8 ⨉ 10308. In case of a number greater than that Python will mark it as “inf”. The smallest nonzero positive in Python is approximately 5.0 ⨉ 10-324 while anything smaller will be considered as zero.
>>>print(1.79e308) 1.79e+308 >>>print(1.8e308) inf >>>print(5e-324) 5e-324 >>>print(1e-325) 0.0Code language: CSS (css)
If you want to learn more about floating points in python then see
>>> 2+5j (2+5j) >>> print(type(2+5j)) <class 'complex'>Code language: PHP (php)
As in other popular languages such as Java, the Python string is immutable and therefore the value of a string cannot be changed.
>>>print(type("Hello I am a string")) <class 'string'> >>>print(type('''Hello I am a string''')) <class 'string>Code language: HTML, XML (xml)
Escape Sequences in Strings
In Python strings, the backslash “\” is called the “escape” character. This special character indicates that one or more characters that follow it should be treated specially. An example of a string using a single quote:
>>> print('This string contains a single quote (\') character.') This string contains a single quote (') character.Code language: PHP (php)
Example of breaking up a string over more than one line:
>>> print('a\ ... b\ ... c') abcCode language: PHP (php)
In this example, by including a backslash before each newline, the newlines will be ignored. An example of how to include a literal backslash in a string:
>>> print('Hello\\world') Hello\worldCode language: PHP (php)
By using prefixes r or R we specify the interpreter not to translate any escape sequences.
>>> print('Hello\nworld') Hello world >>> print(r'Hello\nworld') Hello\nworldCode language: PHP (php)
>>> print('Hello\nworld') Hello world >>> print(R'Hello\nworld') Hello\nworldCode language: PHP (php)
>>>print(type(True)) <class 'bool'> >>>print(type(False)) <class 'bool'>Code language: HTML, XML (xml)
Variables in Python
As mentioned earlier, a variable is a place in memory for storing data. Example of changing the data type of a variable:
>>>age=20 >>>age='twenty' >>>print(age) 'twenty'Code language: PHP (php)
In Python, the variables can be a sequence of uppercase, lowercase, digits, and underscore. Usually, you use an underscore between two lower case words, an uppercase letter with the first letter of any new word depending on the convention used e.g. evenNumber, EvenNumber, even_number are all acceptable variable names in Python.
Any characters such as !,#,%,& are not acceptable by Python interpreter. Additionally, any words from Python keywords list cannot be chosen as variable names.
I suggest using a convention and never change it within the same project otherwise the code becomes very unreadable. Also, variable names should be always meaningful. For example using a, b, c, d as variables means nothing to most people whereas name, surname, age, sex make the code immediately more readable and hence easier to maintain.
Assigning multiple variables
Python has a very powerful and simple way of assigning multiple variables, resulting in shorter lines of code. For example:
>>>name,surname,age='Max','Keenan',52 >>>print(name) 'Max' >>>print(surname) 'Keenan' >>>print(age) 52Code language: PHP (php)
Python Built-in Functions
These are pre-written chunks of code you can call to do useful things such as the print() function. The Python interpreter supports many functions that are built-in: 68, as of Python 3.6. See the Python documentation on built-in functions for more detail.
Conversion Functions in Python
In Python, you can convert between different data types by using conversion functions.
You can convert an int to a float by using the function float(int) and the output will be a floating number.
>>>print(float(5)) 5.0Code language: CSS (css)
On the other hand, if you want to convert a float into an int then use the function int(float) where the decimal part is truncated.
>>>print(int(5.6)) 5Code language: CSS (css)
Also, if you try to convert an integer into an integer or a float into a float then the value will remain the same.
To convert any number into a string then use function str(number):
>>>print(str(15)) 15Code language: PHP (php)
abs() Returns absolute value of a number
divmod() Returns quotient and remainder of integer division
max() Returns the largest of the given arguments or items in an iterable
min() Returns the smallest of the given arguments or items in an iterable
pow() Raises a number to a power
round() Rounds a floating-point value
sum() Sums the items of an iterable
ascii() Returns a string containing a printable representation of an object
bin() Converts an integer to a binary string
bool() Converts an argument to a Boolean value
chr() Returns string representation of character given by integer argument
complex() Returns a complex number constructed from arguments
float() Returns a floating-point object constructed from a number or string
hex() Converts an integer to a hexadecimal string
int() Returns an integer object constructed from a number or string
oct() Converts an integer to an octal string
ord() Returns integer representation of a character
repr() Returns a string containing a printable representation of an object
str() Returns a string version of an object
type() Returns the type of an object or creates a new type object
Iterables and Iterators
all() Returns True if all elements of an iterable are true
any() Returns True if any elements of an iterable are true
enumerate() Returns a list of tuples containing indices and values from an iterable
filter() Filters elements from an iterable
iter() Returns an iterator object
len() Returns the length of an object
map() Applies a function to every item of an iterable
next() Retrieves the next item from an iterator
range() Generates a range of integer values
reversed() Returns a reverse iterator
slice() Returns a slice object
sorted() Returns a sorted list from an iterable
zip() Creates an iterator that aggregates elements from iterables
Composite Data Type
bytearray() Creates and returns an object of the bytearray class
bytes() Creates and returns a bytes object (similar to bytearray, but immutable)
dict() Creates a dict object
frozenset() Creates a frozenset object
list() Creates a list object
object() Creates a new featureless object
set() Creates a set object
tuple() Creates a tuple object
Classes, Attributes, and Inheritance
classmethod() Returns a class method for a function
delattr() Deletes an attribute from an object
getattr() Returns the value of a named attribute of an object
hasattr() Returns True if an object has a given attribute
isinstance() Determines whether an object is an instance of a given class
issubclass() Determines whether a class is a subclass of a given class
property() Returns a property value of a class
setattr() Sets the value of a named attribute of an object
super() Returns a proxy object that delegates method calls to a parent or sibling class
format() Converts a value to a formatted representation
input() Reads input from the console
open() Opens a file and returns a file object
print() Prints to a text stream or the console
Variables, References, and Scope
dir() Returns a list of names in current local scope or a list of object attributes
globals() Returns a dictionary representing the current global symbol table
id() Returns the identity of an object
locals() Updates and returns a dictionary representing current local symbol table
vars() Returns __dict__ attribute for a module, class, or object
callable() Returns True if object appears callable
compile() Compiles source into a code or AST object
eval() Evaluates a Python expression
exec() Implements dynamic execution of Python code
hash() Returns the hash value of an object
help() Invokes the built-in help system
memoryview() Returns a memory view object
staticmethod() Returns a static method for a function
__import__() Invoked by the import statement