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 in programming?
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".
Which of the following is the correct way to declare and assign a variable in Python?
In Python, what happens if you try to assign a value to a variable that hasn't been declared or defined previously?
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)
In Python, which of the following is NOT a valid variable name?
Which of the following is NOT a valid variable name in Python?
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 the most appropriate variable name in Python for storing 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.
Review: Fill in the Blanks
are used to categorize variables and constants based on the kind of data they can hold. Common data types include integers, floating-point numbers, characters, and Boolean values. If a variable or constant is declared without specifying a data type, allows the programming language to automatically determine the appropriate data type based on its initial value.
The of a variable or constant involves specifying its name and data type. This is essential for the programming language to allocate memory and reserve space accordingly. Once a variable or constant is declared, it can be assigned a value using the operator. The assigned value should be compatible with the data type declared.
The of a variable or constant determines the part of the program where it is accessible. A can be accessed from any part of the program, whereas a is only accessible within a specific block of code, such as a function. This allows for better control and organization of data within a program.
A refers to an expression that evaluates to a constant value. It can be used in situations where a value needs to be computed at compile-time and remain constant throughout the program's execution.
Complete! Ready to test your knowledge?
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