Command Palette

Search for a command to run...

Variables & Data Types

Understanding variables, data types, and type conversion in Python.

Variables

  • Variables store data values.
  • No need to declare type - Python infers it automatically.
  • Variable names must start with letter or underscore.
  • Case-sensitive: 'age' and 'Age' are different variables.
# Creating variables
name = "Alice"
age = 25
height = 5.6
is_student = True

print(name, age, height, is_student)

Data Types

  • int: Whole numbers (1, 42, -10)
  • float: Decimal numbers (3.14, -0.5)
  • str: Text in quotes ('hello', "world")
  • bool: True or False
  • Use type() to check variable type.
# Different data types
x = 10           # int
y = 3.14         # float
name = "Python"  # str
active = True    # bool

print(type(x))    # <class 'int'>
print(type(name)) # <class 'str'>

Type Conversion

  • Convert between types using int(), float(), str(), bool().
  • Useful when reading user input or processing data.
  • Be careful - some conversions may fail or lose data.
# Type conversion
x = "123"
y = int(x)        # Convert string to int
print(y + 10)     # 133

a = 5
b = str(a)        # Convert int to string
print(b + "0")    # "50"

c = float("3.14") # Convert string to float
print(c * 2)      # 6.28

Multiple Assignment

  • Assign multiple variables in one line.
  • Swap variables without temporary variable.
  • Unpack values from lists or tuples.
# Multiple assignment
x, y, z = 1, 2, 3
print(x, y, z)  # 1 2 3

# Swap variables
a, b = 10, 20
a, b = b, a
print(a, b)     # 20 10

# Same value to multiple variables
x = y = z = 0