Search Here

Python Data Types

Python has several built-in data types that can be used to store different kinds of information. These data types include:

Numbers: Python has two types of numbers: integers and floating-point numbers. Integers are whole numbers (e.g., 1, 2, 3) and floating-point numbers are numbers with a decimal point (e.g., 1.0, 2.5, 3.14). You can use the int() and float() functions to convert numbers from one type to another.

x = 10  # integer
y = 20.5  # floating-point number

print(type(x))  # Output: <class 'int'>
print(type(y))  # Output: <class 'float'>

# You can use the int() function to convert a floating-point number to an integer
z = int(y)
print(z)  # Output: 20
print(type(z))  # Output: <class 'int'>

# You can use the float() function to convert an integer to a floating-point number
a = float(x)
print(a)  # Output: 10.0
print(type(a))  # Output: <class 'float'>

Strings: Strings are sequences of characters and are used to represent text. You can use single quotes (‘) or double quotes (“) to define a string. For example: "Hello, World!" or 'Hello, World!'. You can use the len() function to find the length of a string.

x = "Hello, World!"
y = 'Hello, World!'

print(len(x))  # Output: 13
print(len(y))  # Output: 13

# You can use single quotes inside a string defined with double quotes and vice versa
x = "Hello, 'John'"
y = 'Hello, "John"'

print(x)  # Output: Hello, 'John'
print(y)  # Output: Hello, "John"

Lists: Lists are ordered sequences of objects. You can define a list by enclosing a comma-separated sequence of objects in square brackets ([]). For example: [1, 2, 3] or ['apple', 'banana', 'cherry']. You can access the elements of a list using their indexes (e.g., my_list[0] returns the first element of the list). You can use the len() function to find the length of a list.

# Define a list
x = [1, 2, 3]

# Access the elements of the list using their indexes
print(x[0])  # Output: 1
print(x[1])  # Output: 2
print(x[2])  # Output: 3

# You can also use negative indexes to access the elements of the list from the end
print(x[-1])  # Output: 3
print(x[-2])  # Output: 2
print(x[-3])  # Output: 1

# You can use the len() function to find the length of the list
print(len(x))  # Output: 3

# You can modify the elements of a list by assigning new values to them
x

Leave a Comment