What are Variables

A program is essentially a set of instructions that tells a computer what to do. Just like a recipe guides a chef, a program guides a computer to perform specific tasks—whether it’s calculating numbers, playing a song, displaying a website, or running a game.

Programs are written in programming languages like Python, Java, or C++, which help humans communicate their logic to machines. When you run a program, your computer follows those instructions step by step to get something done.

A program is a collection of instructions written in a programming language to carry out specific tasks.

Every program is built on two essential components:

  1. Data – Information such as numbers, facts, or values that the program processes.
  2. Instructions – A sequence of steps that operate on the data to achieve desired outcomes.

Regardless of the programming language used, both data and instructions are required to create a functioning program.

Without data, instructions alone have no purpose.

What are Variables in Python?

In Python, a variable is essentially a named storage location in your computer’s memory that holds a value. Think of it as a label or a box with a name on it, and inside that box, you put some data.

Unlike some other programming languages, Python is dynamically typed. This means you don’t need to declare the type of a variable (like int, string, float) explicitly when you create it. Python infers the type based on the value you assign to it.

Key characteristics of Python variables:

  • Names: They must start with a letter (a-z, A-Z) or an underscore (_). They can contain letters, numbers, and underscores. They are case-sensitive (myVar is different from myvar).
  • Values: They hold data of various types (numbers, text, true/false, etc.).
  • Mutable/Immutable: The values they refer to can be mutable (changeable, like lists) or immutable (unchangeable, like numbers, strings, tuples). However, the variable itself can always be reassigned to refer to a different value.

Methods to Initialize Variables

Initializing a variable simply means assigning a value to it for the first time.

  1. Direct Assignment: This is the most common and straightforward method.
  2. Multiple Assignment (Chained Assignment): Assign the same value to multiple variables simultaneously.
  3. Multiple Assignment (Unpacking): Assign multiple values to multiple variables in a single line. The number of variables on the left must match the number of values on the right. This is commonly used for swapping variable values:
  4. From Function Return Values: If a function returns a value, you can assign it directly to a variable.
  5. From User Input: Using the input() function.

In summary, Python variables are flexible labels that point to objects in memory. Python’s dynamic typing and object model simplify development by handling memory management and type inference automatically, while understanding the distinction between mutable and immutable objects is crucial for predicting program behavior.

Python Variable Naming: Rules & Conventions 📝

In Python, while variables are dynamically typed (meaning you don’t declare their type explicitly), there are strict rules and widely accepted conventions for naming them. Adhering to these rules and conventions makes your code readable, maintainable, and less prone to errors. ✨


Strict Rules (Must Follow) 🚨

If you break these, your code will raise a SyntaxError or NameError.

  • Must start with a letter or an underscore (_): 🅰️
    • Valid: name, _age, my_variable
    • Invalid: 1name (starts with a number), !variable (starts with a special character)
  • Can only contain letters, numbers, and underscores (_): 🔢
    • Valid: user_id, product_name_2, _temp_data
    • Invalid: user-name (contains a hyphen), total amount (contains a space), item# (contains a special character)
  • Are case-sensitive: age, Age, and AGE are three different variables. 🔍
  • Cannot be Python keywords (reserved words): 🚫 Python has a list of words that have special meanings (e.g., if, else, for, while, class, def, import, True, False, None, and, or, not, etc.). You cannot use these as variable names.
    • Invalid: if = 10, class = "Python" You can get a list of keywords using: <!– end list –>
    🔑

Naming Conventions (PEP 8 – Recommended Best Practices) ✅

While these are not strict rules that break your code, following them is crucial for writing “Pythonic” code that is consistent, readable, and easy for other Python developers (and your future self!) to understand. These guidelines are part of PEP 8 (Python Enhancement Proposal 8), the official style guide for Python code. 📜

  • Use lowercase with underscores (snake_case) for variables and functions: 🐍 This is the most common and recommended convention for general variables.
    • Good: first_name, total_price, is_active
    • Avoid (though technically valid): firstName, TotalPrice (camelCase/PascalCase are less common for variables in Python)
  • Be descriptive and meaningful: ✍️ Choose names that clearly indicate the purpose or content of the variable. Avoid single-letter variable names unless it’s a simple loop counter (i, j) or a very short-lived temporary variable.
    • Good: customer_age, inventory_count, email_address
    • Bad: x, num, e (unless context is super clear)
  • Constants should be in ALL CAPS with underscores: ⬆️ While Python doesn’t have true “constants” (values that cannot be reassigned), by convention, variables intended to be constants are named in uppercase to signify that their value should not change.
    • Example: MAX_RETRIES = 5, PI = 3.14159
  • Leading underscore (_variable_name): 💡 A single leading underscore suggests that a variable is intended for “internal use” within a module or class. It’s a convention, not an enforcement, meaning you can still access it, but you’re typically not supposed to. 🤫
  • Double leading underscore (__variable_name): 🔒 Used for “name mangling” within classes, making variables essentially private to the class to avoid naming conflicts in subclasses. This is a more advanced concept.
  • Double leading and trailing underscores (__variable_name__): ✨ These names are reserved for “magic methods” or “dunder methods” (e.g., __init__, __str__). Avoid using this pattern for your own variable names.

Python Keywords: Special Reserved Words 🔑

Python keywords are special reserved words that have specific meanings and purposes in the language. You cannot use these words as variable names, function names, class names, or any other identifiers, as doing so would cause a SyntaxError. 🚫

These keywords are fundamental to Python’s syntax and structure, enabling you to define logic, control flow, functions, classes, and more. 🏗️

Here is the current list of Python keywords (as of Python 3.x), which you can also retrieve programmatically using the keyword module:

  • False
  • None 👻
  • True
  • and 🤝
  • as 🏷️
  • assert
  • async (introduced in Python 3.5 for asynchronous programming) ⏳
  • await (introduced in Python 3.5 for asynchronous programming) ⏳
  • break 🛑
  • class 🏛️
  • continue ➡️
  • def ⚙️
  • del 🗑️
  • elif ➡️❓
  • else
  • except 🛡️
  • finally
  • for 🔄
  • from 📥
  • global 🌍
  • if
  • import 📦
  • in 📍
  • is 🆔
  • lambda ➡️
  • nonlocal (introduced in Python 3.x for nested function scope) 🏘️
  • not ✖️
  • or
  • pass 🚶
  • raise ⬆️
  • return ↩️
  • try
  • while 🔁
  • with 🤝
  • yield 🍎

Important Notes: 📌

  • Case-Sensitivity: All Python keywords are in lowercase, except for True, False, and None, which are capitalized. You must use them exactly as they appear. 🔡⬆️
  • Checking Keywords: You can always get the current list of keywords for your Python interpreter version by running this simple code: This list might have minor additions or changes in future Python versions, so using keyword.kwlist is the most reliable way to check. 🔍

ific type, provide more complex examples, or perhaps integrate them all into a single, larger program file?

Similar Posts

  •  Duck Typing

    Python, Polymorphism allows us to use a single interface (like a function or a method) for objects of different types. Duck Typing is a specific style of polymorphism common in dynamically-typed languages like Python. What is Duck Typing? 🦆 The name comes from the saying: “If it walks like a duck and it quacks like…

  • recursive function

    A recursive function is a function that calls itself to solve a problem. It works by breaking down a larger problem into smaller, identical subproblems until it reaches a base case, which is a condition that stops the recursion and provides a solution to the simplest subproblem. The two main components of a recursive function…

  • start(), end(), and span()

    Python re start(), end(), and span() Methods Explained These methods are used with match objects to get the positional information of where a pattern was found in the original string. They work on the result of re.search(), re.match(), or re.finditer(). Methods Overview: Example 1: Basic Position Tracking python import re text = “The quick brown fox jumps over the lazy…

  • Strings in Python Indexing,Traversal

    Strings in Python and Indexing Strings in Python are sequences of characters enclosed in single quotes (‘ ‘), double quotes (” “), or triple quotes (”’ ”’ or “”” “””). They are immutable sequences of Unicode code points used to represent text. String Characteristics Creating Strings python single_quoted = ‘Hello’ double_quoted = “World” triple_quoted = ”’This is…

  • Iterators in Python

    Iterators in Python An iterator in Python is an object that is used to iterate over iterable objects like lists, tuples, dictionaries, and sets. An iterator can be thought of as a pointer to a container’s elements. To create an iterator, you use the iter() function. To get the next element from the iterator, you…

  • ASCII ,Uni Code Related Functions in Python

    ASCII Code and Related Functions in Python ASCII (American Standard Code for Information Interchange) is a character encoding standard that assigns numerical values to letters, digits, punctuation marks, and other characters. Here’s an explanation of ASCII and Python functions that work with it. ASCII Basics Python Functions for ASCII 1. ord() – Get ASCII value of a…

Leave a Reply

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