Data Types, Variables, and Arithmetic Operators
Let's start by looking at a simple mathematical equation to calculate the mean of a set of numbers:
a = 15, b = 35, c = 55
mean = (a + b + c) / 3 = 35
To perform this calculation, you might use mental math or a calculator. In Python, you must first understand how to declare variables like a, b, and c, identify their data types (integers, real numbers, text, etc.), and use arithmetic operators. In this lesson, we will explore these fundamental concepts.
What is a data type?
In its simplest form, a computer program processes data stored in variables. In the mean calculation above, variables a, b, and c hold numeric values. Before the computer can process this data, it needs to know its type. Data can be an integer, a word (string), or other literal values.
While you can multiply two numbers, you cannot multiply two words. Data types tell the computer which operations are valid for a given variable. Additionally, the data type helps the program determine how much memory to allocate for a value. For example, if a variable is an integer, the program knows it can perform arithmetic and allocates the appropriate space to store the result.
In languages like Java or C, you must explicitly declare a variable's type before using it. In Python, however, the interpreter identifies the type automatically based on the value assigned. This is known as dynamic typing (or sometimes "Duck Typing"—from the phrase, "If it looks like a duck and quacks like a duck, it's a duck").
Common Python Data Types
| Data Type | Name | Example | Allowed Values |
|---|---|---|---|
| str | String | name = "Joe" |
Any text |
| bool | Boolean | is_active = True |
True or False |
| int | Integer | year = 2026 |
Whole numbers |
| float | Float | height = 5.9 |
Real numbers (decimals) |
| NoneType | Null | x = None |
None only |
The None data type represents the absence of a value, similar to 'null' in other programming languages.
Interactive Learning
This eBook is designed to be fully interactive. The code blocks you see throughout the chapters run entirely within your web browser. This means there is no round trip to a remote server—your code executes locally and instantly on your machine.
How to use code blocks:
- View: Read the code provided in the editor.
- Edit: You can click directly inside the code block to modify the values or logic. Your input is saved on your browser. You can reset it to the original value at any time.
- Run: When ready, click on the Run Code button to execute your code snippet.
- Observe: The results will appear immediately below in the Output block.
Note: The blocks of code that cannot execute on the browser, do not have the Run button. You should copy them to Colab or another Python environment to run them.
Simple Statements
Let's practice by calculating the mean in the interactive code cell below:
a = 15
b = 35
c = 55
mean = (a + b + c) / 3
print(mean)
print(type(mean))
Try it out: Run the code above and observe the output. Notice the class 'float' printed below 35.0. Because the result is a decimal, Python automatically assigned it the float data type. Feel free to add a variable d or change the values to see how the output updates instantly in your browser.
Keywords: print and type
Functions act like "black boxes": they accept inputs (arguments) and produce outputs (returned values).
- The
printfunction takes an argument (likemean) and displays its value. - The
typefunction identifies the data type of an argument. In the example above, the output oftype(mean)is passed directly intoprint()to display it.
Arguments are always passed within a pair of parentheses ().
- Must start with a letter or an underscore
_. - Must contain only letters, digits, or underscores.
- Cannot be a reserved Python keyword (e.g.,
if,else,while,return). Reserved Keywords:and, as, assert, break, class, continue, def, del, elif, else, except, finally, for, from, global, if, import, in, is, lambda, nonlocal, not, or, pass, raise, return, try, while, with, yield
- Use meaningful names (e.g.,
student_nameinstead ofs). - Start with a lowercase letter and use underscores to separate words (snake_case).
- While "camelCase" is common in some languages, Python data analysts typically prefer underscores.
- Example of camel case:
studentName="joe", example of snake case:student_name="joe"
- Indentation: Python is very strict about indentation. Simple statements must align vertically without leading spaces.
- Case Sensitivity: Variable names are case-sensitive (
meanis not the same asMean). - Definition First: A variable must be defined before it is used. Running the code below will throw a
NameError:
print(d)
- Strings: You can use single (
'), double ("), or triple (""") quotes for strings. Triple quotes are ideal for text that spans multiple lines.- No Quotes for Numbers: Do not wrap
int,float, orboolvalues in quotes; doing so turns them into strings.- Reassignment: A variable's type can change if you assign it a new value.
weight = 100
weight = "150 pounds"
print(weight)
The code above runs without error, outputting "150 pounds".
- ** Persistent Context: Variables defined in one cell remain available for other cells on the same page. Note that the execution order matters more than the visual order of cells.
- Refreshing the Page: Refreshing your browser will clear all variables from memory (the execution context). However, any changes you made to the code are saved in the browser cache.
- Resetting Code: To restore a code block to its original state, use the Reset button.
- Context Suffixes:
python(Shared): Variables are shared across all standard blocks on the page.python-isolated: Creates a private sandbox for that specific block.python-main: Creates a named shared context for specific examples.
Arithmetic Operators
Python supports standard mathematical operators, including shorthand (augmented) assignments:
| Operation | Notation | Shorthand | Result (if x = 3) |
|---|---|---|---|
| Addition | x = x + 1 |
x += 1 |
4 |
| Subtraction | x = x - 1 |
x -= 1 |
2 |
| Multiplication | x = x * 2 |
x *= 2 |
6 |
| Division | x = x / 2 |
x /= 2 |
1.5 |
| Floor Division | x = x // 2 |
x //= 2 |
1 (removes decimal) |
| Modulo | x = x % 2 |
x %= 2 |
1 (remainder) |
| Exponent | x = x ** 2 |
x **= 2 |
9 |
Rounding: Ceiling and Floor
- Ceiling: Rounds a number up to the next whole integer.
- Floor: Rounds a number down to the previous whole integer.
To perform these operations, we use the built-in math module. A module is a collection of pre-written functions that you can "import" into your program to extend its capabilities. The math module provides access to advanced mathematical functions.
import math
val = 3.1
print(math.ceil(val)) # Rounds up to 4
val = 3.9
print(math.floor(val)) # Rounds down to 3
- Shorthand: Augmented assignments (like
+=) are preferred for brevity. - Division: In Python 3, the
/operator always returns afloat. - Order of Operations: Python follows the PEMDAS rule (Parentheses, Exponents, Multiplication, Division, Addition, Subtraction).
Advanced Assignments
Python also supports scientific notation and complex numbers:
a = 0.4e7 # 4,000,000.0 (Exponential)
b = 3 + 4j # Complex number (Real + Imaginary)
print(a)
print(type(b))
Multiple Assignments
You can initialize multiple variables in a single line:
# Same value for all
a = b = c = 10
print(a, b, c)
# Different values
x, y, z = 1, 2, 3
print(x, y, z)
Swapping Variables
In many languages, swapping two variables requires a temporary placeholder. In Python, you can do this elegantly in one line:
a, b = 10, 20
print(a, b)
a, b = b, a # Swaps values instantly
print(a, b)
Deleting Variables
You can remove a variable from memory using the del keyword:
a = 10
del a
print(a) # This would now throw a NameError
Using Semicolons
While Python uses newlines to separate statements, you can use semicolons (;) to put multiple statements on one line. However, this is generally discouraged by the PEP 8 style guide in favor of readability.
Hands-on Exercises
Exercise 1: Calculate Body Mass Index (BMI)
Write a Python program to calculate a person's Body Mass Index (BMI).
- Store the weight of a person in kilograms (
weight = 72) and their height in meters (height = 1.78) in variables. - Use the mathematical formula:
BMI = weight / (height squared). (Hint: Use the exponentiation operator**for squaring). - Compute the BMI, round the result to 2 decimal places using
round(), and print it.
# Write your code below and click Run Code
Click to view Answer
weight = 72
height = 1.78
bmi = weight / (height ** 2)
print("BMI is:", round(bmi, 2))
# Output: 22.72
Exercise 2: Variable Swap Challenge
You have two values representing coordinates: x = 45 and y = 90.
Write a Python program to:
- Initialize the variables
xandy. - Swap their values in a single line using Python's shorthand multiple assignment mechanism.
- Print the values of
xandyafter swapping to confirm they have changed.
# Write your code below and click Run Code
Click to view Answer
x = 45
y = 90
# Shorthand variable swap
x, y = y, x
print("x is:", x) # 90
print("y is:", y) # 45