🐍

Overview of Python Variables and Concepts

Mar 23, 2025

Python Variables

Introduction

  • Variables in Python are used to store data that can be referenced and manipulated during program execution.
  • Python variables do not require explicit declaration of type; the type is inferred based on the value assigned.
  • Variables act as placeholders for data, allowing for storage and reuse of values.

Example

x = 5 name = "Samantha" print(x) print(name)

Output:

5 Samantha

Key Concepts

Rules for Naming Variables

  • Variable names can contain letters, digits, and underscores (_).
  • Cannot start with a digit.
  • Case-sensitive (myVar and myvar are different).
  • Avoid using Python keywords (e.g., if, else, for)._

Valid Example:

age = 21 _colour = "lilac" total_score = 90

Invalid Example:

1name = "Error" # Starts with a digit class = 10 # 'class' is a reserved keyword user-name = "Doe" # Contains a hyphen

Assigning Values to Variables

  • Use = operator to assign values.
  • Dynamic Typing: A variable can hold different types of values during execution.

Example:

x = 10 x = "Now a string"

Multiple Assignments

  • Assign the same value to multiple variables:
a = b = c = 100

Output:

100 100 100
  • Assign different values to multiple variables in one line:
x, y, z = 1, 2.5, "Python"

Output:

1 2.5 Python

Type Casting

  • Convert one data type to another using functions like int(), float(), str().

Example:

s = "10" n = int(s) f = float(5) s2 = str(25)

Output:

10 5.0 25

Getting the Type of Variable

  • Use type() function to determine the type.

Example:

n = 42 print(type(n))

Output:

<class 'int'>

Scope of a Variable

  • Local Variables: Defined inside a function and accessible only there.
  • Global Variables: Defined outside any function and accessible globally. Use global keyword to modify inside functions.

Example:

def f(): a = "I am local" print(a) a = "I am global" print(a)

Output:

I am local I am global

Object Reference

  • Variables hold references to objects, not the objects themselves.
  • Reassigning a variable creates a new reference.

Deleting a Variable

  • Use del keyword to remove a variable.

Example:

x = 10 del x
  • Accessing x after deletion will raise NameError.

Practical Examples

Swapping Two Variables

  • Swap values using multiple assignments.

Example:

a, b = 5, 10 a, b = b, a

Output:

10 5

Counting Characters in a String

  • Use len() to find the length of a string.

Example:

word = "Python" length = len(word)

Output:

Length of the word: 6

This overview provides a foundational understanding of how variables work in Python, covering key principles such as naming conventions, value assignment, type casting, and variable scope.