Python Tutorial
Python Flow Control
Python Functions
Python Data Types
Python Date and Time
Python Files
Python String
Python List
Python Dictionary
Python Variable
Python Input/Output
Python Exceptions
Python Advanced
In Python, variables are used to store data in memory, which can be used and manipulated throughout the program. In this tutorial, we'll cover creating variables, naming conventions, basic variable operations, and variable assignment.
In Python, you don't need to declare a variable or specify its data type before using it. Just assign a value to a variable using the =
operator, and Python will automatically determine the data type based on the value.
Example:
integer_var = 42 float_var = 3.14 string_var = "Hello, World!" list_var = [1, 2, 3, 4, 5]
Variable names in Python can contain letters (a-z, A-Z), digits (0-9), and underscores (_). However, they cannot start with a digit.
Valid variable names:
variable = 1 _variable = 2 variable_name = 3
Invalid variable names:
1_variable = 1 # Starts with a digit
It's recommended to use lowercase letters and underscores for variable names (also known as "snake_case").
You can perform basic arithmetic and other operations on variables, just like you would with values.
Example:
x = 10 y = 20 # Addition z = x + y print(z) # Output: 30 # Subtraction z = x - y print(z) # Output: -10 # Multiplication z = x * y print(z) # Output: 200 # Division z = x / y print(z) # Output: 0.5 # String concatenation greeting = "Hello, " name = "Alice" message = greeting + name print(message) # Output: Hello, Alice
You can assign multiple variables at once, or even swap the values of two variables without using a temporary variable.
Example:
# Assigning multiple variables at once x, y, z = 1, 2, 3 print(x, y, z) # Output: 1 2 3 # Swapping variable values x, y = y, x print(x, y) # Output: 2 1
In summary, variables in Python are used to store and manipulate data throughout a program. To create a variable, just assign a value to it using the =
operator, and Python will automatically determine its data type. Be sure to follow naming conventions and use valid characters in your variable names. You can perform basic operations on variables and assign multiple variables at once or swap their values easily.
Declaring and initializing variables in Python:
my_variable = 42
Naming conventions for Python variables:
user_age = 25
Variable assignment and reassignment in Python:
=
). Variables can be reassigned with new values.x = 5 x = x + 1 # Reassignment
Local and global variables in Python:
global_variable = 10 # Global variable def my_function(): local_variable = 5 # Local variable
Scope of variables in Python:
def my_function(): local_variable = 5 # Local variable within the function
Using constants and variables in Python:
MAX_VALUE = 100
Differences between variables and constants in Python:
PI = 3.14159 # Conventionally treated as a constant radius = 5 circumference = 2 * PI * radius