Variables & Data Types

Variables are used to store data in a program. In Python, you don't need to declare a variable's type explicitly; the interpreter infers it from the value assigned to it. This is called dynamic typing.

Creating Variables

In Python, you create a variable by assigning a value to it using the equals sign (=):

name = "John"
age = 25
height = 1.75
is_student = True

In this example, we've created four variables with different types:

  • name is a string (text)
  • age is an integer (whole number)
  • height is a float (decimal number)
  • is_student is a boolean (True or False)

Variable Naming Rules

When naming variables in Python, you must follow these rules:

  • Variable names can contain letters, numbers, and underscores
  • Variable names must start with a letter or underscore
  • Variable names cannot start with a number
  • Variable names are case-sensitive (age, Age, and AGE are three different variables)
  • Variable names cannot be Python keywords (like if, for, while, etc.)

Python Data Types

Python has several built-in data types:

Numeric Types

  • int: Integer numbers (e.g., 42, -7)
  • float: Floating-point numbers (e.g., 3.14, -0.001)
  • complex: Complex numbers (e.g., 3+4j)

Text Type

  • str: Strings (e.g., "Hello", 'Python')

Boolean Type

  • bool: Boolean values (True or False)

Sequence Types

  • list: Ordered, mutable collection (e.g., [1, 2, 3])
  • tuple: Ordered, immutable collection (e.g., (1, 2, 3))
  • range: Sequence of numbers (e.g., range(6))

Mapping Type

  • dict: Key-value pairs (e.g., {"name": "John", "age": 25})

Set Types

  • set: Unordered collection of unique items (e.g., {1, 2, 3})
  • frozenset: Immutable version of a set

None Type

  • NoneType: The None object, representing the absence of a value

Type Conversion

You can convert between different data types using conversion functions:

# Convert to integer
x = int(3.14)    # x will be 3
y = int("10")    # y will be 10

# Convert to float
a = float(5)     # a will be 5.0
b = float("3.14") # b will be 3.14

# Convert to string
c = str(42)      # c will be "42"
d = str(3.14)    # d will be "3.14"

# Convert to boolean
e = bool(0)      # e will be False
f = bool(1)      # f will be True
g = bool("")     # g will be False
h = bool("Hello") # h will be True

Checking Types

You can check the type of a variable using the type() function:

x = 42
print(type(x))  # 

y = "Hello"
print(type(y))  # 

z = 3.14
print(type(z))  # 

String Operations

Strings are one of the most commonly used data types. Here are some common string operations:

String Concatenation

first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name  # "John Doe"

String Repetition

pattern = "-" * 10  # "----------"

String Indexing

message = "Hello, World!"
first_char = message[0]   # "H"
last_char = message[-1]   # "!"

String Slicing

message = "Hello, World!"
substring = message[0:5]  # "Hello"
from_sixth = message[7:]  # "World!"
to_fifth = message[:5]    # "Hello"

String Methods

message = "Hello, World!"
print(message.upper())         # "HELLO, WORLD!"
print(message.lower())         # "hello, world!"
print(message.replace("Hello", "Hi"))  # "Hi, World!"
print(message.split(", "))     # ["Hello", "World!"]
print(len(message))            # 13

F-Strings (Formatted String Literals)

F-strings provide a concise and convenient way to embed expressions inside string literals:

name = "Alice"
age = 30
message = f"My name is {name} and I am {age} years old."
print(message)  # "My name is Alice and I am 30 years old."

# You can also include expressions
price = 49.95
quantity = 3
total = f"Total: ${price * quantity:.2f}"
print(total)  # "Total: $149.85"

Variable Scope

The scope of a variable determines where in your code the variable is accessible. Python has two main types of variable scope:

Global Scope

Variables defined at the top level of a script or module have global scope and can be accessed throughout the code:

global_var = 10  # Global variable

def my_function():
    print(global_var)  # Accessing global variable

my_function()  # Outputs: 10

Local Scope

Variables defined inside a function have local scope and can only be accessed within that function:

def my_function():
    local_var = 20  # Local variable
    print(local_var)

my_function()  # Outputs: 20
# print(local_var)  # This would cause an error

The global Keyword

You can modify a global variable from within a function using the global keyword:

counter = 0  # Global variable

def increment():
    global counter
    counter += 1
    print(counter)

increment()  # Outputs: 1
increment()  # Outputs: 2

Try experimenting with variables and data types in the code playground below!

Quick Quiz

Which of the following is NOT a valid variable name in Python?

Code Playground

Code output will appear here...