End interactive session 1D
Code
# Define variables x and y as integers.
= 1
x = 42 y
π Variables, Operators, and Functions
All programming languages contain the same fundamental tools: variables
, operators
, and functions
. This session covers a first introduction to each of these these basic elements of the Python language.
Session Topics
int
, float
Before we begin our interactive session, please follow these steps to set up your Jupyter Notebook:
+
button in the top left cornerPython 3.10.0
from the Notebook options (it should be the third option)Untitled.ipynb
tab (see the note below if you have trouble!)Session_1D_Operators_and_Functions.ipynb
(Replace X with the day number and Y with the session number)Some browsers and operating system combinations will not conceded right-clicking to the JupyterLab interface and will show a system menu when you try to right click. In those cases, usually CTRL-Right Click
or OPTION-Right Click
will bring up the Jupyter menu.
# Day 1: Session D - Operators & Functions
[Session Webpage](https://eds-217-essential-python.github.io/course-materials/interactive-sessions/1d_operators_functions.html)
Date: 09/03/2024
Remember to save your work frequently by clicking the save icon or using the keyboard shortcut (Ctrl+S or Cmd+S).
Letβs begin our interactive session!
We will work through this material together, writing a new notebook as we go.
π This symbol designates an important note about Python structure, syntax, or another quirk.
βοΈ This symbol designates code you should add to your notebook and run.
Variables are used in Python to create references to an object (e.g. string, float, DataFrame, etc.). Variables are assigned in Python using =
.
π Variable names should be chosen carefully and should indicate what the variable is used for. Python etiquette generally dictates using lowercase variable names. Underscores are common. Variable names cannot start with a number. Also, there are several names that cannot be used as variables, as they are reserved for built-in Python commands, functions, etc. We will see examples of these throughout this session.
Numbers in Python can be either integers (whole numbers) or floats (floating-point decimal numbers).
βοΈ Try it. Add the cell below to your notebook and run it.
The following syntax is used to define a float:
βοΈ Try it. Create a new cell and define variables a, b, and c according to the values above.
Just like a calculator, basic arithmetic can be done on number variables. Python uses the following symbols:
Symbol | Task |
---|---|
+ | Addition |
- | Subtraction |
* | Multiplication |
/ | Division |
% | Modulus |
// | Floor division |
** | Power |
βοΈ Try it. Practice using arithmetic operations by running the code in a new cell. Feel free to add more to test the operators. Use the print()
command to output your answers.
Notice that the order of operations applies.
Compound assignment operators combine an arithmetic or bitwise operation with assignment in a single statement. They provide a concise way to update a variableβs value based on its current value.
# Initialize a variable
count = 10
# Decrement using compound assignment
count -= 1
print(f"After count -= 1: {count}") # Output: 9
# Increment using compound assignment
count += 2
print(f"After count += 2: {count}") # Output: 11
# Multiply using compound assignment
count *= 3
print(f"After count *= 3: {count}") # Output: 33
After count -= 1: 9
After count += 2: 11
After count *= 3: 33
Complete the following code to achieve the desired output:
# Initialize the score
score = 100
# TODO: Use compound assignment to decrease the score by 15
# Your code here
# TODO: Use compound assignment to double the score
# Your code here
# TODO: Use compound assignment to divide the score by 5
# Your code here
print(f"Final score: {score}") # Expected output: 34.0
Final score: 100
Try modifying the initial score
value or the operations to see how the result changes!
Boolean operators evaluate a condition between two operands, returning True
if the condition is met and False
otherwise. True
and False
are called booleans.
Symbol | Task |
---|---|
== | Equals |
!= | Does not equal |
< | Less than |
> | Greater than |
<= | Less than or equal to |
>= | Greater than or equal to |
βοΈ Try it. Enter and Run the cell below in your .ipynb file.
Python has a number of built-in functions. Here we will introduce a few of the useful built-in functions for numerical variables.
The type()
function is used to check the data type of a variable. For numerical arguments, either float
or int
is returned.
βοΈ Try it. Enter and Run the cell below in your .ipynb file.
The isinstance()
function is used to determine whether an argument is in a certain class. It returns a boolean value. Multiple classes can be checked at once.
isinstance(12, int)
>>> True
isinstance(12.0, int)
>>> False
isinstance(12.0, (int, float))
>>> True
The commands int()
and float()
are used to convert between data types.
βοΈ Try it. Enter and Run the cell below in your .ipynb file.
Notice that when converting a float value to an integer, the int()
command always rounds down to the nearest whole number.
To round a float to the nearest whole number, use the function round()
. You can specify the number of decimal places by adding an integer as an argument to the round()
function.
βοΈ Try it. Enter and Run the cell below in your .ipynb file.
To return the absolute value of a number, use the abs()
function.
βοΈ Try it. Enter and Run the cell below in your .ipynb file.
The pow()
function is an alternative to the **
operator for raising a number to an exponent, i.e. \(x^y\).
βοΈ Try it. Enter and Run the cell below in your .ipynb file.
Pieces of text in Python are referred to as strings. Strings are defined with either single or double quotes. The only difference between the two is that it is easier to use an apostrophe with double quotes.
βοΈ Try it. Enter and Run the cell below in your .ipynb file.
To use an apostrophe or single quotes inside a string defined by single quotes (or to use double quotes), use a single backslash ( \ ) referred to as an βescapeβ character.
βοΈ Try it. Enter and Run the cell below in your .ipynb file.
True
Python has multi-line strings as well, which you can use when documenting your code or handling large quotes or chunks of text. Multi-line strings are started with three quotes ("""
) and terminated with three quotes ("""
):
βοΈ Try it. Enter and Run the cell below in your .ipynb file.
Multi-line formatting is preserved in multi-line strings:
βοΈ Try it. Enter and Run the cell below in your .ipynb file.
Just like the int()
and float()
commands, the str()
command converts a number to a string.
βοΈ Try it. Enter and Run the cell below in your .ipynb file.
The +
operator can be used to combine two or more strings.
βοΈ Try it. Enter and Run the cell below in your .ipynb file.
The commands string.upper()
and string.capitalize()
can be used to convert all letters in the string to uppercase and capitalize the first letter in the string, respectively.
βοΈ Try it. Enter and Run the cell below in your .ipynb file.
Pythonβs f-string formatting provides an efficient and readable way to create formatted strings. This is useful for printing variables, formatting numerical output, and displaying messages.
To use an f-string, place an f
before the opening quotation mark of a string literal, and then include variables inside curly braces {}
.
βοΈ Try it. Enter and Run the cell below in your .ipynb file.
You can also format numbers, especially floating-point numbers, within f-strings by specifying format specifiers inside the curly braces:
.nf
to display a float with n
decimal places.βοΈ Try it. Enter and Run the cell below in your .ipynb file.
The value of pi is approximately 3.14.
βοΈ Try it. Enter and Run the cell below in your .ipynb file.
Value aligned to 10 spaces: | 123.46|
End interactive session 1D