In this lesson, we will learn about the different data types in Python and how to work with them.
In Python, there are several built-in data types that you can use to store data. These data types include integers, floats, strings, and booleans.
Integers
An integer is a whole number that can be positive, negative, or zero. In Python, you can use the int
data type to store integers.
Here is an example of how to create an integer variable:
age = 30
In this example, the age
variable is an integer with a value of 30.
Floats
A float is a number with a decimal point. In Python, you can use the float
data type to store floats.
Here is an example of how to create a float variable:
price = 10.99
In this example, the price
variable is a float with a value of 10.99.
Strings
A string is a sequence of characters. In Python, you can use the str
data type to store strings.
Here is an example of how to create a string variable:
name = 'John'
In this example, the name
variable is a string with a value of 'John'.
Strings can also be defined using triple quotes (either single or double). This allows you to create multi-line strings or strings that contain quotes within them.
Here is an example of how to create a multi-line string:
description = '''
This is a multi-line
string that can span
multiple lines.
'''
And here is an example of how to create a string that contains quotes:
quote = "He said, 'Hello, World!'"
Booleans
A boolean is a data type that can only have two values: True
or False
. In Python, you can use the bool
data type to store booleans.
Here is an example of how to create a boolean variable:
is_active = True
In this example, the is_active
variable is a boolean with a value of True
.
Converting data types
Sometimes, you may need to convert a variable from one data type to another. In Python, you can use the int()
, float()
, and str()
functions to convert a variable to an integer, float, or string, respectively.
Here is an example of how to convert a variable to a different data type:
age = 30
age_str = str(age) # age_str is now a string with a value of '30'
price = 10.99
price_int = int(price) # price_int is now an integer with a value of 10
Working with strings
In Python, you can use the +
operator to concatenate (join) two strings together.
Here is an example of how to concatenate two strings:
first_name = 'John'
last_name = 'Doe'
full_name = first_name + ' ' + last_name # full_name is now 'John Doe'
You can also use the *
operator to repeat a string a certain number of times.
Here is an example of how to repeat a string:
message = 'Hello, World! '
print(message * 3) # prints 'Hello, World! Hello, World! Hello, World! '
There are many other string methods and operations that you can perform in Python. For a complete reference, you can refer to the official Python documentation.