The Pursuit of Programming #2: Variables, Operators and Data Types
Building Blocks of Programming: Unravelling Variables, Operators, and Data Types
In the first post of the Pursuit of Programming series, we covered setting up our Python development environment and configuring Visual Studio Code as our preferred editor for writing Python code. In this second post, we will introduce the concept of variables, data types, and operators. Let's dive in!
(This post is a bit long, if you are reading it in your email I would encourage you to read it online or in the Substack app.)
Variables
Variables are fundamental building blocks for creating programs. A variable is a name with an associated value, somewhat similar to variables used in algebra. For example, we can create a variable x
with the value 10 by writing x = 10
in Python. Here, x
is the variable name, =
is the assignment operator, and 10
is the value assigned to x
. From this point on, whenever we write x
in our program, it will refer to its value 10
.
We can also change the value of a variable. In a Python shell let’s try the following examples (refer to this on how to start the Python shell):
In this example, we first created a variable x
with the value 10
which is displayed when we print x
. Next on line 4, we update x
to the value 12
, and when we print it again, we can see its updated value.
The purpose of variables is to represent data in our programs. Suppose we intend to write a program that calculates simple interest using the formula shown below.
Our program would need three variables, one for principal, one for interest rate and one for time. We could also create a fourth variable which will store the value of the computed interest. Based on this, our program to calculate simple interest could look like this:
On line 1-3 we have created variables for principal, interest rate and time period.
On line 4 we are creating the variable for interest
whose value is the product of the variables: principal
, interest
and time
. Since at the time of evaluating this expression, Python knows the values of those variables, it can immediately calculate the product as 100 * 5 * 1
and assign the result to interest. This means that the value of the interest variable upon assignment on line 4 becomes 500
.
Naming Convention for Variables in Python
Now that we know how to create a variable in Python, let's discuss the rules for naming them. Each programming language has certain rules for naming variables; for Python, these rules are as follows:
Valid Characters: Python allows all alphabets (uppercase and lowercase), digits, and underscores (
_
) in a variable name. A name must start with a letter or an underscore but cannot start with a digit.Case-sensitive: Variable names are case-sensitive. For example, the variables
x
andX
are different.Reserved Keywords: We cannot use certain names because they are reserved keywords in Python. For example, keywords like
for
,if
,elif
,def
, etc. cannot be used. Check this link for the complete list of reserved keywords in Python.Meaningful Names: Although not enforced by Python, it is generally important to use meaningful names for our variables, so that someone reading the code can understand the purpose of those variables.
Snakecase: When coming up with variable names consisting of multiple words, the convention in Python is to separate the words with underscores, for example:
interest_rate
. This convention is also called snakecase in programming.
Let’s look at some examples of variable names following these rules and conventions.
age
name
student_name
total_count
_my_var
And, here are some examples of invalid variable names:
1number (starts with a digit)
my-var (contains a hyphen)
for (reserved keyword)
Data Types in Python
Now that we know what a variable is, we need to discuss their data types (or simply called types). In programming, a variable not only has a value but also an associated data type based on the value. For example, it can be a number, a string, or something else. Knowing the data type allows us to decide what operations we can perform on that variable. Different programming languages have different data types (although most share a common subset), Python has the following primitive data types:
int: These are integer numbers, such as 1, 20, 30, etc.
float: These are floating point numbers, such as 3.14, 2.1, 5.0, etc.
string: These represent text data, such as “apple”
. String values in Python need to be enclosed between double quotes (e.g. “apple”
) or single quotes (e.g. ‘apple’
).
bool: bool
represents boolean values, which have only two possible values: True
and False
. These are commonly used when writing program logic based on conditions.
These are the most basic data types available in most programming languages. Python also has more complex data types, which we will discuss in our next post in this series.
Let’s create some variables with different types in the Python shell and print their types. We will use Python’s builtin type
function to print the types of the variables.
Python is a dynamically typed language, which means that the type of a variable is inferred based on the value assigned to it. For example, try the following code in the Python shell:
In this example, initially, the variable x
has the type int
because we assigned the value 10 to it. However, on line 4, we assigned the value hello, world
to x
, which changed its type to string
.
Operators in Python
Variables themselves are of not much use to us unless we can perform operations on them and manipulate them, this is where operators come into the picture. We have already used some operators in some of our examples, let’s discuss them more formally.
Operators are symbols which allow us to perform certain operations on the variables and data in our program. For example, we used the *
operator in our example to calculate simple interest for multiplying the numbers. In this section let’s look at the complete list of operators available in Python.
Numeric Operators in Python
Python supports all arithmetic operators for int
and float
type variables. Let’s see them with examples below:
Addition: Python uses the +
operator to add two numbers (int
or float
types).
When doing any arithmetic operation where
int
andfloat
types are involved, the resulting value is always a floating-point value.
Subtraction: Python uses the -
operator for subtracting two numbers. See the example below.
Multiplication: The *
operator is used for multiplying two numbers.
Division: We use the /
operator for division. This operator produces the quotient after the division. Let’s see some examples.
When we divide a number by 0, Python gives us a
ZeroDivisionError
. This is because dividing by 0 is not a well-defined operation, and Python doesn't know what to do. As a programmer, we need to avoid such cases by putting appropriate checks in place. We will discuss how to do these checks when we talk aboutif
conditions in a future post.
Integer Division: You might have noticed that the /
operator always produces a floating-point value even when we are dividing two integers that are perfectly divisible, such as the result of 10 / 2
being 5.0
. If we are interested only in the integer part of the result and not the fraction, Python provides the special //
operator for integer division. Let’s see some examples.
Exponentiation Operator: Python also includes the **
operator to calculate the power of a number. For example, 2 ** 3
calculates 2
raised to the power of 3
.
Modulo Operator: The modulo operator (%
) computes the remainder of a division operation. For example, 5 % 2
gives 1
as the result.
Comparison Operators in Python
Python (and every other programming language) includes operators to compare two values:
Equality Operator: The
==
operator compares two values to determine if they are equal. It produces a boolean value as a result, which will beTrue
if the values on both sides of the operator are equal, andFalse
otherwise. Let’s try some examples in the Python shell.
Not Equal Operator: The not equal operator is represented by
!=
. It producesTrue
if the values on the two sides of the operator are not equal andFalse
otherwise. Let’s try a few examples.
Numerical Comparison Operators: Python includes operators for comparing numbers. These are
>
(greater than),<
(less than),>=
(greater than or equal to), and<=
(less than or equal to).
Operator Precedence
When doing complex calculations, we need to be aware which operators are evaluated first because this order can change the result of the expression. The following table shows the precedence of operators in Python.
In any expression, the higher precedence operators are evaluated first. Let’s understand with the help of some examples.
As you can see in the first example 5 + 10 * 2
, because of higher precedence of the *
operator, 10 * 2
is calculated first and then the result is added to 5
.
In a simpler expression such as 5 + 10 - 2
, where both the operators (+
and -)
are of equal precedence, the operators are evaluated from left to right. In this case first 5 + 10
is evaluated to 15,
and then 15 - 2
is evaluated.
We can use parenthesis to change the order of evaluation. If an expression has parenthesis, then the sub-expressions within the parenthesis are evaluated first. For example:
We can also use nested parenthesis as shown in the last example. In case of nested parenthesis, we start the evaluation from the innermost parenthesis.
String Operators in Python
Concatenation Operator: In programming, concatenating strings means joining two or more strings together to form a new string. In Python, the +
operator is used to concatenate strings. For example, “hello” + “world”
produces the new string “helloworld”
.
Note that the + operator when used with numbers performed addition, but when used with strings, it performs concatenation.
Repetition Operator: The repetition operator (*
) repeats a string the specified number of times. For example, if we have a string s
, then s * 3
produces a new string where s
has been repeated 3 times.
Boolean Operators in Python
Boolean operators allow us to implement logic in our programs based on conditions. For example, when we want a piece of code to execute only when a certain condition is true, we need to evaluate that condition using these operators. We will delve deeper into how to write such conditional code, but first, let's understand how to use these operators.
The and
, or
and not
operators: These operators allow us to express complex logical conditions by combining multiple conditions into a single expression. For example:
The and
operator evaluates whether both conditions on its left and right are true. If either of them is false, it produces False
.
Similarly, the or
operator evaluates whether at least one of the conditions is true. If both conditions are false, then it produces False
; otherwise, it produces True
.
Finally, the not
operator negates a condition. For example, not True
produces False
.
Unlike the
and
andor
operators,not
is a unary operator, that means it only has one operand, which appears on the right-hand side ofnot
.
Let’s try some examples in the Python shell.
We can also combine and
and or
conditions in a single statement.
Use of parenthesis: The use of parentheses clarifies the code's intent. For example, when we have code like this:
x > 10 and x < 12 or y == 5
Even though Python is able to evaluate this using the operator precedence rules. But as a reader, it’s hard for me to understand whether the programmer intended to evaluate the
or
part first or theand
part first. However, if we add parentheses appropriately, the intent becomes clear. For example:
(x > 10 and x < 12) or y == 5
Short-Circuit Evaluation of Boolean Operators
The and
and or
operators perform a short-circuit evaluation of their operands. For example, if the left operand of the and
operator is False
then the right operand is not evaluated because the end result of the and
operation would have been False
anyway.
Similarly, in case of an or
operation, if the left operand is evaluated as True
then the right operand is not evaluated because the or
operation would result in a True
value regardless the value of the right operand.
You might wonder why this is useful, let’s understand with the help of an example. Let’s say you want to check whether a number is divisible by another number. You could do this by checking that the remainder of their division is 0
as shown below.
is_divisble = x % y == 0
However, what if y
is 0
? Python would give a ZeroDivisionError
in that case and your program will crash. To avoid this, you want to add a check that y
is not 0
and only then do the division. The short-circuit evaluation of the and
operator will allow us to do that.
is_divisble = y != 0 and x % y == 0
If y
is 0
, then the and
operator would short-circuit and it will not evaluate x % y
which will prevent the division by 0
.
Putting it All Together in a Project
We have covered a lot in this post. Let’s apply what we've learned by building a small project. We will write a small program that computes the area of a circle by asking the user to input the radius.
Assuming you have set up Visual Studio Code with the Python plugin, you can now create a new file and save it with the name "circle_area_calculator.py" in the "python_tutorial" directory. Write the following code in the file:
On line 1, we create a variable to store the value of pi
.
On line 2, we use the Python function input
to prompt the user to provide the value for the radius. The input
function prints a message on the screen and waits for the user to enter a value in the response, which can then be assigned to a variable.
By default, the input
function treats user input as a string. To compute the area of the circle, we need the radius to be a float. Therefore, we use the float()
function to convert the string value into a float
type before assigning it to the radius variable.
On line 3, we calculate the area of the circle by squaring the radius
and multiplying it by pi
. In Python, the **
operator has a higher priority than multiplication, so Python first calculates radius ** 2
and then multiplies the result by pi
.
On line 4, we print the result. We used the string concatenation operator (+
) to generate the output message. When concatenating a string and a number, we need to typecast the number into a string using the str
function; otherwise, Python will return a TypeError
.
Press Ctrl + F5
to run the project. The screen displays a message prompting you to enter the radius. Input the value and press Enter
to calculate the area.
Conclusion and Next Steps
In this second instalment of the Pursuit of Programming series, we delved into essential programming concepts such as variables, data types, and operators in Python. We provided real-world examples to illustrate these concepts, ensuring thorough understanding. Furthermore, we combined these topics in a practical exercise, developing a simple program to calculate the area of a circle.
As you continue to explore Python programming, take the time to practice writing more programs using the concepts we've covered. Examples include a compound interest calculator or a program to compute the area of a rectangle. Utilizing these concepts in numerous scenarios will help solidify your understanding.
In our upcoming posts, we will explore more advanced concepts such as lists, tuples, and dictionaries. Feel free to ask questions and share your experiences in the comments section below as we continue in the Pursuit of Programming. Happy coding!