Python Tutorial: Variables in Python.

Introduction to Variables in Python Programming

In Python programming, variables are used to store and manipulate data. They act as containers that hold values, which can be of different types such as numbers, strings, or even more complex objects. Understanding variables and their types is fundamental to writing effective and efficient Python code.

Variable Types in Python

Python is a dynamically-typed language, which means that variables do not have explicit types assigned to them. Instead, the type of a variable is determined at runtime based on the value it is assigned. However, Python does have built-in types that are commonly used:

Numeric Types

Python supports several numeric types, including:

  • int: Used to represent integers, such as 1, 100, or -5.
  • float: Used to represent floating-point numbers, such as 3.14 or -2.5.
  • complex: Used to represent complex numbers in the form a + bj, where a and b are floats and j is the imaginary unit.

Here are some examples of variables with numeric types:

num1 = 10
num2 = 3.14
num3 = 2 + 3j

String Type

The string type in Python is used to represent sequences of characters. Strings are enclosed in either single quotes (”) or double quotes (“”). Here’s an example:

name = "John Doe"

Boolean Type

The boolean type in Python is used to represent truth values, which can be either True or False. Boolean variables are often used in control structures and logical operations. Here’s an example:

is_true = True
is_false = False

Collection Types

Python provides several collection types to store multiple values:

  • List: An ordered collection of items. Lists are mutable, meaning they can be modified after creation. Here’s an example:
fruits = ['apple', 'banana', 'orange']
  • Tuple: Similar to lists, but tuples are immutable, meaning they cannot be modified once created. Here’s an example:
coordinates = (10, 20)
  • Dictionary: A collection of key-value pairs. Each key is unique and is used to access its associated value. Here’s an example:
person = {'name': 'John', 'age': 25, 'city': 'New York'}

Custom Types

In addition to the built-in types, Python allows you to define your own custom types using classes. By defining classes, you can create objects with their own attributes and methods. Here’s an example:

class Car:
    def __init__(self, brand, model):
        self.brand = brand
        self.model = model

my_car = Car("Toyota", "Camry")

Conclusion

Variables are an essential part of Python programming. They allow you to store and manipulate data of different types. Understanding the various types of variables in Python is crucial for writing effective and readable code. By using variables effectively, you can create more flexible and powerful programs.

Leave a Comment