L-02: Data Types and Type Casting
Understanding the data types of a variable and type casting.
Table of contents
Data Types
In Python, data types are the fundamental concept that defines the kind of data a variable can hold and the operations that can be performed on that data. Python is dynamically typed, which means you don't need to declare the data type explicitly; it's determined automatically based on the value assigned to a variable.
In Python, data types can be broadly classified into the following categories:
Numeric Types
int
: Represents integer values.float
: Represents floating-point (decimal) values.complex
: Represents complex numbers (a + ib).
# Numeric Types Examples
integer_variable = 42
float_variable = 3.14
complex_variable = 2 + 3j
Sequence Types
str
: Represents strings (sequences of characters).list
: Represents ordered, mutable sequences.tuple
: Represents ordered, immutable sequences.
# Sequence Types Examples
string_variable = "Hello, Python!"
list_variable = [1, 2, 3, 4, 5]
tuple_variable = (10, 20, 30)
Mapping Type
dict
: Represents key-value pairs using a dictionary.
# Mapping Type Example
dictionary_variable = {'name': 'John', 'age': 30}
Set Types
set
: Represents an unordered collection of unique elements.frozenset
: Represents an immutable version of a set.
# Set Types Examples
set_variable = {1, 2, 3, 4, 5}
frozenset_variable = frozenset({1, 2, 3})
Boolean Type
bool
: Represents Boolean valuesTrue
orFalse
.
# Boolean Type Example
bool_variable = True
Binary Types
bytes
: Represents a sequence of bytes (immutable).bytearray
: Represents a mutable sequence of bytes.memoryview
: Represents a memory view object for binary data.
# Binary Types Example
bytes_variable = b'hello'
bytearray_variable = bytearray([65, 66, 67])
None Type
None
: Represents the absence of a value, often used as a placeholder.
# None Type Example
none_variable = None
These are the broad data type categories in Python, along with some code examples for each type. You can use these data types to store and manipulate different kinds of data in your Python programs.
Type casting
Type casting, also known as type conversion in Python, refers to the process of converting a value from one data type to another. Python provides several built-in functions for type casting, allowing you to change the data type of a value as needed. Here are some common type-casting functions in Python:
int()
: Converts a value to an integer data type. This is useful when you want to treat a value as a whole number.x = 5.6 y = int(x) # y is now 5
float()
: Converts a value to a floating-point data type. This is useful when you want to include decimal places in a number.x = 10 y = float(x) # y is now 10.0
str()
: Converts a value to a string data type. This is useful for converting numbers or other data types to text.x = 42 y = str(x) # y is now "42"
bool()
: Converts a value to a boolean data type (True
orFalse
). Generally, values that are considered "empty" or "zero" will be converted toFalse
, and other values will be converted toTrue
.x = 0 y = bool(x) # y is now False z = "hello" w = bool(z) # w is now True
list()
,tuple()
,set()
,dict()
: These functions can be used to convert between various collection data types.x = (1, 2, 3) y = list(x) # y is now [1, 2, 3] z = [1, 2, 3] w = tuple(z) # w is now (1, 2, 3)
ord()
andchr()
: These functions are used to convert characters to their corresponding ASCII values and vice versa.char = 'A' ascii_value = ord(char) # ascii_value is 65 ascii_value = 65 char = chr(ascii_value) # char is 'A'
Custom Type Casting: You can also create your custom functions or methods to perform custom type casting, especially when dealing with complex objects or user-defined data types.
def custom_cast(value): # Custom type casting logic return converted_value result = custom_cast(some_value)
Type casting is a common operation in Python, allowing you to work with data in the format that best suits your program's needs. However, be cautious when converting between data types, as it can sometimes lead to loss of information or unexpected results.
ASCII
ASCII (American Standard Code for Information Interchange) is a character encoding standard that assigns a unique numerical value (an integer, referred to as Dec
in the given table below) to each character on the keyboard and to some control characters. It was originally developed in the early 1960s and has become one of the most widely used character encoding standards.
In the ASCII standard:
Each character is represented by a 7-bit binary number (0-127).
The first 32 values (0-31) are reserved for control characters (e.g., newline, tab, and carriage return) used to control devices such as printers and teletypes.
The remaining values (32-127) represent printable characters, including letters (both uppercase and lowercase), digits, punctuation marks, and special symbols.
Here is a basic ASCII table showing some common characters and their corresponding ASCII values:
Dec Hex Character
----------------------
0 00 NUL (Null)
1 01 SOH (Start of Heading)
2 02 STX (Start of Text)
3 03 ETX (End of Text)
4 04 EOT (End of Transmission)
5 05 ENQ (Enquiry)
6 06 ACK (Acknowledgment)
7 07 BEL (Bell)
8 08 BS (Backspace)
9 09 HT (Horizontal Tab)
10 0A LF (Line Feed)
11 0B VT (Vertical Tab)
12 0C FF (Form Feed)
13 0D CR (Carriage Return)
14 0E SO (Shift Out)
15 0F SI (Shift In)
16 10 DLE (Data Link Escape)
17 11 DC1 (Device Control 1)
18 12 DC2 (Device Control 2)
19 13 DC3 (Device Control 3)
20 14 DC4 (Device Control 4)
21 15 NAK (Negative Acknowledgment)
22 16 SYN (Synchronous Idle)
23 17 ETB (End of Transmission Block)
24 18 CAN (Cancel)
25 19 EM (End of Medium)
26 1A SUB (Substitute)
27 1B ESC (Escape)
28 1C FS (File Separator)
29 1D GS (Group Separator)
30 1E RS (Record Separator)
31 1F US (Unit Separator)
32 20 Space
33 21 !
34 22 "
35 23 #
36 24 $
37 25 %
38 26 &
39 27 '
40 28 (
41 29 )
42 2A *
43 2B +
44 2C ,
45 2D -
46 2E .
47 2F /
48 30 0
49 31 1
50 32 2
51 33 3
52 34 4
53 35 5
54 36 6
55 37 7
56 38 8
57 39 9
58 3A :
59 3B ;
60 3C <
61 3D =
62 3E >
63 3F ?
64 40 @
65 41 A
66 42 B
67 43 C
68 44 D
69 45 E
70 46 F
71 47 G
72 48 H
73 49 I
74 4A J
75 4B K
76 4C L
77 4D M
78 4E N
79 4F O
80 50 P
81 51 Q
82 52 R
83 53 S
84 54 T
85 55 U
86 56 V
87 57 W
88 58 X
89 59 Y
90 5A Z
91 5B [
92 5C \
93 5D ]
94 5E ^
95 5F _
96 60 `
97 61 a
98 62 b
99 63 c
100 64 d
101 65 e
102 66 f
103 67 g
104 68 h
105 69 i
106 6A j
107 6B k
108 6C l
109 6D m
110 6E n
111 6F o
112 70 p
113 71 q
114 72 r
115 73 s
116 74 t
117 75 u
118 76 v
119 77 w
120 78 x
121 79 y
122 7A z
123 7B {
124 7C |
125 7D }
126 7E ~
127 7F DEL (Delete)
These are the ASCII values for some commonly used characters. You can use these values to perform character encoding and decoding operations in Python and other programming languages.