{
"cells": [
{
"cell_type": "markdown",
"id": "44e4997d",
"metadata": {
"id": "Z7zGE9I7TEF5"
},
"source": [
" \n",
"\n",
"# **Operators**"
]
},
{
"cell_type": "markdown",
"id": "5aa03580",
"metadata": {
"id": "czb8k3dfd30C"
},
"source": [
"## Operators and operands\n",
"We can do arithmatic operations in Python, similar to those in standard mathematics. This is very straightforward. Let's start with a simple operation: `2+3` , where `2` and `3` are called operands and the plus sign `+` is called the operator or arithmatic operator. You can also use already defined variables as operands or store the output of the operation in a new or existing variable."
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "caa39bd0",
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "XFjD7j9flzkn",
"outputId": "b2aad49a-68bf-42db-e327-35836590feab"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"5\n"
]
}
],
"source": [
"print( 2+3 )"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "c05f51a8",
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "xzyGvWPZl0uK",
"outputId": "bf25d87c-f8de-4abb-9d20-84cf87460a9c"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"7\n"
]
}
],
"source": [
"x=2\n",
"print(x+5)"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "b1564762",
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "il1eIAkzd48n",
"outputId": "7d4b85e1-ec77-4491-b13a-e8301ec30682"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"-4\n"
]
}
],
"source": [
"y=x-6\n",
"print(y)"
]
},
{
"cell_type": "markdown",
"id": "5671e040",
"metadata": {
"id": "MXXPr7_EiefK"
},
"source": [
"## Arithmetic operators\n",
"\n",
"Below you can see a list of commonly used operators and their corresponding signs in Python.\n",
"\n",
"| Operator\t | Description |\n",
"|---------------|---------------------------------------|\n",
"|``+`` |Addition (e.g., ``1 + 1 = 2``) |\n",
"|``-`` |Subtraction (e.g., ``3 - 2 = 1``) |\n",
"|``-`` |Unary negation (e.g., ``-2``) |\n",
"|``*`` |Multiplication (e.g., ``2 * 3 = 6``) |\n",
"|``/`` |Division (e.g., ``3 / 2 = 1.5``) |\n",
"|``//`` |Floor division (e.g., ``3 // 2 = 1``) |\n",
"|``%`` |Modulus/remainder (e.g., ``9 % 4 = 1``)|\n",
"|``**`` |Exponentiation (e.g., ``2 ** 3 = 8``) |\n",
"\n",
"\n",
"The code below shows some examples."
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "f1fdb20c",
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "nYsAG976lWtX",
"outputId": "fdc3f2ec-e4f0-4b92-aa33-09088691aed7"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"7\n"
]
}
],
"source": [
"x = 2\n",
"z = x+5 # Addition\n",
"print(z)"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "ad989198",
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "TlU61ISBuW3c",
"outputId": "66af162e-d2e2-4700-afed-e0eedfe77141"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"4\n"
]
}
],
"source": [
"w = x ** 2 # Exponentiation (power)\n",
"print(w)"
]
},
{
"cell_type": "markdown",
"id": "9430cd3a",
"metadata": {
"id": "P1MGZ5gvuOxN"
},
"source": [
"The code below shows some more examples. Note that the first argument (input) in the `print(.,.)` is a string just to show which operation will be printed. What you see after this string is the result of the operation performed as the second argument."
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "5629f89f",
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "To8eVoOf6DKX",
"outputId": "7e1a0e11-9e39-425a-c66d-c9cb36565e79"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"x = 2\n",
"x + 5 = 7\n",
"x - 5 = -3\n",
"x * 2 = 4\n",
"x / 2 = 1.0\n",
"x // 2= 1\n",
"-x = -2\n",
"x ** 2= 4\n",
"x % 2 = 0\n"
]
}
],
"source": [
"x=2\n",
"print(f\"x = {x}\")\n",
"print(f\"x + 5 = {x + 5}\") # Addition\n",
"print(f\"x - 5 = {x - 5 }\") # Subtraction\n",
"print(f\"x * 2 = {x * 2}\") # Multiplication\n",
"print(f\"x / 2 = {x / 2}\") # Division\n",
"print(f\"x // 2= {x // 2}\") # Floor division\n",
"print(f\"-x = {-x}\") # Negation\n",
"print(f\"x ** 2= {x ** 2}\") # Exponentiation (power)\n",
"print(f\"x % 2 = {x % 2}\") # Modulus"
]
},
{
"cell_type": "markdown",
"id": "88c4ffe7",
"metadata": {
"id": "w5EB1_AklO7q"
},
"source": [
"### **Exercise: Python as a calculator**\n",
"\n",
"You're planning a trip from Amsterdam to The Hague, considering a specific route. Your chosen route involves traveling 50 km to the south and 30 km west. Your friend opts for a direct route, represented by a red line on the map."
]
},
{
"cell_type": "markdown",
"id": "044c263f",
"metadata": {
"id": "SG2cMSiohK8P"
},
"source": [
""
]
},
{
"cell_type": "markdown",
"id": "1446631f",
"metadata": {
"id": "E49m_3F2hJhK"
},
"source": [
"a) Write a Python program that calculates the reduction in distance your friend needs to drive compared to your chosen route."
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "4c0b2072",
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "DkepJz4ol70a",
"outputId": "dbd664c6-af45-4677-8369-fd73ee135503"
},
"outputs": [
{
"ename": "SyntaxError",
"evalue": "invalid syntax (4166851397.py, line 6)",
"output_type": "error",
"traceback": [
" \u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[7]\u001b[39m\u001b[32m, line 6\u001b[39m\n\u001b[31m \u001b[39m\u001b[31mfriend_route_distance = # your code here # km\u001b[39m\n ^\n\u001b[31mSyntaxError\u001b[39m\u001b[31m:\u001b[39m invalid syntax\n"
]
}
],
"source": [
"# Distance of your chosen route\n",
"your_route_horizontal = 50 # km to the left\n",
"your_route_vertical = 30 # km up\n",
"\n",
"# Distance of the straight path your friend takes using the Pythagorean theorem\n",
"friend_route_distance = # your code here # km\n",
"\n",
"# Calculate the total distance of your chosen route\n",
"your_total_distance = # your code here\n",
"\n",
"# Calculate the reduction in distance your friend needs to drive\n",
"reduction_in_distance = # your code here\n",
"\n",
"# Output the result\n",
"print(f\"Your friend needs to drive {reduction_in_distance} km less than your chosen route.\")"
]
},
{
"cell_type": "markdown",
"id": "4a83b257",
"metadata": {
"id": "p3CKYQyDe4if"
},
"source": [
"b) Now, imagine you're driving your car at a constant speed of 22 m/s. Write a Python program that calculates the time it takes for you to reach your destination using your chosen route."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "337ed7d1",
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "ZiUBdlkfpWyo",
"outputId": "78ecc642-40d5-466c-d5ae-9ec234d5bf1b"
},
"outputs": [],
"source": [
"# Speed of the car in meters per second\n",
"car_speed = 22 # m/s\n",
"\n",
"# Calculate the time it takes to reach the destination in seconds\n",
"time_seconds = # your code here\n",
"\n",
"# Display the time in seconds\n",
"print(f\"It takes {time_seconds:.2f} seconds to reach your destination.\")"
]
},
{
"cell_type": "markdown",
"id": "0d373e5e",
"metadata": {
"id": "tjJSZg5xxnGa"
},
"source": [
"c) Write another Python program that converts the calculated time from part (b) into whole hours, whole minutes, and remaining seconds."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "b25ca90e",
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "Dlz8IO-xyvv4",
"outputId": "52fb6e94-e47b-4daa-b913-91cb198b9bc7"
},
"outputs": [],
"source": [
"# Convert seconds to hours, minutes, and remainder seconds\n",
"hours = # your code here # 1 hour = 3600 seconds\n",
"remaining_seconds = # your code here\n",
"minutes = # your code here # 1 minute = 60 seconds\n",
"seconds = # your code here\n",
"\n",
"# Display the converted time\n",
"print(f\"{int(time_seconds)} seconds is equal to {hours} hours, {minutes} minutes, and {seconds} seconds.\")"
]
},
{
"cell_type": "markdown",
"id": "a5de9794",
"metadata": {
"id": "mTjuHBBpsryD"
},
"source": [
"## Arithmetic operations on strings\n",
"\n",
"Some arithmetic operations can be applied to strings, although their behavior is a bit different from the standard arithmetic operations on numbers. The main string-related arithmetic operations are:\n",
"\n",
"* Addition (+): Concatenates (joins) two strings together.\n",
"\n",
"* Multiplication (*): Replicates a string a given number of times."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "20548868",
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "CibK0V2-mljT",
"outputId": "725c696b-658a-4a9c-9027-1d49af69701f"
},
"outputs": [],
"source": [
"# Addition\n",
"str1 = \"Hello, \"\n",
"str2 = \"world!\"\n",
"result = str1 + str2\n",
"print(result) # Output: Hello, world!"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "5d8fc26f",
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "0RCAp1wZtDNA",
"outputId": "e9c556e6-8d54-45b1-a1e3-fa50b99b3468"
},
"outputs": [],
"source": [
"# Multiplication\n",
"text = \"Python\"\n",
"multiplied_text = text * 3\n",
"print(multiplied_text) # Output: PythonPythonPython"
]
},
{
"cell_type": "markdown",
"id": "1c5945eb",
"metadata": {
"id": "aXJHBfnytZzJ"
},
"source": [
"It's important to note that other arithmetic operations like subtraction, division, floor division, and exponentiation do not apply to strings directly in the same way they do for numbers. Attempting these operations on strings will likely result in errors or unexpected behavior."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "b677f967",
"metadata": {
"id": "mL5W6cK2tlMB"
},
"outputs": [],
"source": [
"str1 = \"Hello\"\n",
"str2 = \"world\"\n",
"# result = str1 - str2 # Raises TypeError: unsupported operand type(s) for -: 'str' and 'str'"
]
},
{
"cell_type": "markdown",
"id": "a2bf18cd",
"metadata": {
"id": "AkO8e5UeQoo_"
},
"source": [
"## Assignment operators\n",
"You can also use the arithmatic operators listed above with an equal sign like: `a += b`. This is a compact version of `a = a+b`. Here is an example:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "d70863f3",
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "KGU3nSaeRiSQ",
"outputId": "de181fa9-9380-4b0d-9e6f-8ae1d209357d"
},
"outputs": [],
"source": [
"a = 3\n",
"a += 5\n",
"\n",
"print(a)"
]
},
{
"cell_type": "markdown",
"id": "eac64507",
"metadata": {
"id": "nyVJgCZNBTEd"
},
"source": [
"## Comparison operators\n",
"These operators are used to compare the values on either sides of them and decide if the relation among them is True or False. Below is a list of commonly used comparison operators in Python. Note that you can use variables or operations on both sides of them.\n",
"\n",
"| Operator\t | Description |\n",
"|---------------|---------------------------------------------|\n",
"|``==`` |Equal to (e.g., ``3 == 5`` is False) |\n",
"|``!=`` |Not equal to (e.g., ``3 != 5`` is True) |\n",
"|``>`` |Greater than (e.g., ``3 > 5` is False) |\n",
"|``<`` |Less than (e.g., ``3 < 5`` is True) |\n",
"|``>=`` |Greater than or equal ``3 >= 5` is False`) |\n",
"|``<=`` |Less than or equal (e.g., ``3 <= 5`` is True)|"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "1b89e2c7",
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "y1Lg7CbmvWyC",
"outputId": "729a96d0-b093-489a-ea89-f118e45133c4"
},
"outputs": [],
"source": [
"x = 10\n",
"y = 20\n",
"z = x==y\n",
"print (z)"
]
},
{
"cell_type": "markdown",
"id": "64e97656",
"metadata": {
"id": "Q7p0AMP_vfN9"
},
"source": [
"More examples:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "d119bf7e",
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "nEej667lDnKt",
"outputId": "0176ed1c-fcfb-47a8-fb77-c404b8aadfc2"
},
"outputs": [],
"source": [
"print (\"x != 10 :\", x !=10)\n",
"print (\"5 > 20 :\", 5 > 20)\n",
"print (\"x >= y :\", x >= y)"
]
},
{
"cell_type": "markdown",
"id": "93fe7a8e",
"metadata": {
"id": "AbDY8E34EgcV"
},
"source": [
"## Logical (aka boolean) operators\n",
"\n",
"Logical operators are performed on conditional statements that have a True or False value. They perform logical operations.\n",
"\n",
"| Operator\t | Description |\n",
"|--------------- |--------------------------------------------- |\n",
"|``not`` |logical not (e.g., ``not False`` is True) |\n",
"|``and`` |logical and (e.g., ``False and False`` is False)|\n",
"|``or`` |logical or (e.g., ``False or True`` is True) |"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "8de87fc6",
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "kEmmDw_bmync",
"outputId": "0026876f-52f1-46a6-97e7-25e13f1df754"
},
"outputs": [],
"source": [
"print(not True)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "71213bc1",
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "HNypNSD8mzOZ",
"outputId": "5b52926b-9197-4bb1-efe0-6d2c5f4d2eb8"
},
"outputs": [],
"source": [
"a=True\n",
"print (\"a and False : {a and False}\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ba9d71ba",
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "2WoBtmyfm0j7",
"outputId": "b873e260-e155-40de-f80f-c240ae7f4523"
},
"outputs": [],
"source": [
"a=True\n",
"print (\"a and False : {a and False}\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "57b49472",
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "HeANJ2PTm3Ji",
"outputId": "fd83de54-735f-4213-bf1f-6e10e1373bba"
},
"outputs": [],
"source": [
"print (\"a or 3==5 : {a or 3==5}\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c6ca1634",
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "TS8-loH3F4Sz",
"outputId": "5e0c8395-244d-4cdb-f9c6-05c165f3b850"
},
"outputs": [],
"source": [
"x=10\n",
"print (\"x>=10 or x<3 : {x>=10 or x<3}\")"
]
},
{
"cell_type": "markdown",
"id": "a02f42bb",
"metadata": {
"id": "LxmCbrJdqgDs"
},
"source": [
"___\n",
"### **Exercise: Time conversion**\n",
"In the previous exercise, assume that your friend is traveling with a speed of 15 m/s. Write a Python code using logical operators that evaluates and prints the variable `you_are_first` with True if you indeed arrived earlier or False otherwise."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "3dcaa494",
"metadata": {
"id": "s15qu_94qbMX"
},
"outputs": [],
"source": [
"# Speed of the car in meters per second\n",
"friend_car_speed = 15 # m/s\n",
"\n",
"# Calculate the time it takes to reach the destination in seconds\n",
"# your code here\n",
"\n",
"# Check if you are faster than your friend using logical operators\n",
"# your code here\n",
"\n",
"# Display the result\n",
"# your code here"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "28296a86",
"metadata": {
"id": "nqj5S6UNO9K8"
},
"outputs": [],
"source": []
}
],
"metadata": {
"jupytext": {
"text_representation": {
"extension": ".md",
"format_name": "myst",
"format_version": 0.13,
"jupytext_version": "1.16.4"
}
},
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.12.11"
},
"source_map": [
14,
20,
25,
35,
46,
57,
77,
89,
100,
104,
123,
130,
134,
138,
162,
166,
183,
187,
204,
214,
228,
241,
245,
253,
258,
271,
285,
298,
302,
314,
326,
336,
347,
358,
368,
379,
385,
403
]
},
"nbformat": 4,
"nbformat_minor": 5
}