{
"cells": [
{
"cell_type": "markdown",
"id": "bd7de80c",
"metadata": {
"id": "EBBAYTZhS8V6"
},
"source": [
" \n",
"\n",
"# **Variables**\n",
"\n",
"One of the main concepts in programming are variables. In Python, a variable is a __symbolic name__ that represents a value stored in memory. It allows you to store and manipulate data, making your code more flexible and reusable. Variables can hold different types of data, such as numbers, strings, lists, and more, and you can change their values throughout your program's execution."
]
},
{
"cell_type": "markdown",
"id": "906bd640",
"metadata": {
"id": "Yw1lz7IALu0w"
},
"source": [
"## Creating and assigning a value to a variable\n",
"Here is a simple example of creating and assigning value to a variable. In the code below, the numeric value of 5 is assigned (or bound) to variable `x` using `=`. To execute this line of code, also called a statement, you should first click on the code block and run it using the play button or \"shift\"+\"enter\". The first line of code doesn't show you anything as output, but to print this value you can use the `print()` __command__. Also note that Python is case-sensitive; this means `x` will be considered a different variable than `X`.\n",
"\n",
"Note that a __command__ refers to an instruction or action that you give to the computer to perform a specific task. Commands are the building blocks of your Python programs, allowing you to create functionality and automation."
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "64880a63",
"metadata": {
"class": "thebe"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"5\n"
]
}
],
"source": [
"x = 5 # assigning value 5 to variable x\n",
"print(x)"
]
},
{
"cell_type": "markdown",
"id": "f3ade3c2",
"metadata": {
"id": "Z9fV8CaQL1SQ"
},
"source": [
"Note that the text after hash sign `#` is considered as __comment__ (or note) by the computer and not executable code, so it will be ignored. It is only added to increase the readability of your code for you and others. Make sure to add comments to your code as you are writing it.\n",
"\n",
"### Variable Names\n",
"\n",
"In Python, variable names can contain both letters and numbers, but they can't begin with a number. It is conventional to use only lowercase for variable names. The underscore character, _, can be used in names with multiple words: `your_name` or `airspeed_of_unladen_swallow`.\n",
"Note that there are some keywords in Python that the interpreter uses to recognize the structure of the program, and they cannot be used as variable names. If you give a variable an illegal name, you get a syntax error. This applies to the following keywords:\n",
"\n",
"| | | | | |\n",
"|--|--|--|--|--|\n",
"| and | as | assert | async | await |\n",
"| break | class | continue | def | del |\n",
"| elif | else | except | False | finally |\n",
"| for | from | global | if | import |\n",
"| in | is | lambda | None | nonlocal |\n",
"| not | or | pass | raise | return |\n",
"| True | try | while | with | yield |"
]
},
{
"cell_type": "markdown",
"id": "be66e0e8",
"metadata": {
"id": "sl35VkvLL7Vy"
},
"source": [
"## Basic data types in Python\n",
"In Python, a data type defines the kind of value a variable can hold, such as numbers, text, lists, or more complex structures. It helps Python understand how to handle and manipulate the data correctly and efficiently.\n",
"There are four basic data types that you should know:\n",
"* __int__: integer numerical values with no decimal point.\n",
"* __float__: floating points for real numbers with decimal point.\n",
"* __bool__: boolean True or False values.\n",
"* __str__: string, text values composed of a sequence of characters.\n",
"\n",
"Below you can see how you can create variables and assign different types of data to them. If needed, you can check the type of a variable using the `type()` command."
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "301597f8",
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "nqioV4SpL3Yt",
"outputId": "1c3ff1c6-9fe2-4ad5-abb0-ab8ad415e8e5"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"4\n"
]
},
{
"data": {
"text/plain": [
"int"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Basic data types in python\n",
"# integer\n",
"x = 4\n",
"print(x)\n",
"type(x)"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "9f1b3ac5",
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "JMjJSKmVfhfF",
"outputId": "dc199516-0f91-43d9-b15f-e1751b6bed02"
},
"outputs": [
{
"data": {
"text/plain": [
"float"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# float\n",
"y = 2.5\n",
"type(y)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "4236157b",
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "ppjTaS4ffhRn",
"outputId": "1450f424-e59a-407a-9b12-d363c88aa754"
},
"outputs": [
{
"data": {
"text/plain": [
"bool"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# boolean\n",
"t = True\n",
"f = False\n",
"type(t)"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "3e86e5d0",
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "m78GlycUfhHS",
"outputId": "d61a3753-e443-410a-f750-c0105a7985fc"
},
"outputs": [
{
"data": {
"text/plain": [
"str"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# string\n",
"message = \"hello, There\" # you can use \" \" or ' ', it doesn't matter\n",
"type(message)"
]
},
{
"cell_type": "markdown",
"id": "0866adae",
"metadata": {
"id": "ytOHrGmg-JoU"
},
"source": [
"___\n",
"### **Exercise**\n",
"\n",
"Write a Python program with one variable to store your `name` and then print the value of the variable.\n",
"\n",
"* Step 1: Declare variable\n",
"\n",
"* Step 2: Print the result using the print() function"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "e90c946d",
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "7TzDRg6gBtGZ",
"outputId": "7de95168-e012-4981-b97a-3ed08154a0d2"
},
"outputs": [],
"source": [
"# your code here"
]
},
{
"cell_type": "markdown",
"id": "316c5ba9",
"metadata": {
"id": "vNqpGoI4MFtv"
},
"source": [
"## Declaring or changing the type of a variable\n",
"\n",
"If necessary, we can change the type of a variable to another one using the commands: `int()`, `float()`, and `str()`. See some examples below:"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "7ec7dccc",
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "nbHqjExbk9e8",
"outputId": "f2e7861b-6503-464d-ce12-ce2661b07362"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2.5 \n"
]
}
],
"source": [
"v = float(2.5) # v is float\n",
"print(v, type(v))"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "1ec95442",
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "PMa3Bpoyk-9A",
"outputId": "dd722571-34dc-4b90-ee3d-d690faefa99b"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2 \n"
]
}
],
"source": [
"# from float to integer\n",
"v = int(v)\n",
"print(v, type(v))"
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "c6aa831e",
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "2V7ou4kfMJd5",
"outputId": "65cfcc0d-43c4-42b2-f49e-8718a691f294"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2 \n"
]
}
],
"source": [
"# from float to string\n",
"v = str(v) # v is not a number anymore but string\n",
"print(v, type(v))"
]
},
{
"cell_type": "markdown",
"id": "af79c0d5",
"metadata": {
"id": "cK-0dWJvvOuL"
},
"source": [
"Later you'll see more examples of how you can convert the type of variable. One common example is to convert numbers read from a text file (_str_) to numbers (_int_ or _float_) to perform arithmetic operations on them."
]
},
{
"cell_type": "markdown",
"id": "9cec6b99",
"metadata": {
"id": "p-8P3rduMQjW"
},
"source": [
"## Reassign values\n",
"\n",
"You can reassign a new value to an old variable. By doing so, Python ignores the old value and replaces it with the new value. Below is an example."
]
},
{
"cell_type": "code",
"execution_count": 10,
"id": "5845aa5f",
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "zIwo0V7VL_eP",
"outputId": "c6c71230-c9bc-4c66-91d0-f12905b326db"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"6\n"
]
}
],
"source": [
"m = 3 # first assignment\n",
"m = 6 # re-assignment\n",
"print(m)"
]
},
{
"cell_type": "markdown",
"id": "3465aa7f",
"metadata": {
"id": "Oq-0HwMlvwuQ"
},
"source": [
"Here is a simple example where we convert a fraction (4 out of 10, written as a decimal) to a percentage and reassign it to the same value."
]
},
{
"cell_type": "code",
"execution_count": 11,
"id": "69534fa5",
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "s9QtvS9FvxMn",
"outputId": "5fd0a0ce-cc0e-4818-977d-5c078bd42710"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"40.0\n"
]
}
],
"source": [
"completed_steps = 0.4 # first assignment\n",
"completed_steps = completed_steps*100 # re-assignment\n",
"print(completed_steps)"
]
},
{
"cell_type": "markdown",
"id": "b0da761d",
"metadata": {
"id": "yT5AL0jlBuj4"
},
"source": [
"----\n",
"### **Exercise**\n",
" Write a Python program that: assigns value 2.8 to the variable `num`, prints its type and then changes the type of `num` to `int`. Print the variable `num`'s type and value again to make sure your code works properly.\n",
"\n",
" * Step 1: Declare variable `num` and assign the value 2.8 to it\n",
" * Step 2: Print the type of variable `num`\n",
" * Step 3: Change the type of variable `num` to `int`\n",
" * Step 4: Print the type and value of the variable `num` again"
]
},
{
"cell_type": "code",
"execution_count": 12,
"id": "84a63c93",
"metadata": {
"id": "e-0M81ApFIl3"
},
"outputs": [],
"source": [
"# your code here"
]
},
{
"cell_type": "markdown",
"id": "8a2e924d",
"metadata": {
"id": "IxAjg6yhkrYz"
},
"source": [
"## `Print()` Function\n",
"Here we take a break from variables and focus on the `print()` function, as we will be using it very often to display text and variables. We will cover basic printing, string concatenation, and introducing some options to format the output.\n",
"\n",
"* __Basic printing:__ Let's start by printing a simple text (string) message"
]
},
{
"cell_type": "code",
"execution_count": 13,
"id": "505b3088",
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "f8HVuVMcmcjh",
"outputId": "3a5f2c0e-f952-461f-bba4-ac19b1144089"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hello, world!\n",
"\n",
"Life is short,\n",
"and the world is wide.\n",
"\n"
]
}
],
"source": [
"# printing simple text\n",
"print(\"Hello, world!\")\n",
"\n",
"# printing multiple lines\n",
"quote = \"\"\"\n",
"Life is short,\n",
"and the world is wide.\n",
"\"\"\"\n",
"print(quote)"
]
},
{
"cell_type": "markdown",
"id": "b00198a8",
"metadata": {
"id": "_2EONmxYrEJj"
},
"source": [
"* __Printing variables:__ You can also print the values of variables using the `print()` function. For printing multiple variables or texts you can use `,` in between them (providing multiple inputs to the function)."
]
},
{
"cell_type": "code",
"execution_count": 14,
"id": "06ab1750",
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "TQisBty2rHdO",
"outputId": "7c23e8ea-759e-44c1-815c-2e21539ad223"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"25\n",
"My name is Alice and I am 25 years old.\n"
]
}
],
"source": [
"name = \"Alice\"\n",
"age = 25\n",
"\n",
"# printing single variables\n",
"print(age)\n",
"\n",
"# printing multiple variables and text\n",
"print(f\"My name is {name} and I am {age} years old.\")"
]
},
{
"cell_type": "markdown",
"id": "9ff73dce",
"metadata": {
"id": "zem1oFufrGmd"
},
"source": [
"* __Formatting options:__\n",
"You may also see examples where F-strings orthe `.format()` method are used to provide a concise way to embed or insert variables within strings for printing. This can be done in two ways:"
]
},
{
"cell_type": "code",
"execution_count": 15,
"id": "44e53d17",
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "mf0Wd3GHrIGu",
"outputId": "3b2ddfc7-b6df-4d28-9906-635623ada269"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The book costs $19.9999.\n",
"The book costs $19.9999.\n",
"The book costs $20.00.\n"
]
}
],
"source": [
"item = \"book\"\n",
"price = 19.9999\n",
"\n",
"print(f\"The {item} costs ${price}.\")\n",
"\n",
"print(\"The {} costs ${}.\".format(item, price))\n",
"\n",
"# for printing only 2 decimal points\n",
"print(\"The {} costs ${:.2f}.\".format(item, price))"
]
},
{
"cell_type": "markdown",
"id": "86bf8238",
"metadata": {
"id": "ps6QqRAutThO"
},
"source": [
"Note that we can also add `.2f` to indicate that we want the float to have two decimals, as seen in the resulting output.\n",
"\n",
"___\n",
"### **Exercise**\n",
"\n",
"Declare a variable `course` and assign it the name of a subject (e.g., \"Math\").\n",
"Declare a variable duration and assign it an integer (e.g., 6).\n",
"Use both the `input()` function with multiple input variables and the string formatting method using `.format()` to print the following message, replacing [course] with the name of the course and [duration] with the duration:\n",
"\n",
"`Explore the world of [course] in just [duration] weeks!`"
]
},
{
"cell_type": "code",
"execution_count": 16,
"id": "5e649f15",
"metadata": {
"id": "SSb-FihVu-t0"
},
"outputs": [],
"source": [
"# your code here"
]
}
],
"metadata": {
"jupytext": {
"text_representation": {
"extension": ".md",
"format_name": "myst",
"format_version": 0.13,
"jupytext_version": "1.16.4"
}
},
"kernelspec": {
"display_name": "Python 3",
"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": [
13,
21,
29,
35,
55,
68,
82,
94,
107,
119,
131,
141,
147,
158,
170,
182,
186,
192,
204,
208,
220,
231,
237,
244,
262,
266,
283,
288,
306,
319
]
},
"nbformat": 4,
"nbformat_minor": 5
}