Lesson 1: Variables and Constants
In this lesson, we will explore how to use variables and constants in Python. You will learn how to declare variables, assign values to them, and understand the concept of constants in Python. This is a fundamental concept, as variables are essential for storing and manipulating data in any programming language, and constants help to maintain values that should remain unchanged throughout the program.
1. Declaring Variables
A variable is a name that is used to store a value. In Python, you don’t need to specify the type of the variable when declaring it—Python is a dynamically typed language, which means it automatically infers the type of the variable based on the value assigned to it.
To declare a variable in Python, you simply assign a value to a name using the assignment operator =.
Syntax:
For example:
name = “John”
height = 5.9
In the example above:
- ageis a variable that holds an integer value 25.
- nameis a variable that holds a string “John”.
- heightis a variable that holds a floating-point value 9.
Python allows you to store many types of data in variables, such as:
- Integers(whole numbers)
- Floats(decimal numbers)
- Strings(text)
- Booleans(True/False)
2. Assigning Values
Once a variable is declared, you can assign it a new value at any point in your program. You simply use the assignment operator = again.
Example:
x = 20 # Re-assigning a new value to x
In this example, the value of x is initially 10, but it is later changed to 20. This demonstrates how the value of a variable can be updated during the execution of a program.
Python also allows multiple variables to be declared and assigned values in one line:
Here, the variable a is assigned 1, b is assigned 2, and c is assigned 3.
3. Understanding Constants in Python
In Python, constants are values that cannot be changed once they are assigned. However, Python does not have a built-in mechanism to define constants like some other programming languages. The convention is to use uppercase letters for variable names that represent constant values. While this is just a naming convention, it helps signal to other programmers that the value of the variable should not be changed.
Example:
PI = 3.14159
MAX_USERS = 100
In the example:
- PIrepresents the constant value of pi, typically used in mathematical calculations.
- MAX_USERSrepresents the maximum number of users allowed, which should not change during the program’s execution.
Although Python does not enforce the immutability of constants, developers should follow the convention of using uppercase letters to signify constants and avoid changing their values.
For immutable values (like numbers, strings, and tuples), you can also create “constant-like” behavior. For example:
Leave a Reply