Understanding Data Types and Variables in Python

Python offers a wide variety of built-in data types that make it versatile for many tasks. In this lesson, we will explore the most common data types and how to work with variables in Python.

Python Data Types

1. Numbers

Python supports multiple numeric types:

  • Integers (int): Whole numbers without decimals.
  • Floating Point Numbers (float): Numbers with decimals.
  • Complex Numbers (complex): Numbers with a real and imaginary part, denoted as a + bj.
int_number = 5
float_number = 5.0
complex_number = 3 + 4j

2. Boolean (bool)

Booleans represent truth values: True or False. They are often used in conditional statements.

is_valid = True

3. Strings (str)

Strings are ordered sequences of characters used for representing text. They are immutable, meaning they cannot be changed after creation.

name = "John Doe"

4. Lists (list)

Lists are ordered and mutable collections of items. Items within a list can be of different types. Lists are defined using square brackets.

fruits = ["apple", "banana", "cherry"]
Example: List Manipulation
numbers = [1, 2, 3, 4, 5]
numbers.append(6)
print(numbers)  # Outputs: [1, 2, 3, 4, 5, 6]
print(numbers[1])  # Outputs: 2 (lists are zero-indexed)

5. Tuples (tuple)

Tuples are ordered collections like lists, but they are immutable. Tuples are created using parentheses.

point = (1, 2, 3)
Example: Attempting to Modify a Tuple
my_tuple = (1, 2, 3)
try:
    my_tuple[1] = 4  # This will raise a TypeError
except TypeError as e:
    print("Error:", e)

6. Dictionaries (dict)

Dictionaries store key-value pairs. Keys must be unique and immutable, but values can be of any data type.

person = {"name": "Alice", "age": 25}
Example: Dictionary Manipulation
person = {"name": "John", "age": 30, "city": "New York"}
person["occupation"] = "Software Developer"
print(person)

7. Sets (set)

Sets are unordered collections of unique elements. They are useful for eliminating duplicates and performing mathematical operations like unions and intersections.

colors = {"red", "blue", "green"}
Example: Set Operations
my_tuple = (10, 20, 30, 40, 50)
my_set = set(my_tuple)
my_set.add(60)
print(my_set)

Type Conversion in Python

Python provides built-in functions for converting between data types:

str_number = "123"
int_number = int(str_number)  # Converts string to integer

Variables in Python

Variables in Python are names that refer to data stored in memory. Python uses dynamic typing, meaning the type of the variable can change depending on what is assigned to it.

x = 10  # integer
greeting = "Hello, world!"  # string

Example: String Manipulation

greeting = "Hello, world!"
uppercase_greeting = greeting.upper()
personalized_greeting = greeting.replace("world", "Alice")
reversed_greeting = personalized_greeting[::-1]

print(uppercase_greeting)  # Outputs: "HELLO, WORLD!"
print(personalized_greeting)  # Outputs: "Hello, Alice!"
print(reversed_greeting)  # Outputs: "!ecilA ,olleH"

Exercises

Exercise 1: Basic Variables and Types

Create variables of each type (int, float, str, bool) and print their types using the type() function.

x = 10
print(type(x))  # Output: <class 'int'>

Exercise 2: List Operations

Create a list of five integers. Perform the following:

  • Print the list.
  • Append an element.
  • Print the third and fourth elements.
numbers = [1, 2, 3, 4, 5]
numbers.append(6)
print(numbers[2], numbers[3])  # Outputs: 3 4

Exercise 3: String Manipulation

Given the string "Hello, world!", perform the following:

  • Convert it to lowercase.
  • Replace "Hello, " with "Perfect".
  • Reverse the string.
greeting = "Hello, world!"
print(greeting.lower())  # Outputs: "hello, world!"
print(greeting.replace("Hello, ", "Perfect"))  # Outputs: "Perfectworld!"
print(greeting[::-1])  # Outputs: "!dlrow ,olleH"

Exercise 4: Dictionary Lookup

Create a dictionary with keys name, age, and city. Print the entire dictionary, access the age, and add an occupation.

person = {"name": "John", "age": 30, "city": "New York"}
person["occupation"] = "Developer"
print(person)

Exercise 5: Tuple and Set Operations

Create a tuple with elements (10, 20, 30, 40, 50), convert it to a set, and add an element to the set.

my_tuple = (10, 20, 30, 40, 50)
my_set = set(my_tuple)
my_set.add(60)
print(my_set)

Exercise 6: Type Conversion and Calculation

Given the list of strings ["1", "2", "3", "4"], convert each string to an integer, sum them, and print the result.

string_numbers = ["1", "2", "3", "4"]
int_numbers = [int(num) for num in string_numbers]
print(sum(int_numbers))  # Outputs: 10

This SEO-friendly guide enhances clarity, includes rich keyword usage for better searchability, and incorporates detailed explanations and practical examples to help learners grasp Python data types and variable manipulation.