In Python, variables are used to store and manipulate data. They act as containers that hold a value, which can be of various types such as numbers, strings, lists, or even more complex objects. Here’s an example of how to declare and assign a value to a variable:
# Variable declaration and assignment name = "John" age = 25 height = 1.75 is_student = True
In the example above, we declared and assigned values to four variables:
is_student. The variable
name stores a string,
age stores an integer,
height stores a floating-point number, and
is_student stores a boolean value.
Python is dynamically typed, which means you don’t need to explicitly declare the type of a variable. The type is inferred based on the value assigned to it. This allows you to assign different types of values to the same variable. For example:
x = 5 print(x) # Output: 5 x = "Hello" print(x) # Output: Hello
You can also assign the result of an expression or a function call to a variable:
a = 10 b = 5 sum_result = a + b print(sum_result) # Output: 15 name = input("Enter your name: ") print("Hello,", name) # Output: Hello, John (if the user enters John)
Variables can be updated by assigning a new value to them:
x = 5 print(x) # Output: 5 x = 10 print(x) # Output: 10
Variables can be used in expressions and statements to perform operations, comparisons, or any other desired computations.