Variables & Constants
Introduction to Variables
Variables are used to store and manipulate data in a computer program. Think of them as named containers for different types of information.
Variables allow us to store values and retrieve them later when needed. They help in simplifying the code and make it easier to understand and maintain. With variables, we can perform operations and calculations using the stored data. For example:
# Declaration and initialization of variables age = 16; height = 1.75 name = "John"# Using variables in calculations bmi = weight / (height * height);# Displaying the result print("Name: " + name); print("Age: " + age) print("BMI: " + bmi)
In the above example, we declared and initialized three variables: "age" (an integer), "height" (a float), and "name" (a string).
We then used the variables in a calculation to calculate the body mass index (BMI). Finally, we displayed the values of the variables along with the calculated BMI.
What is a variable?
Declaring and Assigning Variables
Declaring Variables
To declare a variable, in most languages we need to specify its data type and give it a name. For example, in C# we can declare a variable to store a number like this:
int age;
Here, we have declared a variable named "age" of the type integer, which is a whole number.
Note: In Python you don't need to declare the type before you use is, as it uses implicit typing, where the data type is automatically guessed when you assign a value to the variable.
Assigning Variables
Once a variable is declared, we can assign a value to it using the assignment operator (=). For example, to assign the value 16 to the "age" variable, we do:
age = 16;
Now, the "age" variable holds the value 16.
Combining Declaration and Assignment
Combining Declaration and Assignment
In python combine the declaration and assignment of a variable in a single statement.
Here's an example:
name = "John";
In this example we set the variable name to the value "John". Python automatically assigns the data type String to the variable, which is short for "String of characters".
What is the correct syntax for declaring a variable in Python?
Variable Naming Rules
When naming variables in Python, you need to follow certain rules:
- A variable name can only contain letters (a to z, A to Z), digits (0 to 9), and underscores (_).
- It cannot start with a digit.
- Variable names are case-sensitive, which means variable and Variable are considered different.
- Spaces and special characters (such as !, @, #) are not allowed in variable names.
- Python keywords (reserved words) such as if, for, and while cannot be used as variable names.
Examples of Valid Variable Names
- age
- num_of_students
- total_count
- _name
- first_name
Examples of Invalid Variable Names
- 2friends (starts with digit)
- my variable (contains space)
- if (reserved keyword)
- @name (contains special character)
Which of the following is NOT a valid variable name?
Python Reserved Words
In Python there are a number of words that cannot be used as a variable. If you try to use them the Python will raise a syntax error. Here are the words. You don't need remember then all at once, but you need to be aware of them!
Keywords
| False | await | else | import | pass |
| None | break | except | in | raise |
| True | class | finally | is | return |
| and | continue | for | lambda | try |
| as | def | from | nonlocal | while |
| assert | del | global | not | with |
| async | elif | if | or | yield |
Built-in Constants
| True | False | None |
Which of the following is a Python reserved word?
Built-in Functions
Python also has a number of in-built functions that you should use as variable names. If you overwrite the in-built variables then Python won't complain but it's bad practice and can cause strange and unexpected behaviour in your program!
| abs() | divmod() | input() | open() | str() |
| all() | enumerate() | int() | ord() | sum() |
| any() | eval() | isinstance() | pow() | tuple() |
| bin() | exec() | issubclass() | print() | type() |
| bool() | filter() | iter() | round() | vars() |
| bytearray() | float() | len() | set() | zip() |
| bytes() | format() | list() | slice() | __import__() |
| callable() | frozenset() | locals() | sorted() | |
| chr() | getattr() | map() | staticmethod() | |
| classmethod() | globals() | max() | str() |
Sensible vs Not Sensible Variable Names
Sensible Variable Names
In Python, it is considered good practice to use sensible variable names that describe the purpose or content of the variable. This improves code readability and makes it easier for other developers (including your future self) to understand and maintain your code. Here are some examples of sensible variable names:
age = 16 - Sensible
username = "JohnDoe" - Sensible
is_valid = True - Sensible
num_of_students = 30 - Sensible
Not Sensible Variable Names
Using not sensible or unclear variable names can lead to confusion and make your code harder to understand. Avoid using single characters or generic names that do not provide any meaningful context. Here are some examples of not sensible variable names:
a = 10 - Not sensible
b = "hello" - Not sensible
xzy = True - Not sensible
var1 = 20 - Not sensible
temp = "world" - Not sensible
Which of the following is a sensible variable name for a variable that stores a person's last name?
Constants
A constant is similar to a variable, except that its value remains unchanged throughout the program. It is typically used for values that are known and fixed.
In Python, constants are implemented using variables that are named using uppercase letters to indicate their immutability (unchangeability).
PI = 3.14159
NAME = "John Doe"
Here, PI is assigned the constant value of 3.14159.
Note: Python treats constants and variables exactly the same, we use the UPPERCASE LETTERS convention to help make writing and maintaining programs easier.
Variables & Constants
- Introduction to Variables
- Declaring and Assigning Variables
- Combining Declaration and Assignment
- Variable Naming Rules
- Python Reserved Words
- Built-in Functions
- Sensible vs Not Sensible Variable Names
- Constants