Skip to content

Instantly share code, notes, and snippets.

@MishaelRosenthal
Last active February 16, 2023 00:54
Show Gist options
  • Save MishaelRosenthal/e414d8a2290e260fc6e9d84b524a0229 to your computer and use it in GitHub Desktop.
Save MishaelRosenthal/e414d8a2290e260fc6e9d84b524a0229 to your computer and use it in GitHub Desktop.
introduction-to-python.ipynb
Display the source blob
Display the rendered blob
Raw
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"provenance": [],
"authorship_tag": "ABX9TyMbEtCew+BtFZq2dtJB0OoZ",
"include_colab_link": true
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
}
},
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "view-in-github",
"colab_type": "text"
},
"source": [
"<a href=\"https://colab.research.google.com/gist/MishaelRosenthal/e414d8a2290e260fc6e9d84b524a0229/introduction-to-python.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
]
},
{
"cell_type": "markdown",
"source": [
"# Introduction to Python\n",
"\n",
"By ChatGPT and Mishael Rosenthal\n",
"\n",
"This lesson was partially generated by ChatGPT. To be frank, I am not sure if ChatGPT helped me, or I helped it ;-)\n",
"\n",
"## Intorduction\n",
"Python is a popular programming language that has many advantages for beginners and experienced programmers alike. Here are some reasons why Python is a good language to learn:\n",
"\n",
"* Easy to read and write: Python has a syntax that is easy to understand and write. It emphasizes code readability and simplicity, making it an ideal language for beginners to learn.\n",
"* Versatile: Python can be used for a wide variety of applications, such as web development, data analysis, machine learning, game development, and more. This means that once you learn Python, you'll have many different career paths and projects to choose from.\n",
"* Large community and resources: Python has a large community of developers and users who create and share resources such as libraries, modules, and frameworks. This means that there are many resources available for learning and troubleshooting Python.\n",
"* Career opportunities: Python is one of the most in-demand programming languages in the job market. Learning Python can open up many job opportunities in industries such as technology, finance, healthcare, and more.\n",
"* Interpreted language: Python is an interpreted language, which means that code can be executed directly without being compiled first. This makes it easier and faster to write and test code.\n",
"\n",
"Overall, Python is a great language for beginners to learn because it's easy to use, versatile, has a large community, and many career opportunities.\n",
"\n",
"Shall we dive in?"
],
"metadata": {
"id": "8BC6_Fkw-pD9"
}
},
{
"cell_type": "markdown",
"source": [
"## Variables\n",
"Variables are used to store data in memory so that it can be used later in your code. To assign a value to a variable, use the ```=``` operator:"
],
"metadata": {
"id": "6nPxXbq_-0pb"
}
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "dowrMp2k9j56"
},
"outputs": [],
"source": [
"x = 10\n",
"y = \"Hello, world!\""
]
},
{
"cell_type": "markdown",
"source": [
"Note that you run a code block using the play button on the left. You can rerun it as many times a s you want."
],
"metadata": {
"id": "nUa7yGpKHY-k"
}
},
{
"cell_type": "markdown",
"source": [
"## Printing\n",
"The ```print()``` function in Python is used to output information to the console. It takes one or more arguments, and prints them to the console.\n",
"\n",
"Here's an example:"
],
"metadata": {
"id": "gd8klZe2h_TA"
}
},
{
"cell_type": "code",
"source": [
"print(x)\n",
"print(y)"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "9FEiMdHjiCOS",
"outputId": "b5b4af23-fd98-48f1-ce39-cf0f20bef0c4"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"10\n",
"Hello, world!\n"
]
}
]
},
{
"cell_type": "markdown",
"source": [
"**Exercise**:\n",
"Define two variables ```a, b``` and print them."
],
"metadata": {
"id": "i7u1brKx_HEH"
}
},
{
"cell_type": "code",
"source": [],
"metadata": {
"id": "0sRQokpm_RnV"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"You can also pass multiple arguments to the ```print()``` function, separated by commas. The function will concatenate these arguments with a space in between them, and print the resulting string to the console. Here's an example:"
],
"metadata": {
"id": "xKOp1DpFiVhd"
}
},
{
"cell_type": "code",
"source": [
"name = \"Alice\"\n",
"age = 25\n",
"print(\"My name is\", name, \"and I am\", age, \"years old.\")"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "UWGvp3QuiZNt",
"outputId": "bd3f9cc9-d78a-4374-dd8d-9f0264f7d361"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"My name is Alice and I am 25 years old.\n"
]
}
]
},
{
"cell_type": "markdown",
"source": [
"**Exercise**: Print your name and age."
],
"metadata": {
"id": "6HfbfTPQid10"
}
},
{
"cell_type": "code",
"source": [],
"metadata": {
"id": "24-kp_HvieFU"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"## Data types\n",
"Python supports several data types, including:\n",
"\n",
"* Strings (text)\n",
"* Integers (whole numbers)\n",
"* Floats (decimal numbers)\n",
"* Booleans (true or false values)\n",
"\n",
"\n",
"\n"
],
"metadata": {
"id": "55zYRYjg_Sol"
}
},
{
"cell_type": "code",
"source": [
"name = \"Alice\"\n",
"age = 27\n",
"height = 1.75\n",
"is_student = True"
],
"metadata": {
"id": "MoiYZ5Gt_zxm"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"Note that strings are encapsulated by quotation marks."
],
"metadata": {
"id": "iA6s8xI6_7-q"
}
},
{
"cell_type": "markdown",
"source": [
"## Arithmetic operators\n",
"Python supports several arithmetic operators, including:\n",
"\n",
"* Addition: ```+```\n",
"* Subtraction: ```-```\n",
"* Multiplication: ```*```\n",
"* Division: ```/```\n",
"* Division whole (quotient): ```//```\n",
"* Modulo (remainder): ```%```"
],
"metadata": {
"id": "IlWQqmzrANyu"
}
},
{
"cell_type": "code",
"source": [
"a = 12\n",
"b = 5\n",
"\n",
"print(\"sum is\", a + b)\n",
"print(\"difference is\", a - b)\n",
"print(\"product is\", a * b)\n",
"print(\"quotient is\", a / b)\n",
"print(\"whole quotient is\", a // b)\n",
"print(\"reminder is\", a % b)"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "SGK9WNqqAoeS",
"outputId": "89de41fa-4c96-4be5-b616-2013b8a5ed53"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"sum is 17\n",
"difference is 7\n",
"product is 60\n",
"quotient is 2.4\n",
"whole quotient is 2\n",
"reminder is 2\n"
]
}
]
},
{
"cell_type": "markdown",
"source": [
"**Exercise**: Calculate and print the whole quotient and reminder of dividing 57 by 5."
],
"metadata": {
"id": "x2l6DQeCD89h"
}
},
{
"cell_type": "code",
"source": [],
"metadata": {
"id": "mJoFUrTEELM5"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"## Conditional statements\n",
"Conditional statements are used to control the flow of your program based on certain conditions. In Python, the most commonly used conditional statement is the ```if``` statement:"
],
"metadata": {
"id": "vtqA-bpzfpYT"
}
},
{
"cell_type": "code",
"source": [
"x = 10\n",
"\n",
"if x > 5:\n",
" print(\"x is greater than 5\")\n",
"else:\n",
" print(\"x is less than or equal to 5\")"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "LQidCSfUfuRt",
"outputId": "e47ba65c-4551-4d1f-8b54-5ce95019b596"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"x is greater than 5\n"
]
}
]
},
{
"cell_type": "markdown",
"source": [
"## Numeric Comparison Operators:\n",
"Python provides several comparison operators for comparing numeric values. These operators\n",
"\n",
"\n",
"\n",
" include:\n",
"\n",
"* ```<```: less than\n",
"* ```<=```: less than or equal to\n",
"* ```>```: greater than\n",
"* ```>=```: greater than or equal to\n",
"* ```==```: equal to\n",
"* ```!=```: not equal to\n",
"\n",
"These operators are used to compare two numeric values, and return a Boolean value of True or False depending on whether the comparison is true or false.\n",
"\n",
"Here is an example that shows how to use these operators:"
],
"metadata": {
"id": "g7Wk1NDdgyCy"
}
},
{
"cell_type": "code",
"source": [
"x = 5\n",
"y = 10\n",
"\n",
"if x < y:\n",
" print(\"x is less than y\")\n",
"\n",
"if x <= y:\n",
" print(\"x is less than or equal to y\")\n",
"\n",
"if y > x:\n",
" print(\"y is greater than x\")\n",
"\n",
"if y >= x:\n",
" print(\"y is greater than or equal to x\")\n",
"\n",
"if x == 5:\n",
" print(\"x is equal to 5\")\n",
"\n",
"if y != 5:\n",
" print(\"y is not equal to 5\")"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "XksAxEz9hebn",
"outputId": "481a9df1-9801-4cdf-9ad8-2ca2cbe53b09"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"x is less than y\n",
"x is less than or equal to y\n",
"y is greater than x\n",
"y is greater than or equal to x\n",
"x is equal to 5\n",
"y is not equal to 5\n"
]
}
]
},
{
"cell_type": "markdown",
"source": [
"**Exercise**: Define two variables ```a, b```, check if ```a >= b``` or not, and print an appropriate message for each case."
],
"metadata": {
"id": "yWAyLWOk5YFp"
}
},
{
"cell_type": "code",
"source": [],
"metadata": {
"id": "3fkAj46A53h-"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"## Loops\n",
"Loops are used to repeat a block of code multiple times. Python has two types of loops:\n",
"\n",
"* \"for\" loops, which repeat a block of code for each element in a sequence (such as a list or a string)\n",
"* \"while\" loops, which repeat a block of code as long as a certain condition is true"
],
"metadata": {
"id": "NpkC3qT-6ah6"
}
},
{
"cell_type": "code",
"source": [
"# for loop example\n",
"for i in range(10):\n",
" print(i)\n",
"\n",
"print()\n",
"\n",
"# while loop example\n",
"i = 0\n",
"while i < 10:\n",
" print(i)\n",
" i += 1"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "ChVlkcuU6rJ2",
"outputId": "877927fd-f491-41dd-ef6d-59f1d2e92bcb"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"0\n",
"1\n",
"2\n",
"3\n",
"4\n",
"5\n",
"6\n",
"7\n",
"8\n",
"9\n",
"\n",
"0\n",
"1\n",
"2\n",
"3\n",
"4\n",
"5\n",
"6\n",
"7\n",
"8\n",
"9\n"
]
}
]
},
{
"cell_type": "markdown",
"source": [
"## Ranges\n",
"\n",
"The ```range()``` function is used to generate a sequence of numbers. The ```range()``` function can take one, two, or three arguments:\n",
"\n",
"* ```range(stop)```: generates a sequence of numbers from 0 up to (but not including) stop.\n",
"* ```range(start, stop)```: generates a sequence of numbers from start up to (but not including) stop.\n",
"* ```range(start, stop, step)```: generates a sequence of numbers from start up to (but not including) stop, incrementing by step.\n",
"\n",
"Here are some examples to help illustrate how to use the ```range()``` function:"
],
"metadata": {
"id": "owRTqIlm9wcY"
}
},
{
"cell_type": "code",
"source": [
"# Example 1: generating a sequence of numbers up to a stop value\n",
"for i in range(5):\n",
" print(i)\n",
"\n",
"print()\n",
"\n",
"# Example 2: generating a sequence of numbers between a start and stop value\n",
"for i in range(2, 6):\n",
" print(i)\n",
"\n",
"print()\n",
"\n",
"# Example 3: generating a sequence of numbers between a start and stop value with a step\n",
"for i in range(1, 10, 2):\n",
" print(i)\n"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "k1oQFL5R-Ln8",
"outputId": "ae0fb8d8-146b-4bf5-cfd0-15104850784f"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"0\n",
"1\n",
"2\n",
"3\n",
"4\n",
"\n",
"2\n",
"3\n",
"4\n",
"5\n",
"\n",
"1\n",
"3\n",
"5\n",
"7\n",
"9\n"
]
}
]
},
{
"cell_type": "markdown",
"source": [
"**Exercise**: Print the numbers between 5 and 30 (30 included) in steps of 5."
],
"metadata": {
"id": "DgPu7BGM-gCM"
}
},
{
"cell_type": "code",
"source": [],
"metadata": {
"id": "NXzUiKyU-wh1"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"## Lists\n",
"Lists are a fundamental data structure in Python, and they're used to store collections of items.\n",
"\n",
"### Creating Lists\n",
"To create a list, use square brackets ```[ ]``` and separate the items with commas. You can store any type of data in a list:"
],
"metadata": {
"id": "KQfl1SuB7QI9"
}
},
{
"cell_type": "code",
"source": [
"my_list = [1, 2, 3, \"apple\", \"banana\", \"cherry\"]\n",
"\n",
"for element in my_list:\n",
" print(element)"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "LP-u79DY7m9X",
"outputId": "5f50311b-c96e-4ced-b29c-b94a9195eebd"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"1\n",
"2\n",
"3\n",
"apple\n",
"banana\n",
"cherry\n"
]
}
]
},
{
"cell_type": "markdown",
"source": [
"### Accessing List Items\n",
"You can access individual items in a list using their index, which starts at ```0``` for the first item:"
],
"metadata": {
"id": "4rrEIqpq7nuX"
}
},
{
"cell_type": "code",
"source": [
"my_list = [1, 2, 3, \"apple\", \"banana\", \"cherry\"]\n",
"\n",
"print(my_list[0]) # returns first element\n",
"print(my_list[1]) # returns second element\n",
"print(my_list[-1]) # returns the last element"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "X_s_j5qa7ugY",
"outputId": "02ef86e1-14bb-4c66-a304-41819b8fd2c5"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"1\n",
"2\n",
"cherry\n"
]
}
]
},
{
"cell_type": "markdown",
"source": [
"Note that we can print a list using the ```print()``` function directly without using a ```for``` loop."
],
"metadata": {
"id": "ETG76MhkC-v_"
}
},
{
"cell_type": "markdown",
"source": [
"### Modifying Lists\n",
"You can modify the items in a list by accessing them using their index and assigning a new value:"
],
"metadata": {
"id": "x5ASKMiS73jT"
}
},
{
"cell_type": "code",
"source": [
"my_list = [1, 2, 3, \"apple\", \"banana\", \"cherry\"]\n",
"\n",
"my_list[0] = 10 # replaces the first item with 10\n",
"my_list[-1] = \"orange\" # replaces the last item with \"orange\"\n",
"\n",
"for element in my_list:\n",
" print(element)"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "fFHLW-v48I9H",
"outputId": "dc969fcb-c852-404f-8404-03705b696799"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"10\n",
"2\n",
"3\n",
"apple\n",
"banana\n",
"orange\n"
]
}
]
},
{
"cell_type": "markdown",
"source": [
"Lists can be manipulated using a variety of built-in methods. Here are a couple of examples:\n",
"\n",
"* ```append(x)```: adds an item ```x``` to the end of the list.\n",
"* ```insert(i, x)```: inserts an item ```x``` at a specific position ```i``` in the list.\n",
"* ```pop([i])```: removes the item at the specified index ```i``` (or the last item in the list if no index is specified) and returns it.\n",
"\n"
],
"metadata": {
"id": "LsnM5Wvn9EWp"
}
},
{
"cell_type": "code",
"source": [
"my_list = [0, 1, 2, 3]\n",
"\n",
"my_list.append(4)\n",
"print(my_list)\n",
"\n",
"my_list.pop(1)\n",
"print(my_list)\n",
"\n",
"my_list.pop()\n",
"print(my_list)\n"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "cAUTv0TI9Jop",
"outputId": "f610b70b-a70e-49f1-e1c2-fb713cbc0822"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"[0, 1, 2, 3, 4]\n",
"[0, 2, 3, 4]\n",
"[0, 2, 3]\n"
]
}
]
},
{
"cell_type": "markdown",
"source": [
"**Exercise**: Using the ```my_list``` list we defined above. Add and remove elements in the \"right\" indices until you get ```[-1, 1, 3, 5]```, then print it."
],
"metadata": {
"id": "6h2JbRmk9OQf"
}
},
{
"cell_type": "code",
"source": [],
"metadata": {
"id": "ZIpOdYsoDxTi"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"## Functions\n",
"\n",
"In Python, you can define your own functions using the ```def``` keyword. Here's the basic syntax for defining a function:\n",
"\n",
"\n",
"```\n",
"def function_name(parameter1, parameter2, ...):\n",
" # Code block\n",
" # This is where you define the behavior of the function\n",
" return value\n",
"```\n",
"\n",
"Let's break down this syntax:\n",
"\n",
"* ```def```: This keyword is used to define a new function.\n",
"* ```function_name```: This is the name of the function you are defining. It should be descriptive and follow Python's variable naming conventions (e.g., no spaces, use underscores to separate words, etc.).\n",
"* ```parameter1, parameter2, ...```: These are the parameters that the function takes as input. You can specify as many parameters as you need, and they can have default values if desired.\n",
"* ``:``: This colon indicates the start of a new code block.\n",
"* ```# Code block```: This is where you write the code that defines the behavior of the function. You can use any Python code here, including other functions or loops.\n",
"* ```return value```: This statement returns a value from the function. If your function doesn't need to return a value, you can omit this line.\n",
"Here's an example function that takes two numbers as input and returns their sum:\n"
],
"metadata": {
"id": "SxiVTjmQDx7D"
}
},
{
"cell_type": "code",
"source": [
"def add_numbers(x, y):\n",
" sum = x + y\n",
" return sum"
],
"metadata": {
"id": "pxNKvdsiEjxU"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"Once you've defined a function, you can call it in your code like this:"
],
"metadata": {
"id": "lzYPzYXjEkwk"
}
},
{
"cell_type": "code",
"source": [
"result = add_numbers(2, 3)\n",
"print(result) "
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "ZoVBT_4SEpcp",
"outputId": "20419017-9746-4162-97c7-3bdf32f54deb"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"5\n"
]
}
]
},
{
"cell_type": "markdown",
"source": [
"We can also re-use the result as an input parameter:"
],
"metadata": {
"id": "VUfW0H1yEu8u"
}
},
{
"cell_type": "code",
"source": [
"result = add_numbers(result, 7)\n",
"print(result)"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "7rXbeuxPE0_o",
"outputId": "724004c6-25ac-43b9-c3bc-d5be817dc771"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"12\n"
]
}
]
},
{
"cell_type": "markdown",
"source": [
"**Exercise**: Write a ```subtract_number``` function and use it and the ```add_numbers`` function to calculate 7+5-6-9 "
],
"metadata": {
"id": "H2NBOv2FFDRO"
}
},
{
"cell_type": "code",
"source": [],
"metadata": {
"id": "scOaQpKXSGAR"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"The ```input()``` function in Python allows you to prompt the user to enter some text, and then store that text as a string. Here's the basic syntax for using the ```input()``` function:"
],
"metadata": {
"id": "29EmABY1R6__"
}
},
{
"cell_type": "code",
"source": [
"name = input(\"What's you name\")\n",
"\n",
"print(\"Nice to meet you\", name)\n"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "3HICpTZYFl_8",
"outputId": "03cca4a1-d77e-4fdd-d984-6732eddb570c"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"What's you nameDavid\n",
"Nice to meet you David\n"
]
}
]
},
{
"cell_type": "markdown",
"source": [
"To get an integer input from the user using the ```input()``` function, you can use the following syntax:"
],
"metadata": {
"id": "DrNwKDWfSjI7"
}
},
{
"cell_type": "code",
"source": [
"age = int(input(\"How old are you?\"))\n",
"\n",
"print(\"That's great, I am\", 42-age, \"years older than you!\")"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "TNMPptAOSprb",
"outputId": "7d913868-4bc9-453f-ff5e-ea9a8bb32325"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"How old are you?12\n",
"That's great, I am 30 years older than you!\n"
]
}
]
},
{
"cell_type": "markdown",
"source": [
"**Exercise**: Using the `input()` and the `add_number()` functions, get two numbers from the user, add them and print the result."
],
"metadata": {
"id": "ybl6bAAmS9EM"
}
},
{
"cell_type": "code",
"source": [],
"metadata": {
"id": "grJXR0DKTNYX"
},
"execution_count": null,
"outputs": []
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment