= 5
x type(x)
int
Knowing about data types in Python is crucial for several reasons:
Correctness and reliability: Understanding data types helps ensure that your code operates correctly and produces reliable results. By explicitly defining and handling data types, you can avoid unexpected errors or inconsistencies in your code.
Memory optimization: Different data types have varying memory requirements. By choosing appropriate data types, you can optimize memory usage and improve the performance of your code. For example, using integers instead of floating-point numbers can save memory if decimal precision is not necessary.
Data manipulation and operations: Each data type in Python has its own set of operations and methods. Understanding data types allows you to perform specific operations and manipulate data effectively. For example, you can concatenate strings, perform arithmetic calculations with numbers, or iterate over elements in a list.
Input validation and error handling: When receiving input from users or external sources, it is important to validate and handle the data appropriately. Knowing the expected data types allows you to validate inputs, handle errors gracefully, and provide meaningful feedback to users.
Interoperability and integration: Python integrates with various libraries, frameworks, and external systems. Understanding data types helps you exchange data seamlessly between different components of your code or integrate with external systems. For example, when interacting with a database, you need to understand how Python data types map to the database’s data types.
Code readability and maintainability: Explicitly defining data types in your code improves readability and makes it easier for other developers to understand and maintain your code. It helps convey your intentions and makes the code self-documenting, reducing the chances of misinterpretation or confusion.
Overall, having knowledge of data types in Python enables you to write robust, efficient, and understandable code that operates correctly with the data it handles. It empowers you to make informed decisions about memory usage, data manipulation, input validation, and code integration, leading to better overall programming proficiency.
Python has a small set of built-in types for handling numerical data, strings, Boolean (True
or False
) values, and dates and time. These “single value” types are sometimes called scalar types, and we refer to them in this book as scalars . See Standard Python scalar types for a list of the main scalar types. Date and time handling will be discussed separately, as these are provided by the datetime
module in the standard library.
?(caption)
Type
|
Description
|
---|---|
None
|
The Python “null” value (only one instance of the
None object exists)
|
str
|
String type; holds Unicode strings
|
bytes
|
Raw binary data
|
float
|
Double-precision floating-point number (note there is no separate
double type)
|
bool
|
A Boolean
True or False value
|
int
|
Arbitrary precision integer
|
= 5
x type(x)
int
=7.5
ytype(y)
float
type(x+y)
float
The primary Python types for numbers are int
and float
. An int
can store arbitrarily large numbers:
= 17239871
ival ** 6 ival
26254519291092456596965462913230729701102721
can take only two values: True
and False
.
print(4 == 5)
print(4 < 5)
= 4 != 5
b print(b)
print(int(b))
False
True
True
1
Many people use Python for its built-in string handling capabilities. You can write string literals using either single quotes ’
or double quotes “
(double quotes are generally favored):
= 'one way of writing a string'
a = "another way"
b
type(a)
str
For multiline strings with line breaks, you can use triple quotes, either '''
or """
:
= """
c This is a longer string that
spans multiple lines
"""
"\n") c.count(
3
Note: All string methods return new values. They do not change the original string.
Method | Description |
---|---|
capitalize() | Converts the first character to upper case |
casefold() | Converts string into lower case |
center() | Returns a centered string |
count() | Returns the number of times a specified value occurs in a string |
encode() | Returns an encoded version of the string |
endswith() | Returns true if the string ends with the specified value |
expandtabs() | Sets the tab size of the string |
find() | Searches the string for a specified value and returns the position of where it was found |
format() | Formats specified values in a string |
format_map() | Formats specified values in a string |
index() | Searches the string for a specified value and returns the position of where it was found |
isalnum() | Returns True if all characters in the string are alphanumeric |
isalpha() | Returns True if all characters in the string are in the alphabet |
isascii() | Returns True if all characters in the string are ascii characters |
isdecimal() | Returns True if all characters in the string are decimals |
isdigit() | Returns True if all characters in the string are digits |
isidentifier() | Returns True if the string is an identifier |
islower() | Returns True if all characters in the string are lower case |
isnumeric() | Returns True if all characters in the string are numeric |
isprintable() | Returns True if all characters in the string are printable |
isspace() | Returns True if all characters in the string are whitespaces |
istitle() | Returns True if the string follows the rules of a title |
isupper() | Returns True if all characters in the string are upper case |
join() | Converts the elements of an iterable into a string |
ljust() | Returns a left justified version of the string |
lower() | Converts a string into lower case |
lstrip() | Returns a left trim version of the string |
maketrans() | Returns a translation table to be used in translations |
partition() | Returns a tuple where the string is parted into three parts |
replace() | Returns a string where a specified value is replaced with a specified value |
rfind() | Searches the string for a specified value and returns the last position of where it was found |
rindex() | Searches the string for a specified value and returns the last position of where it was found |
rjust() | Returns a right justified version of the string |
rpartition() | Returns a tuple where the string is parted into three parts |
rsplit() | Splits the string at the specified separator, and returns a list |
rstrip() | Returns a right trim version of the string |
split() | Splits the string at the specified separator, and returns a list |
splitlines() | Splits the string at line breaks and returns a list |
startswith() | Returns true if the string starts with the specified value |
strip() | Returns a trimmed version of the string |
swapcase() | Swaps cases, lower case becomes upper case and vice versa |
title() | Converts the first character of each word to upper case |
translate() | Returns a translated string |
upper() | Converts a string into upper case |
zfill() | Fills the string with a specified number of 0 values at the beginning |
Many operations/functions in python are specific to the data type even though we use the same syntax:
print(x+y)
print(a+b)
12.5
one way of writing a stringanother way
We can often convert from one type to another if it makes sense:
str(x)
'5'
float(x)
5.0
Mutable objects are those that allow you to change their value or data in place without affecting the object’s identity. In contrast, immutable objects don’t allow this kind of operation. You’ll just have the option of creating new objects of the same type with different values.
In Python, mutability is a characteristic that may profoundly influence your decision when choosing which data type to use in solving a given programming problem. Therefore, you need to know how mutable and immutable objects work in Python.
In Python, variables don’t have an associated type or size, as they’re labels attached to objects in memory. They point to the memory position where concrete objects live. In other words, a Python variable is a name that refers to or holds a reference to a concrete object. In contrast, Python objects are concrete pieces of information that live in specific memory positions on your computer.
The main takeaway here is that variables and objects are two different animals in Python:
Strings and tuples are immutable:
= "this is a string"
a
10] = "f" a[
TypeError: 'str' object does not support item assignment
A tuple is a fixed-length, immutable sequence of Python objects which, once assigned, cannot be changed. The easiest way to create one is with a comma-separated sequence of values wrapped in parentheses:
= (4, 5, 6)
tup print(tup)
= (4, "Ray", 6)
tup print(tup)
#In many contexts, the parentheses can be omitted
= 4, "Ray", 6
tup print(tup)
(4, 5, 6)
(4, 'Ray', 6)
(4, 'Ray', 6)
Elements can be accessed with square brackets [] as with most other sequence types. As in C, C++, Java, and many other languages, sequences are 0-indexed in Python:
0] tup[
4
#but you cannot change the value:
0] = 3 tup[
TypeError: 'tuple' object does not support item assignment
You can concatenate tuples using the +
operator to produce longer tuples:
4, None, 'foo') + (6, 0) + ('bar',) (
(4, None, 'foo', 6, 0, 'bar')
Multiplying a tuple by an integer, as with lists, has the effect of concatenating that many copies of the tuple:
'foo', 'bar') * 4 (
('foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'bar')
If you try to assign to a tuple-like expression of variables, Python will attempt to unpack the value on the righthand side of the equals sign:
= (4, 5, 6)
tup = tup a, b, c