Newer
Older
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"# Agenda\n",
"\n",
"* Python Syntax \n",
"* Variables & Data Types\n",
"* Operators\n",
"* Decisions\n",
"* Loops\n",
"* Lists\n",
"* Iterations"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"# Python Syntax"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
Jöran Frey
committed
"* Basically, Python code executes from top top bottom\n",
"* Every programming language organizes code in code blocks (statements that belong together)\n",
"* Indentation in Python is very important (it's mandatory not optional)\n",
Jöran Frey
committed
" * Unlike other languages, code blocks do not require brackets {}\n",
" * The number of spaces is up to you you, the most common use is four, but it has to be at least one."
]
},
{
"cell_type": "code",
" print(\"Five is greater than two!\")\n",
" print(\"This is a second statement.\")\n",
"else:\n",
" print(\"The world is a disk!\")"
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"evalue": "expected an indented block (3793329317.py, line 2)",
"\u001b[0;36m Cell \u001b[0;32mIn[4], line 2\u001b[0;36m\u001b[0m\n\u001b[0;31m print(\"Five is greater than two!\")\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mIndentationError\u001b[0m\u001b[0;31m:\u001b[0m expected an indented block\n"
]
}
],
"source": [
"if 5 > 2:\n",
"print(\"Five is greater than two!\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Important Keywords (must not be used as names)\n",
"\n",
Jöran Frey
committed
"* As with every programming language, there are some keywords that belong to the language and must not be used for names\n",
"* Some popular ones are: True, False, None, def, class, break, return\n",
"\n",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"source": [
"import keyword\n",
"print(keyword.kwlist)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
Jöran Frey
committed
"* Python has commenting capabilities for the purpose of in-code documentation.\n",
"* Comments start with a #, and Python will ignore them:"
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [],
"source": [
"# This is a comment\n",
"print(\"Hello, World!\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"source": [
"* Comments can be placed at the end of a line, and Python will ignore the rest of the line"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [],
"source": [
"print(\"Hello, World!\") #This is a comment"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"# Variables and Data Types"
]
},
{
"cell_type": "markdown",
"metadata": {
"vscode": {
"languageId": "plaintext"
}
},
"source": [
Jöran Frey
committed
"* Variables are an essential concept to store data.\n",
"* Python has no command for declaring a variable.\n",
Jöran Frey
committed
"* A variable is automatically created when you first assign a value to it.\n",
"* In Python, variables are not declared with any particular type.\n",
"* To output the value of a variable, we use the `print()` command.\n",
"\n",
"Let's see some examples"
]
},
{
"cell_type": "code",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"10\n",
"This is a string\n"
]
}
],
"source": [
"x = 10\n",
"print(x)\n",
"y = \"This is a string\"\n",
"print(y)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Naming Conventions\n",
"\n",
"* It is very important to choose meaningful names for variables\n",
Jöran Frey
committed
" * This will make your code better readable to others as well\n",
" * You need fewer comments to explain your code\n",
"* These are the most important rules and conventions:\n",
" * PEP 8 Style Guide for Python Code https://peps.python.org/pep-0008/#naming-conventions\n",
" * A good summary can be found here: https://medium.com/@rowainaabdelnasser/python-naming-conventions-10-essential-guidelines-for-clean-and-readable-code-fe80d2057bc9"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Most Important Naming Conventions\n",
"\n",
"* Names **never start with a number**\n",
Jöran Frey
committed
"* We **don't use special characters** in names (ASCII compatiblity)\n",
"* **Variable and Function Names**: Use `snake_case` (all lowercase letters with words separated by underscores).\n",
"* **Constants**: Use `ALL_CAPS` with words separated by underscores. Constants are usually defined at the top of a module.\n",
"* **Boolean Variables**: Should be named to sound like a yes/no question or statement, often starting with `is`, `has`, `can`, or `should`. E.g., `is_approved`\n",
"* **Class Names**: Use `PascalCase` (each word starts with an uppercase letter, no underscores)."
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
Jöran Frey
committed
"* Variables store values, and these values are of a particular type\n",
"* Different types exhibit different behavior\n",
" * Adding two integers will result in the arithmetic sum\n",
" * Adding two strings will result in a string containing both substrings\n",
" * different data types have different functions available"
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"9\n",
]
}
],
"source": [
"x = 4\n",
"y = 5\n",
"z = x + y\n",
"print(z)\n",
"\n",
"x = \"Text\"\n",
"y = \" more text\"\n",
"z = x + y\n",
"print(z)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Data Types II\n",
"\n",
"These are the built-in data types of Python\n",
"\n",
"| Type Category | Data Types |\n",
"|---------------------|------------------------------------|\n",
"| Text Type | 'str' |\n",
"| Numeric Types | 'int', 'float', 'complex' |\n",
"| Sequence Types | 'list', 'tuple', 'range' |\n",
"| Mapping Type | 'dict' |\n",
"| Set Types | 'set', 'frozenset' |\n",
"| Boolean Type | 'bool' |\n",
"| Binary Types | 'bytes', 'bytearray', 'memoryview' |\n",
"| None Type | 'NoneType' |\n",
"\n",
Jöran Frey
committed
"Some of these we will use soon, while others you will learn throughout the semester."
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Boolean Data Type\n",
"\n",
"* Boolean: `bool` has only two possible values: `True` or `False`\n",
"* In programming you often need to know if an expression is `True` or `False`.\n",
Jöran Frey
committed
"* E.g. comparing values always returns boolean result\n",
"* Technically `False` correspons to the value of 0, any other number is considerd `True` (will be important for casting to bool)\n",
"\n",
"\n"
]
},
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 1,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"10 > 9"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"source": [
"* Boolian variables / expressions are important for decisions"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"10 is greater than 9\n"
]
}
],
"source": [
"is_true = 10 > 9\n",
"if (is_true):\n",
" print(\"10 is greater than 9\")\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Number Data Type\n",
"\n",
"Python konws 3 numeric data types:\n",
Jöran Frey
committed
"| Type | Explanation | Example |\n",
"| --------- | ----------------------------------------------------------------------------------------------------- | ---------------------- |\n",
"| `int` | A whole number, positive or negative, without decimals, of unlimited length. | 3, 88, -12837654 |\n",
"| `float` | Float, or \"floating point number\" is a number, positive or negative, containing one or more decimals. | 7.5, 1212.875620, 35e3 |\n",
Jöran Frey
committed
"| `complex` | Complex numbers are written with a \"j\" as the imaginary part: | 3+5j |"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"x = 10 # int\n",
"y = 10.0 # float needs a .0 to be a float\n",
"z = 2 + 3j # complex"
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"source": [
"Float can also be scientific numbers with an \"e\" to indicate the power of 10"
]
},
{
"cell_type": "code",
"execution_count": 38,
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
Jöran Frey
committed
"* Besides numbers, we often want to process text in our programms\n",
"* Strings in python are surrounded by either single quotation marks, or double quotation marks. `'hello'` can be used as well as `\"hello\"`."
"execution_count": 12,
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [],
"source": [
"my_name = \"John\"\n",
"my_name = 'John'"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" * Special characters must be \"escaped\" with a I \\ (\\n = return, \\t = tabulator)\n",
" * \" is allowed inside singel quotes, ' is allowed inside double quotes"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"my_text = \"this is 'ok' a double-quote needs an escape: \\\" to work\"\n",
"my_text = 'here we can use \"\" but \\' must be escaped'\n",
"print(\"this is a \\nreturn\")"
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"* Strings can be concatibated"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"John Doe\n"
]
}
],
"source": [
"first_name = \"John\"\n",
"last_name = \"Doe\"\n",
"full_name = first_name + \" \" + last_name\n",
"print(full_name)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"source": [
"* Strings have various functions, that can be accessed"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"JOHN DOE\n",
"2\n"
]
}
],
"source": [
"print(full_name.upper())\n",
"print(full_name.count(\"o\"))"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Type Casting\n",
"\n",
"* Sometimes you want to explicitly change the data type of a variable\n",
"* This process is called casting or type casting\n",
"* In Python we do have functions to do this\n",
"* Casting functions are available for all built-in datatypes, where the function name equals the type name\n",
Jöran Frey
committed
"Here are the most important ones:"
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"<class 'str'>\n",
"3\n",
]
}
],
"source": [
"a = str(3) # Change an int value to a string\n",
"print(type(a))\n",
"b = int(3.7) # Change a float value to an int\n",
"print(b)\n",
"c = float(3) # Change an int value to a float\n",
"print(c)\n",
"c = int(\"3\") # Change a string value to a int\n",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"* In Python, everything is an Object (an instance of a complex data type with functions and behavior)\n",
Jöran Frey
committed
"* More precise, a variable points to an instance of an object\n",
"* The `is` operator checks whether two variables point to the same object in memory, not just if they have the same value."
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"data": {
"text/plain": [
"4537738384"
]
},
"execution_count": 17,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"x = 10.0\n",
"id(x)"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"data": {
"text/plain": [
"4537738384"
]
},
"execution_count": 18,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"y = x\n",
"id(y)"
]
},
Jöran Frey
committed
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"x is y"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"x is 10.0"
]
},
"\n",
"* However, a new assignment creates a new object."
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"data": {
"text/plain": [
"4455295664"
]
},
"execution_count": 15,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"y = 20.0\n",
"id(y)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"* Thus, variables can be reassigned to a different type at runtime (variable remains a pointer, but to a different address/object)."
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"<class 'int'>\n",
"<class 'str'>\n"
]
}
],
"source": [
"x = 10\n",
"print(type(x))\n",
"x = \"This is a string\"\n",
"print(type(x))"
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"# Operators "
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
Jöran Frey
committed
"* To work (compare, add, etc.) with variables, we need operators\n",
"* Python categorizes operators into the following groups:\n",
" * Arithmetic operators\n",
" * Assignment operators\n",
" * Comparison operators\n",
" * Logical operators\n",
" * *Identity operators*\n",
" * *Membership operators*\n",
" * *Bitwise operators*\n",
"\n",
"Reference: https://www.w3schools.com/python/python_operators.asp "
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Arithmetic Operators\n",
"\n",
"We need arithmetic operators to calculate.\n",
"\n",
"| Operator | Name | Example |\n",
"|----------|----------------|----------|\n",
"| `+` | Addition | `x + y` |\n",
"| `-` | Subtraction | `x - y` |\n",
"| `*` | Multiplication | `x * y` |\n",
"| `/` | Division | `x / y` |\n",
"| `%` | Modulus | `x % y` |\n",
"| `**` | Exponentiation | `x ** y` |\n",
"| `//` | Floor division | `x // y` |\n"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"data": {
"text/plain": [
"25"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"5**2"
]
},
{
"cell_type": "markdown",
"metadata": {
"vscode": {
"languageId": "plaintext"
}
},
"source": [
"## Assignment Operators\n",
"\n",
Jöran Frey
committed
"We need assignment operators to assign values to variables.\n",
"\n",
"| Operator | Example | Same As |\n",
"|----------|---------|-------------|\n",
"| `=` | `x = 5` | `x = 5` |\n",
"| `+=` | `x += 3`| `x = x + 3` |\n",
"| `-=` | `x -= 3`| `x = x - 3` |\n",
"| `*=` | `x *= 3`| `x = x * 3` |\n",
"| `/=` | `x /= 3`| `x = x / 3` |\n"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"10\n"
]
}
],
"source": [
"x = 5\n",
"x *=2\n",
"print(x)"
]
},
{
"cell_type": "markdown",
"metadata": {
"vscode": {
"languageId": "plaintext"
}
},
"source": [
"## Comparison Operators\n",
"\n",
"Comparison operators are needed to make decisions.\n",
"The result of a comparison operator is always `true`or `false`.\n",
"\n",
"| Operator | Name | Example |\n",
"|----------|-----------------------------|-----------|\n",
"| `==` | Equal | `x == y` |\n",
"| `!=` | Not equal | `x != y` |\n",
"| `>` | Greater than | `x > y` |\n",
"| `<` | Less than | `x < y` |\n",
"| `>=` | Greater than or equal to | `x >= y` |\n",
"| `<=` | Less than or equal to | `x <= y` |"
]
},
{
"cell_type": "code",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"data": {
"text/plain": [
"False"
]
},
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"4 == 2"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"data": {
"text/plain": [