RBDBlog

Python Variables Tutorial

Variables are fundamental elements in programming that allow you to store and manipulate data. In Python, variables are dynamically typed, meaning you don’t need to declare their type explicitly. They can hold various types of data, such as numbers, strings, lists, and more. This tutorial will cover the basics of Python variables.

1. Variable Declaration and Assignment

In Python, you can create a variable by simply assigning a value to a name. Here’s a basic example:

# Variable declaration and assignment 
my_variable = 42

In this example, my_variable is the name of the variable, and 42 is the value assigned to it.

2. Variable Naming Rules

  • Variable names must start with a letter (a-z, A-Z) or an underscore _.
  • The rest of the variable name can consist of letters, numbers, and underscores.
  • Variable names are case-sensitive (my_variable is different from My_Variable).

# Valid variable names 
name = "John" 
age = 25 m
y_var = 3.14 
# Invalid variable names 
2nd_variable = "This is invalid" # Starts with a number 
my-variable = 1 # Contains a hyphen

3. Data Types

Python supports various data types. The type of a variable is determined dynamically based on the value assigned to it. Common data types include:

  • int: Integer numbers (42, -10, 1000)
  • float: Floating-point numbers (3.14, 2.0, -0.5)
  • str: Strings (text) ("Hello", 'Python', '')
  • bool: Boolean values (True or False)


# Examples of different data types 
integer_var = 42 
float_var = 3.14 
string_var = "Hello, Python!" 
boolean_var = True 

4. Multiple Assignment

You can assign multiple variables in a single line:

# Multiple assignment
x, y, z = 10, 20, 30

This is equivalent to:

x = 10
y = 20
z = 30

5. Reassigning Variables

Variables can be reassigned with new values:

# Reassigning variables
count = 5
count = count + 1  # Incrementing the value

6. Print Statements

Use the print function to display the value of a variable:

# Printing variables
name = "Alice"
print("Hello, " + name + "!")

7. Type Conversion

You can convert variables from one type to another using type casting functions like int(), float(), and str():

# Type conversion
num_str = "42"
num_int = int(num_str)

This tutorial covers the basics of Python variables. As you progress in your Python journey, you’ll encounter more advanced topics related to variables and data manipulation. Experiment with different variable types and assignments to deepen your understanding.

Next Up:

  1. Control Flow
  2. Functions

Return to homepage