< All Topics

Python Foundation

1. Python Variables – Storing Data

A variable is a name given to a memory location in the computer’s RAM. Think of it as a container or a label that stores a specific value (data). You can refer to this data later in your program using the variable name.

variable_name = value

2. Rules for Naming Variables

Python has strict rules for how you can name your variables. If you break these, you will get a syntax error.

  1. Start with a Letter or Underscore, Cannot start with a Number
    • Correct: my_data, _private, name
    • Incorrect: 9lives, 1st_place
  2. No Special Symbols:
    • Only the underscore _ is allowed.
    • Incorrect: user@name, money$, first-name (Hyphens are not allowed)
  3. No Spaces:
    • Incorrect: my name
    • Correct: my_name
  4. Case Sensitive:
    • age, Age, and AGE are three different variables.
  5. Avoid Reserved Keywords:
    • Do not use Python keywords (like if, for, class) or built-in function names (like print, list) as variable names.

3. Naming Conventions (Styles)

While you can write variables in different styles, developers follow specific conventions to keep code readable.

StyleFormatExampleUsage in Python
Snake CaseAll lowercase, separated by _my_variable_nameRecommended for variables & functions.
Camel CaseFirst word lower, others CapitalizedmyVariableNameCommon in JavaScript/Java.
Pascal CaseEvery word CapitalizedMyVariableNameUsed for Classes in Python.

4. assigning Values

Python is flexible with assignments. You can assign variables in several unique ways.

  1. Standard Assignment
    • ex – name = "Lion"
  2. Multiple Values to Multiple Variables – Assign values to variables based on their position in a single line.
    • ex –
      • x, y, z = "Orange", "Banana", "Cherry"

        print(x) # Output: Orange
        print(y) # Output: Banana
  3. One Value to Multiple Variables – Assign the same value to several variables at once.
    • ex-
      • x = y = z = "Orange"

        print(x) # Output: Orange
        print(z) # Output: Orange
  4. Unpacking a Collection – If you have a list, tuple, or set, Python allows you to extract the values directly into variables.
    • ex –
      • fruits = ["apple", "banana", "cherry"]
        x, y, z = fruits # Unpacking

        print(x) # Output: apple
        print(y) # Output: banana
        print(z) # Output: cherry


5. Outputting Variables

We use the print() function to display the value stored in a variable.

x = "Python is awesome"
print(x)

# Combining text and variables
name = "Alice"
print("Hello " + name)  # Using + (Only works if both are strings)
print("Hello", name)    # Using comma (Works with any data type)

6. Global vs. Local Variables

The “Scope” determines where a variable can be seen or used in your code.

1. Local Variables

Created inside a function. They can only be used inside that specific function.

def my_func():
    local_var = "I am inside"
    print(local_var)

my_func()
# print(local_var) # This would cause an Error! (Cannot access outside)

2. Global Variables

Created outside of functions. They can be accessed anywhere in the code.

x = "awesome" # Global

def my_func():
    print("Python is " + x) # Accessible here

my_func()

3. The global Keyword

If you create a variable inside a function with the same name as a global variable, it usually creates a new local variable (shadowing). To modify the original global variable from inside a function, use the global keyword.

x = "awesome"

def my_func():
    global x   # Tells Python: "I want to use the global 'x', not create a new one"
    x = "fantastic"

my_func()
print("Python is " + x) # Output: Python is fantastic (The global value changed!)

7. Python Memory Management

In many languages, a variable is like a box where you store data.

In Python, a variable is like a Tag or Name Tag that is attached to an object in memory.

  1. Everything is an Object: – Whether it’s a number, a string, or a function, Python treats everything as an object stored in memory.
  2. Variables are References: When you write x = 10, Python does two things:
    • Creates an object representing the value 10 in memory (Heap).
    • Creates the name x and makes it “point” or refer to that object.
  3. Garbage Collection: – Python automatically cleans up objects that are no longer being used (when no variables point to them) to free up memory.

Check Memory Address: id()

You can see exactly where an object lives in memory using the built-in id() function.

x = 10
y = 10

print(id(x))  # Example: 140703649625032
print(id(y))  # Example: 140703649625032 (Same address!)

Python optimizes small integers by making different variables point to the exact same object to save memory.

8. Data Types

Python has several built-in data types. Since Python is Dynamically Typed, you do not need to declare the type (e.g., you don’t write int x = 5). Python figures it out based on the value.

To check the type of any variable, use the type() function.

CategoryType NameDescriptionExample
TextstrString (Text data)“Hello World”
NumericintInteger (Whole numbers)20, -5
floatFloating point (Decimals)20.5, 3.14
complexComplex numbers1j
SequencelistOrdered, mutable collection[“apple”, “banana”]
tupleOrdered, immutable collection(“apple”, “banana”)
rangeSequence of numbersrange(6)
MappingdictKey-Value pairs{“name”: “John”, “age”: 36}
SetsetUnordered, unique items{“apple”, “banana”}
BooleanboolLogical TruthTrue, False
BinarybytesBinary datab”Hello”
NullNoneTypeAbsence of valueNone

9. Mutable vs. Immutable Types

This is the most important concept in Python data types. It determines if an object can be changed after it is created.

1. Immutable Types – Cannot Change

If you try to change the value, Python destroys the old object and creates a new one. data types – int, float, bool, str, tuple.

# String is Immutable
name = "Sam"
# You cannot do name[0] = "P" to make it "Pam". This causes an error.

# Instead, you must create a new string:
name = "P" + name[1:] 

2. Mutable Types – Can Change

You can change the content without creating a new object. The memory address remains the same. data types – list, dict, set.

# List is Mutable
fruits = ["apple", "banana"]
print(id(fruits)) # Address A

fruits[0] = "cherry" # We modify the list in place
print(fruits)     # ['cherry', 'banana']
print(id(fruits)) # Address A (Still the same object!)

10. Type Casting – Conversion

You can convert variables from one type to another.

  • Implicit Conversion: Python automatically converts types (e.g., adding an int to a float results in a float).
  • Explicit Conversion: You manually convert types using constructor functions.
# Integer to Float
x = float(5)    # 5.0

# Float to Integer
y = int(3.9)    # 3 (Truncates the decimal, does not round!)

# Number to String
z = str(10)     # "10"

# String to List
s = list("Hello") # ['H', 'e', 'l', 'l', 'o']

11. Dynamic Typing

In static languages (like Java/C++), a variable declared as an Integer stays an Integer.

In Python, a variable can change its type at any time.

x = 5       # x is an int
print(type(x)) 

x = "Guru"  # x is now a str
print(type(x))

Best Practice: While Python allows this, avoid changing variable types frequently as it makes code hard to read.



Contents
Scroll to Top