Variables and Data Types in Python

1. Variables

A variable is a name that refers to a value stored in memory. Variables are used to store data that can be referenced and manipulated throughout your program.

Declaring Variables
  • Variables are created when you assign a value to them.x = 10 # Integer name = "Alice" # String pi = 3.14 # Float
  • Python allows you to assign multiple variables in one line:a, b, c = 1, 2, 3
Rules for Naming Variables
  • Variable names must start with a letter or an underscore (_).
  • Names can only contain letters, numbers, and underscores (e.g., var_name1).
  • Python is case-sensitive (name and Name are different).
  • Avoid using Python reserved keywords (e.g., if, while, def, etc.).

2. Data Types

Python is a dynamically-typed language, meaning you don’t need to specify the type of a variable—it is inferred from the assigned value.

Common Data Types in Python
  1. Numeric Types
    • Integer (int): Whole numbers.age = 25
    • Floating-Point (float): Numbers with decimal points.price = 19.99
    • Complex (complex): Numbers with real and imaginary parts.z = 3 + 4j
  2. String (str)
    • A sequence of characters enclosed in single or double quotes.greeting = "Hello, World!"
    • Supports operations like slicing and concatenation:name = "Alice" print(name[0]) # Output: A print(name[1:4]) # Output: lic
  3. Boolean (bool)
    • Represents True or False values. is_logged_in = True
  4. Sequence Types
    • List (list): Ordered, mutable collection of items.numbers = [1, 2, 3, 4]
    • Tuple (tuple): Ordered, immutable collection.point = (1, 2)
  5. Dictionary (dict)
    • A collection of key-value pairs.person = {"name": "Alice", "age": 25}
  6. Set (set)
    • Unordered, unique collection of items.fruits = {"apple", "banana", "cherry"}

3. Type Checking and Conversion

  1. Check Data Type
    Use the type() function to find the type of a variable. x = 10 print(type(x)) # Output: <class 'int'>
  2. Type Conversion
    Convert between types using functions like int(), float(), str(), etc.x = 5.5 y = int(x) # Converts float to int (y = 5) z = str(x) # Converts float to string (z = "5.5")

By understanding variables and data types, you can effectively store, manipulate, and work with different kinds of data in Python.

CATEGORIES:

BASICS

Tags:

One response

Leave a Reply

Your email address will not be published. Required fields are marked *