Python Variables and Data Types

Learn Python @ Freshers.in

Understanding variables and data types is fundamental in Python programming. In this comprehensive guide, we will delve into Python’s core concepts, covering variables, numbers, strings, lists, dictionaries, and more. You’ll learn through detailed examples with real data, providing you with a strong foundation in Python programming.

Variables in Python

A variable is a container for storing data values. In Python, variables are created when you assign a value to them. Variable names are case-sensitive and must start with a letter or an underscore.

Example:

# Variable assignment
x = 10
name = "John"

Data Types in Python

Python supports various data types, each serving a specific purpose. Let’s explore some of the essential data types:

1. Numbers

Python supports integers, floating-point numbers, and complex numbers.

Example:

# Integer
age = 25

# Floating-point
price = 12.99

# Complex
z = 2 + 3j

2. Strings

Strings are sequences of characters, enclosed in single, double, or triple quotes.

Example:

# Single quotes
single_quoted = 'Hello, Python!'
# Double quotes
double_quoted = "Python is awesome."
# Triple quotes (useful for multi-line strings)
multi_line = '''
This is a
multi-line string.
'''
# Single quotes
single_quoted = 'Hello, Python!'
# Double quotes
double_quoted = "Python is awesome."
# Triple quotes (useful for multi-line strings)
multi_line = '''
This is a
multi-line string.
'''

3. Lists

Lists are ordered and mutable collections that can hold a variety of data types.

Example:

fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed_list = [42, "Python", 3.14, True]
4. Dictionaries

Dictionaries are unordered collections of key-value pairs.

Example:

person = {
    "name": "John",
    "age": 30,
    "city": "New York"
}

5. Boolean

Boolean values represent truth values, either True or False.

Example:

is_python_fun = True
is_raining = False

Type Conversion

You can convert data from one type to another using type casting functions.

Example:

# Converting a number to a string
num = 42
num_as_str = str(num)
Author: user