Co-authored-by: Dario <105294544+Dario-DC@users.noreply.github.com> Co-authored-by: Krzysztof G. <60067306+gikf@users.noreply.github.com>
10 KiB
id, title, challengeType, dashedName
| id | title | challengeType | dashedName |
|---|---|---|---|
| 67fe859a00971c34a23abd43 | What Are Common Data Types in Python and How Do You Get the Type of a Variable? | 19 | what-are-common-data-types-in-python-and-how-do-you-get-the-type-of-a-variable |
--description--
Before working with Python variables, it's important to understand data types. A data type describes the kind of value a variable holds. For example, a number, a piece of text, or a list of items. Programming languages use data types so they know how to store and work with different kinds of information.
Python is a dynamically-typed language like JavaScript, meaning you don't need to explicitly declare types for variables. The language knows what data type a variable is based on what you assign to it.
Here are some examples:
name = 'John Doe' # Python knows this is a string
age = 25 # Python knows this is an integer
This is in contrast to some statically-typed languages like C#, Java, and C++, where you have to declare types with variables, like this:
string name = 'John Doe'
int age = 25
The dynamic-typing nature of Python makes coding really fast and more flexible, but it can lead to unexpected bugs because type errors are detected only when a program runs, not when the program compiles.
Since Python determines data types while your program is running, type-related mistakes are only discovered at that moment. When a program runs, Python executes your code line by line. If it reaches a line where a certain object is expected to behave in a way it's not able to, Python will stop and show an error.
In contrast, some languages compile your program before it runs. Compiling means the computer checks your code in advance and prepares it to run. During this step, those languages can catch type errors before the program even starts.
You don't need to know those languages yet. The important idea is simply:
-
In Python type errors can reveal themselves during execution, when the program is actually running and using your code.
-
Compiled languages catch type errors during the compile step, before the program is allowed to run.
Because of this, you might not learn about a type mistake in Python until the program reaches that specific line of code while running.
Here are the most common data types you'll use in Python:
- Integer: A whole number without decimals, for example,
10or-5.
my_integer_var = 10
print('Integer:', my_integer_var) # Integer: 10
- Float: A number with a decimal point, like
4.41or-0.4.
my_float_var = 4.50
print('Float:', my_float_var) # Float: 4.5
- Complex: A number with a real and imaginary part, like
6 + 7j.
my_complex_var = 3 + 4j
print('Complex:', my_complex_var) # Complex: (3+4j)
- String: A sequence of characters enclosed in single or double quotation marks like
'Hello world!'.
my_string_var = 'hello'
print('String:', my_string_var) # String: hello
- Boolean: A true or false type, written as
TrueorFalse.
my_boolean_var = True
print('Boolean:', my_boolean_var) # Boolean: True
- Set: An unordered collection of unique elements, like
{4, 2, 0}.
my_set_var = {7, 5, 8}
print('Set:', my_set_var) # Set: {7, 5, 8}
- Dictionary: A collection of key-value pairs enclosed in curly braces, like
{'name': 'John Doe', 'age': 28}.
my_dictionary_var = {'name': 'Alice', 'age': 25}
print('Dictionary:', my_dictionary_var) # Dictionary: {'name': 'Alice', 'age': 25}
- Tuple: An immutable ordered collection, enclosed in brackets, like
(7, 8, 4).
my_tuple_var = (7, 5, 8)
print('Tuple:', my_tuple_var) # Tuple: (7, 5, 8)
- Range: A sequence of numbers, often used in loops, for example,
range(5).
my_range_var = range(5)
print(my_range_var) # range(0, 5)
- List: An ordered collection of elements that supports different data types.
my_list = [22, 'Hello world', 3.14, True]
print(my_list) # [22, 'Hello world', 3.14, True]
- None: A special value that represents the absence of a value.
my_none_var = None
print('None:', my_none_var) # None: None
Many other programming languages group data types broadly as either primitive or reference types. Primitive types are simple and immutable, meaning they can't be changed once declared. Reference types can hold multiple values, and are either mutable or immutable. But Python doesn't draw a hard line between those two groups. Instead, all data gets treated as objects, and some objects are immutable while others are mutable.
Immutable data types can't be modified or altered once they're declared. You can point their variables at something new, which is called reassignment, but you can't change the original object itself by adding, removing, or replacing any of its elements. Examples of immutable data types in Python are string, integer, float, boolean, tuple, and range.
Here's an example showing that, while you can reassign a different string to a variable, direct modification of a string isn't allowed because strings are immutable:
greeting = 'hi'
greeting = 'hello'
print(greeting) # hello
greeting[0] = 'H' # TypeError: 'str' object does not support item assignment
On the other hand, you can change mutable types without giving them a new name. You can add, remove, or update items right where they live. Examples are a list and a dictionary.
Here's an example of updating an element in a list:
nums = [1, 2, 3]
nums[0] = 4
print(nums) # [4, 2, 3]
To get the data type of a variable, you can use the type() function:
my_var_1 = 'Hello world'
my_var_2 = 21
print(type(my_var_1)) # <class 'str'>
print(type (my_var_2)) # <class 'int'>
And here's are all the data types covered in this lesson, along with their types in the terminal:
my_integer_var = 10
print('Integer:', my_integer_var, '| Type:', type(my_integer_var)) # Integer: 10 | Type: <class 'int'>
my_float_var = 4.50
print('Float:', my_float_var, '| Type:', type(my_float_var)) # Float: 4.5 | Type: <class 'float'>
my_complex_var = 3 + 4j
print('Complex:', my_complex_var, '| Type:', type(my_complex_var)) # Complex: (3+4j) | Type: <class 'complex'>
my_string_var = 'hello'
print('String:', my_string_var, '| Type:', type(my_string_var)) # String: hello | Type: <class 'str'>
my_boolean_var = True
print('Boolean:', my_boolean_var, '| Type:', type(my_boolean_var)) # Boolean: True | Type: <class 'bool'>
my_set_var = {7, 5, 8}
print('Set:', my_set_var, '| Type:', type(my_set_var)) # Set: {7, 5, 8} | Type: <class 'set'>
my_dictionary_var = {'name': 'Alice', 'age': 25}
print('Dictionary:', my_dictionary_var, '| Type:', type(my_dictionary_var)) # Dictionary: {'name': 'Alice', 'age': 25} | Type: <class 'dict'>
my_tuple_var = (7, 5, 8)
print('Tuple:', my_tuple_var, '| Type:', type(my_tuple_var)) # Tuple: (7, 5, 8) | Type: <class 'tuple'>
my_range_var = range(5)
print('Range:', list(my_range_var), '| Type:', type(my_range_var)) # Range: [0, 1, 2, 3, 4] | Type: <class 'range'>
my_list = [22, 'Hello world', 3.14, True]
print('List:', list(my_list), '| Type:', type(my_list)) # List: [22, 'Hello world', 3.14, True] | Type: <class 'list'>
my_none_var = None
print('None:', my_none_var, '| Type:', type(my_none_var)) # None: None | Type: <class 'NoneType'>
Another way to check the type of a variable is to use the built-in isinstance() function, which checks if a variable matches a specific data type.
isinstance() takes in an object and the type you want to check it against, then returns a boolean. Here are some examples:
isinstance('Hello world', str) # True
isinstance(True, bool) # True
isinstance(42, int) # True
isinstance('John Doe', int) # False
Although Python is dynamically typed, you can still add type hints. These are optional signals that tell other developers what the data type of a variable or function is expected to be. Here's a quick example for variable types:
user_name: str = 'John Doe'
user_age: int = 24
Here's another example showing hints for function parameters and a return type:
def greet(name: str, age: int) -> str:
return f'Hello, {name}, age {age}.'
And here's a combination of the two:
def greet(name: str, age: int) -> str:
return f'Hello, {name}, age {age}.'
user_name: str = 'John Doe'
user_age: int = 24
print(greet(user_name, user_age)) # Hello, John Doe, age 24.
Note that, unlike TypeScript which enforces types at compile time, Python just uses these hints for static analysis, documentation, and editor support, not for enforcing types during runtime. This can help developers catch bugs early and improve code readability, especially in large projects.
--questions--
--text--
What does it mean that Python is dynamically typed?
--answers--
You must manually specify the data type of every variable.
--feedback--
Think about how Python figures out the data type for you.
Python does not support different data types.
--feedback--
Think about how Python figures out the data type for you.
Python automatically determines the data type based on the assigned value.
Variables in Python cannot change their data type after assignment.
--feedback--
Think about how Python figures out the data type for you.
--video-solution--
3
--text--
What is the difference between the integer and float data types?
--answers--
Integers can store both positive and negative numbers, while floats can only store positive numbers.
--feedback--
One has decimals, the other doesn't.
Integers are whole numbers without decimals, while floats are numbers with decimal points.
Floats take up less memory than integers in Python.
--feedback--
One has decimals, the other doesn't.
Integers can only store numbers up to 1000, while floats have no limit.
--feedback--
One has decimals, the other doesn't.
--video-solution--
2
--text--
How can you check the data type of a variable in Python?
--answers--
By using the type() function, like type(my_var).
By checking the variable's value manually.
--feedback--
There's a built-in function for this.
By using the typeof function, like typeof(my_var).
By converting the variable to a string and analyzing its characters.
--feedback--
There's a built-in function for this.
--video-solution--
1