Skip to content
Snippets Groups Projects
Commit 0a65bcc0 authored by Auke Klazema's avatar Auke Klazema
Browse files

Added example program to discuss

parent 4ec9a4bf
No related branches found
No related tags found
No related merge requests found
%% Cell type:markdown id:a1b0abfd-330c-4c9a-81e0-8c996948cf16 tags:
# Introduction to programming in Python
Author: Auke Klazema (klazema@astron.nl)
Length: 2.5 days
%% Cell type:markdown id:fcd3b24a-b187-4241-8d57-6ec3a9c631e3 tags:
## Introduction
The rules of computation are simple to explain, but it takes many years to master. Similar to the game of Chess or Backgammon. We have 2.5 days together to get the basic concepts explained and understood. It will be a first step in you journey as a programmer. How far you take the journey is up to you.
The limit of 2.5 days will mean that, just with your first lessons in say mathematics, I will have to leave things out. For example I will not be able to cover Object Oriented Programming or Functional Programming.
After finishing these days you will know how to program in a basic way, that will already be helpful in automating your life. And just as with running, where you can call yourself a runner if you run, you can call yourself a programmer when you program. Lets start.
%% Cell type:markdown id:785876cb-ef7d-46cf-aa9e-20950b6e8574 tags:
## What is computer programming?
Programming is solving problems with computations. Its describing a process in an accurate way with discrete steps.
So that sound really vague. So let me try to clear it up a bit. A computer exists of a Central Processing Unit (CPU) that can perform certain task. It also has some form of temporary storage (memory). And to be useful it also has some interfaces to the outside world, like a monitor or a keyboard interface. The CPU performs tasks on memory, like adding up two numbers and storing the result in memory.
These individual computational tasks can be combined to solve all sorts of problems. The task of the programmer is to find a combination of task that will solve a problem. If one of tasks is missing or performed in a wrong order the program is incorrect. So one has to be very precise.
The discipline surrounding the actual programming is usually called software engineering. There are many ways to go about it and the discipline is still young so there still is no clear cut way of doing things. But it all has to deal with combining small steps that describe a process.
%% Cell type:markdown id:f8081ed1-9c6b-4c0b-8f10-0cc8fad37a9a tags:
## What is a programming language?
%% Cell type:markdown id:21ae0352-d5d0-4d91-ac9f-31c5f5fdccd0 tags:
The CPU takes in information from a form of memory. This could be a harddrive, USB thumbdrive, SD card, etc. And it tries to decode the information into instructions it can perform. Many instructions sets start with an operational code (op-code) and then continue with decoding its parameters if it has any. These are just numbers represented by 0s and 1s.
A computer can be programmed by providing a long list of numbers. In the past some computers were programmed by toggling switches to represent numbers and another switch to tell the computer to process that number. Luckily some programmers decided they could write programs to help translate the sequence of instructions into numbers. And this started the creation of many programming languages.
So a programming language has the task to turn textual input into numbers that represent instructions the computer understands. The early programming languages had a one to one relationship between words and numbers. With the added benefit that the process can also be reversed. These languages were later extended to help with repeating common patterns in the instructions. For example a sequence of code was repeated many times and therefore the concept of loops were introduced. The loops got there own instructions that did not have a one on one relationship any more.
Later the one on one relationship was abandoned more and more, where certain instructions in the programming language resulted in multiple computer instructions. These languages provided abstractions for common patterns. Now the reversal becomes very difficult and not guaranteed to be the same as the original.
In this sense a programming language provides higher building blocks than the computer is providing. This makes the life of the programmer easier by giving up on some of the flexibility that you have when you have full control over the computer. With the newer languages we more and more step away from the computer we are working on. This has a benefit that code could run on more than one type of computer, but with a possible downside of not taking full use of the capabilities of the computer in use.
There a couple of paradigms of solving problems with computation. Each with there own benefits and downsides. There is procedural programming, Object Oriented programming, logical programming, functional programming, etc. Some programming languages work only well with one paradigms where others cater to more than one.
Usually one gets away with using a general-purpose programming language, but at other times one might need to look into a specialized programming language. Its the job of the programmer to pick the right tool for the job. Which one is the best depends on multiple factors as you might have guessed already.
The many options and different ways of solving a problem with a computer makes programming still feel more like an art than a science. But to be honest most of the time it even feels more like magic where we create tools out of invisible stuff.
%% Cell type:markdown id:9740996d-8206-42ef-83af-d6cb052e15a2 tags:
## Installing Python 3
%% Cell type:markdown id:17af43c5-b1f9-4ac3-9280-0128dcd73921 tags:
Python comes preinstalled on many systems, but if its not it can be installed in many ways. You could download a binary or an install package from the python website: https://www.python.org/downloads/release/python-3100/
### Windows
* Windows Store
* Python website (see above url)
* Windows Subsystem for Linux (WSL)
### GNU/Linux
* Package manager
### MacOS
* Homebrew package
* Python website (see above url)
### Anaconda
Another popular python distribution in the (data) science world is the Anaconda distribution: https://www.anaconda.com/products/individual. It has installation options for windows, GNU/Linux and MacOS
### Jupyter lab
This presentation is created in Jupyter lab. It provides an environment that combines code and text. This makes it ideal for science purposes, because it facilitates documented and reproducible code. It can also be used to log your work/experiments. During the course you will see some of the functionalities of Jupyter lab demonstrated.
https://jupyter.org/install
%% Cell type:markdown id:ecf1f80a-3312-4f3c-85c8-6199daad071d tags:
## Python 3 introduction
%% Cell type:markdown id:f4e3dffa-63dd-4301-ac18-762be4b55cfc tags:
### Python 2
We used to have Python 2. It had a long life (20 years), but its no longer supported. You will still find a lot of code examples and libraries around for Python 2. Please don't use it anymore. The operating systems will stop supporting it as well soon. Luckily we still have Python 3 which is a mature successor (12 years old).
A clear hint that code is python 2 is the old way of printing strings
%% Cell type:code id:4dfcdf73-b032-45f7-ab24-883322040c83 tags:
``` python
print "Hello World"
```
%% Cell type:markdown id:ef5a0ffa-1454-458d-b911-9a268e39b20b tags:
### Version check
You can check your installed version with:
```
python --version
```
Maybe both python2 and python3 are installed. In that case it could be that the python binary/link still points to python2. You could check if there is a python3 binary installed.
```
python3 --version
```
%% Cell type:markdown id:16a5201f-e74f-4fd3-bd31-73cb1b312609 tags:
### Definition
Definition from wikipedia:
https://en.wikipedia.org/wiki/Python_(programming_language)
>Python is an interpreted high-level general-purpose programming language. Its design philosophy emphasizes code readability with its use of significant indentation. Its language constructs as well as its object-oriented approach aim to help programmers write clear, logical code for small and large-scale projects.
>
>Python is dynamically-typed and garbage-collected. It supports multiple programming paradigms, including structured (particularly, procedural), object-oriented and functional programming. It is often described as a "batteries included" language due to its comprehensive standard library.
Executive summary from python.org
https://www.python.org/doc/essays/blurb/
> Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Its high-level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components together. Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance. Python supports modules and packages, which encourages program modularity and code reuse. The Python interpreter and the extensive standard library are available in source or binary form without charge for all major platforms, and can be freely distributed.
> Often, programmers fall in love with Python because of the increased productivity it provides. Since there is no compilation step, the edit-test-debug cycle is incredibly fast. Debugging Python programs is easy: a bug or bad input will never cause a segmentation fault. Instead, when the interpreter discovers an error, it raises an exception. When the program doesn't catch the exception, the interpreter prints a stack trace. A source level debugger allows inspection of local and global variables, evaluation of arbitrary expressions, setting breakpoints, stepping through the code a line at a time, and so on. The debugger is written in Python itself, testifying to Python's introspective power. On the other hand, often the quickest way to debug a program is to add a few print statements to the source: the fast edit-test-debug cycle makes this simple approach very effective.
%% Cell type:markdown id:026b1539-ff19-43be-bb28-910db491afeb tags:
### Syntax
The syntax of the language determines which combination of symbols form a correct expression or statement. We will dive into different aspects of Pythons syntax during the entire course, but two items I want to introduce early. Namely comments and blocks.
#### Comments
A comment is a piece of text that gets ignored by the language and is used to communicate with the reader of the code.
In Python comments start with a '#'. And it will ignore the entire text till the end of the line.
%% Cell type:code id:55b489a8-2568-4418-82f1-d16b74ce8a6d tags:
``` python
#!/bin/env python3
# This is a comment
```
%% Cell type:markdown id:75e6c775-ad35-4e5c-8647-6601787904e5 tags:
#### Blocks
Blocks are a defining feature of Pythons syntax. They are created with indentation. Here we see that text formatting is used to indicate what belongs together. Many other languages don't use indentation for this but use special characters.
Blocks will shown in examples when we get to functions and flow control. But beware that you can't just introduce indentation without any effect. It often cause many errors when used incorrectly.
%% Cell type:markdown id:22265140-8995-4178-a11f-43e452c7fa92 tags:
### Running python code
#### From a file
You can place your code into a plain text file. The file usually has the .py extension. You can then run the code with the following command:
`python filename.py`
Under GNU/Linux and MacOS you can also add the shebang `#!/bin/env python3` as the first line to tell your shell how to run the code following it. You will need to make the file executable with `chmod +x`.
Under MacOS you can also assign the Python Launcher 3 to python files.
Under windows a simple double click would work as well if the python interpreter is assigned to the py extension.
#### Directly in the REPL
You can also experiment with the REPL by starting the python on the command line. The interpreter is waiting for you input and will directly interpret your input when you have entered it. It will report any error or perform your request. Your results are not saved so any results that you want to keep need to be copied to a file. But the direct interaction with python helps a lot with learning and debugging.
%% Cell type:markdown id:5ff828d3-e466-4cbb-b0a0-9daf7457207f tags:
## Finding documentation
Python has a build in documentation system. In the REPL you can ask for help on object and concepts. For example we can run help on functions.
https://docs.python.org/
The official python documentation mostly cover python and its libraries. For all the other questions you can use your favorite search engine. Be careful with what you copy and paste because it might have bugs or vulnerabilities in them. Many searches end up at stack overflow. This is a question and answer site for technical questions.
https://stackoverflow.com/
Many of the external python libraries are documented on "read the docs".
https://readthedocs.org/
%% Cell type:markdown id:cf433491-7990-443f-ae1a-3157a09a3c37 tags:
## First working program
Lets start out with a working simple program.
%% Cell type:code id:f3b3fb00-a25e-4050-8d41-ad9a10678bf9 tags:
``` python
#!/bin/env python3
print("Hello World")
```
%% Cell type:markdown id:0fbd93a6-fa1c-4f38-a6e5-99c2ec222c91 tags:
This is a small script / program that outputs the string plus a newline on the standard output.
The first line is the shebang that tells my terminal how to run the program. This way I only have to execute my script and the terminal feeds it into python. An alternative is to run it directly with python like so: python helloworld.py
Then we have a empty line that gets ignored by Python. The last line contains a built-in function called "print" and this function accepts a couple of arguments. In this case I gave it the string "Hello World".
### Exercise
Run the program directly in the terminal. And put the program into a file and run it that way.
### Internal documentation
Lets look up the documentation for print.
%% Cell type:code id:6bf448b7-7e4f-46ff-81d8-0b94d97104fe tags:
``` python
#!/bin/env python3
help(print)
```
%% Cell type:markdown id:6ec87341-5d37-4c12-a849-0ed856c55e67 tags:
The print documentation can also be found on the online documentation at python.org at https://docs.python.org/3/library/functions.html#print
```
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
Print objects to the text stream file, separated by sep and followed by end. sep, end, file and flush, if present, must be given as keyword arguments.
All non-keyword arguments are converted to strings like str() does and written to the stream, separated by sep and followed by end. Both sep and end must be strings; they can also be None, which means to use the default values. If no objects are given, print() will just write end.
The file argument must be an object with a write(string) method; if it is not present or None, sys.stdout will be used. Since printed arguments are converted to text strings, print() cannot be used with binary mode file objects. For these, use file.write(...) instead.
Whether output is buffered is usually determined by file, but if the flush keyword argument is true, the stream is forcibly flushed.
Changed in version 3.3: Added the flush keyword argument.
```
%% Cell type:markdown id:701d1e4e-fc0a-4164-abac-cc2f49f5c88b tags:
So based on the information given in this first section I could spend days talking. But this is a beginners course on programming. We happen to use Python as our tool of learning so lets get some basics out of the way first. Its fine if not everything is understood from the start because I will revisit them later.
The help text of print talks about values, streams, sys.stdout. It mentions functions, objects and modules. It also mentions optional keywords and strings. We only have 2.5 days so I will need to leave out a lot of things that Python offers. Some will be covered in other courses Astron will give, but others will need to be learned through other means.
### Exercise
Run help() in the REPL to see what options it gives. And also run help(print) to see what that provides. Also try out help on some other functions / concepts.
%% Cell type:markdown id:2babb3aa-8be9-4fe2-8dbc-f3fa8aff2574 tags:
## First broken programs
Your programs will be broken a lot, especially in the beginning, so lets see how to deal with that.
Your programs will be broken a lot, especially in the beginning, so lets see how to deal with that. If your program is broken most of the time you will be confronted with an exception. Exceptions are a way of informing the user or programmer that something is wrong.
%% Cell type:code id:6d99111d-b279-4f22-8862-8c59df632237 tags:
``` python
#!/bin/env python3
printer("Hello World")
```
%% Cell type:markdown id:95082acd-7c8b-4138-9189-84af128a0a93 tags:
This program will give a NameError.
This program will give a NameError exception.
%% Cell type:code id:0c656ee3-870f-4f51-aad4-4fd2dbf160b6 tags:
``` python
#!/bin/env python3
print("Hello World")
```
%% Cell type:markdown id:93564fff-c8c9-4059-89f2-82d29453f28e tags:
This program will give an IndentationError. Indentation is very important in a Python program.
This program will give an IndentationError exception. Indentation is very important in a Python program.
%% Cell type:code id:9fc26361-3d9c-4160-a245-6ef36ff8317f tags:
``` python
#!/bin/env python3
print("Hello World)
```
%% Cell type:markdown id:7b84478e-b8c8-48ad-b6b5-b29d4b21ad3d tags:
This program will give a SyntaxError
This program will give a SyntaxError exception.
%% Cell type:code id:d77d3d4e-f0ca-4df2-82b6-198bc61a3995 tags:
``` python
#!/bin/env python3
# lets raise some exception ourselves to tell that there is something wrong.
raise Exception("Something is wrong")
```
%% Cell type:markdown id:4df3af9b-23e2-45c5-82ed-e7deb2b376aa tags:
### Exercise
Try to break your program in the same and more ways.
%% Cell type:markdown id:5a83d289-4df8-47b8-8187-e103319f85e2 tags:
## Numbers
One of the most basic data types in Python, and most other programming languages, are numbers.
Python offers integers, floats, complex, Decimal and Fraction. For the course we will only go into integers and floats.
%% Cell type:code id:680027f3-13eb-4632-ab75-7801eed203b1 tags:
``` python
#!/bin/env python3
# this is an integer
1
```
%% Cell type:code id:63970c76-b3cc-4baf-9cf3-56e411c5c172 tags:
``` python
#!/bin/env python3
# this is a float
1.1
```
%% Cell type:markdown id:d1368dbd-7ae7-46de-8b7b-26f438cf78ba tags:
To see of with what type of number python is working with we can always ask the type of anything in python with the type() function.
%% Cell type:code id:fe7ca668-54f5-45d2-98d8-43b43efe18d4 tags:
``` python
type(1)
```
%% Cell type:code id:fc018a67-d3b8-4a60-8e06-ce40d4fa1f42 tags:
``` python
type(1.1)
```
%% Cell type:code id:7a382ce2-76e1-4fc7-8c94-a8301aca22b2 tags:
``` python
type(1+2J)
```
%% Cell type:markdown id:32d8f383-db80-479a-9aab-20cc430e9739 tags:
## Basic math
Now that we have introduced numbers we can start doing some math with it. Out of the box Python provides most of the basic math operations you would expect. +, -, * and /.
%% Cell type:code id:5e8d4385-1f26-4c41-963f-95ac2207f683 tags:
``` python
1 + 2
```
%% Cell type:code id:bfa6e62e-063c-4f47-b255-709736ba2c15 tags:
``` python
1 - 2
```
%% Cell type:code id:7527ea33-fda7-4f7b-b315-149a998f528d tags:
``` python
1 / 2
```
%% Cell type:code id:fffb310a-c899-43be-a6f0-f0187d2321e6 tags:
``` python
1 * 2
```
%% Cell type:markdown id:62bf9c89-2072-457b-ad72-ffa99c0df49d tags:
But there is also //, %, **.
%% Cell type:code id:cb45e17f-d04e-441e-852e-171f06bbe466 tags:
``` python
1 // 2
```
%% Cell type:code id:2efad625-5a60-4ffd-828e-8b4a1689cf17 tags:
``` python
1 % 2
```
%% Cell type:code id:550ed6ac-026c-4c3b-b7f0-12e2cc56d4ae tags:
``` python
2 ** 2
```
%% Cell type:markdown id:57451d2e-ca2f-41c0-a85b-387aa60932e7 tags:
You can combine all the operations and number types.
%% Cell type:code id:6c8332df-d2c7-4dae-8b6c-beb05c44fe49 tags:
``` python
6 * 3 - 2.2
```
%% Cell type:markdown id:8023c798-fb79-4e2a-ac2d-ee18df1dfa94 tags:
In python we also have to deal with the operator precedence. If we want to influence the order of application we will need to use parentheses '(' and ')'.
%% Cell type:code id:a11d00c0-c61d-4cd2-bc9b-0c6ca856cccb tags:
``` python
6 * (3 - 2)
```
%% Cell type:markdown id:895e415e-5a33-47c0-9474-baaca7c9fead tags:
### Exercise
Perform some calculations and see if you can find some unexpected results.
%% Cell type:markdown id:41925997-1b78-44a5-a336-ae9a2c87960c tags:
## Variables
A variable is a name or pointer to a value. To create a variable we can pick a name and assign it a value with the '=' character like so:
%% Cell type:code id:ec429a84-de01-40bf-8bc6-67aaea81d240 tags:
``` python
name = 1
print(name)
```
%% Cell type:markdown id:b57b1f6f-8ffd-4941-ad11-4a488adeba80 tags:
We cant pick any name for a variable. A variable needs to start with letter or an underscore. The remainder of the variable name can only be alpha-numeric characters or underscores.
%% Cell type:code id:7734e532-9edd-4013-a838-6ecfe32dcb85 tags:
``` python
# These are all variable names that are allowed
_hello = 1
hello = 1
hello2 = 1
hello_3 = 1
Hello_A = 1
```
%% Cell type:code id:85cfaf9b-5309-4ac7-8fd9-2034e4adb4f9 tags:
``` python
# This one does not start with a letter or an underscore
1_value = 1
```
%% Cell type:code id:d379fb9d-30a3-4505-b98c-d5a77c0b500c tags:
``` python
# This one includes a non alpha-numeric. (remember _ are allowed)
t@or = 1
```
%% Cell type:code id:d9ec65ab-937c-4943-9b10-f923d4ee0363 tags:
``` python
der. = 1
```
%% Cell type:markdown id:86e1659b-dbdb-4873-82d0-bea56b9a29ec tags:
There are also reserved words we can't use.
| Reserved | Reserved | Reserved | Reserved | Reserved |
| --- | --- | --- | --- | --- |
| False | await | else | import | pass |
| None | break | except | in | raise |
| True | class | finally | is | return |
| and | continue | for | lambda | try |
| as | def | from | nonlocal | while |
| assert | del | global | not | with |
| async | elif | if | or | yield |
%% Cell type:code id:fc0f7f9b-440b-4d16-bc12-24fafd18a112 tags:
``` python
None = 1
```
%% Cell type:code id:7d460e27-69e1-4885-ba6c-b00ca6f233ca tags:
``` python
if = 1
```
%% Cell type:code id:5ca05cdd-9fb6-49af-a5b4-6bd0cea82309 tags:
``` python
with = 1
```
%% Cell type:markdown id:e9a4844c-e536-45ce-bc87-c572204c2ad2 tags:
And variables are case sensitive.
%% Cell type:code id:6d88c116-5e8e-4623-9af7-4176f87ad7a5 tags:
``` python
a = 1
A = 2
print(a)
print(A)
```
%% Cell type:markdown id:7b845940-7289-4373-aa50-3dc0887d8b7a tags:
The general coding style used by the Python developers is written down in pep8. It also has something to say about variable names:
> Variable names should be lowercase, with words separated by underscores as necessary to improve readability.
%% Cell type:code id:9ab676b5-8fbd-43ae-acac-c1c76bb40954 tags:
``` python
total_amount = 22
```
%% Cell type:markdown id:9703da1e-d26e-4941-beb4-14b7cafc5e45 tags:
We can change the value of the variable at all times. Even if the value is of a different type.
%% Cell type:code id:984dd4bf-8f79-4dda-9d86-f71f0f117cce tags:
``` python
value = 1
print(value)
value = "Hello"
print(value)
```
%% Cell type:markdown id:98e5daea-9135-49d8-9459-1b757590ab9c tags:
### Exercise
Ask the user for two numbers and print the result of some math operation on those numbers. You can use the input() function to get the user input. See small example below.
%% Cell type:code id:68528cd0-d4c1-4e86-93c1-f5e1d187fc84 tags:
``` python
user_input = input("What is your name?")
print("Hello", user_input)
```
%% Cell type:markdown id:65ae8a92-a9cd-4994-b443-0a987cf12c36 tags:
### Scope
The scope where a variable can be used is limited to the block its defined in. A block can be the global block or a function block or a loop block. The search for the variable is always upward. So first the local block is searched and only if it can't be resolved there it will go up. We will come back to this concept later on.
%% Cell type:markdown id:2d5d509d-2735-4ff0-9417-d2969f991958 tags:
## Functions
A function is a grouping of instructions that gets its own name and variables. This is one of the abstraction options most programming languages provide. It allows the concept contained in the function to be reused in multiple places as well. We have seen a few examples of functions already namely print(), input(), help(), and type().
We invoke a function by calling its name and adding parentheses. Between the parentheses we can specify parameters if they are required.
We could create long programs without any function created by ourselves. This is fine for short scripts that perform a small task. But once programs become bigger then that, functions will provide the needed abstraction to keep the code readable and maintainable.
%% Cell type:code id:2a201b96-0d2c-4a25-bc88-32e98d78e71d tags:
``` python
print("*******")
print("Hello")
print("*******")
print("*******")
print("World")
print("*******")
```
%% Cell type:markdown id:f7524fe0-d24c-4ece-bfc1-d3fa6a90ff3e tags:
This program prints words with rows of stars before and after it. If I have to this for a lot of words it become very repetitive and error prone. I might forget a star for example. We can make it a bit easier by putting part of the code in a function and call that function a couple of times.
%% Cell type:code id:7ad8fa73-e3c9-4c30-ba17-0bff43eb440f tags:
``` python
def star_print(word):
print("*******")
print(word)
print("*******")
star_print("Hello")
star_print("World")
```
%% Cell type:markdown id:6d6172f4-87d3-4c08-90d4-369f64ea2936 tags:
A function definition starts with the reserved word def followed by the name of the function and the parentheses. Between the parentheses we can provide parameters we need for the function. We can have as many parameters as we need but its usually good to limit it to a max of 3. This prevents the function to do too much. A function is most clear to understand, change and reuse if it does only one thing/task. In our case with print a word surrounded by stars.
Also pick your names of functions and variable such that an external user understands what it does/means. We could also have chosen oe3 for the function name and l for the parameter name. Python doesn't care about the names but the reader does.
%% Cell type:code id:171ef230-e9ed-4a73-a44f-b85075882365 tags:
``` python
def eo3(l):
print("*******")
print(l)
print("*******")
eo3("Hello")
eo3("World")
```
%% Cell type:code id:797a3072-8ab0-41df-8573-ea813b28a113 tags:
``` python
# multiple positional parameters
def important_function(param_one, param_two):
pass
important_function(1, 2)
```
%% Cell type:code id:3ea4e9a5-05cb-433d-800d-6f843c7b7b54 tags:
``` python
# using keyword arguments, order can be different than with original parameter list.
def important_function(param_one, param_two):
pass
important_function(param_two=2, param_one=1)
```
%% Cell type:markdown id:8e3a3ac0-6d8c-41b4-b881-eee7780d320b tags:
Keyword arguments can be used to be either more explicit or specify one of the default values. This can also be useful for functions with a lot of default values. But what are default values?
%% Cell type:code id:cd20f1cd-382e-4bc3-865b-eb20434d6db0 tags:
``` python
# default values can be used to make parameters optional
def function(name, greeting="Hello"):
print(greeting, end=" ")
print(name)
function("World", "Hi")
function("World")
function("World", greeting="Yo")
```
%% Cell type:markdown id:833c9e7f-2d3f-4955-b8d5-1383fbb1e251 tags:
A function can also return a object as a result of the function. We could use that to a calculation on the parameters for example. To indicate what to return we use the reserved word "return".
%% Cell type:code id:2349a128-b5aa-4d52-81ce-ff17cc47bdee tags:
``` python
def square(number):
return number * number
square(3)
```
%% Cell type:markdown id:521f3e07-1edc-44e7-afc6-c20114289b47 tags:
### Exercise
Create a function that expects two parameters that get added together and is returned by the function. Call the function a couple of time with different values and print the results.
%% Cell type:markdown id:7eeddda0-c8d9-4caa-8a70-02f1b26f1fae tags:
### Scope
Scope determines the range wherein names get resolved. So when code refers to some variable or function it will try to locate it in a limited space and in a specific order. Some examples:
%% Cell type:code id:35be1bf0-2474-48f6-b322-6b73e2e2650d tags:
``` python
# name is in the global space
name = "Astron"
def print_something():
# name is created in the local space of print_something
name = "Lofar"
# prints the local space name
print(name)
print_something()
# prints the global space name
print(name)
```
%% Cell type:code id:5e04fc82-06ef-4abf-bfed-25ec3d80a06e tags:
``` python
# name is in global space
name = "Astron"
def print_something():
# prints the name in global space
print(name)
print_something()
print(name)
```
%% Cell type:code id:6595d2c7-e14c-40fc-bf3f-5760762b0945 tags:
``` python
name = "Astron"
def print_something():
# in the local space we can't change the global space unless we mark the local variable global
# this way we tell python we want to work with the variable available in the global space
global name
name = "Lofar"
print(name)
print_something()
print(name)
```
%% Cell type:markdown id:52ffa212-b1d5-4466-9e83-648eee755315 tags:
### Exercise
Play with the scope options.
%% Cell type:markdown id:bb1d80f2-640b-4d80-8fd4-ef310008b3b0 tags:
## Strings
Python documentation describes as: "immutable sequences of Unicode code points.". So we get a chain of Unicode characters but we cannot change anything in the chain.
There are three ways of writing string literals.
%% Cell type:code id:c979d150-9c12-4327-b565-15abe1d1c386 tags:
``` python
# Double quoted
print("Hello world")
```
%% Cell type:code id:02fa86ad-deea-4faf-88c6-4c58cc20da4b tags:
``` python
# Single quoted
print('Hello world')
```
%% Cell type:code id:e5ba08fc-c1f6-480f-b266-5e5588088e42 tags:
``` python
# Tripple double or single quoted
print("""Hello
World""")
print('''Hello
World''')
```
%% Cell type:markdown id:2aee0843-6262-4437-9b28-1f7a343353b7 tags:
The triple quoted version allows text to span over multiple lines.
%% Cell type:markdown id:7da3e2e3-2761-45ac-8ad4-69ce88073e26 tags:
You can include single quotes inside a double quoted string and vice versa.
%% Cell type:code id:52191429-1b46-4a83-9fa7-c517a27b2553 tags:
``` python
print("Hello 'world'")
```
%% Cell type:code id:3a669e92-3d70-4a6f-a63e-7297dbb2b23b tags:
``` python
print('Hello "world"')
```
%% Cell type:markdown id:9698eccd-9b07-48c7-a3ae-ee8c30349390 tags:
If you want to mix thing up you need to "escape" the quotes with a \ like so:
%% Cell type:code id:1a228894-08d7-4427-8b1d-dd1189d197cb tags:
``` python
print("'Hello' \"world\"")
```
%% Cell type:markdown id:07a37174-e4df-4fc2-9ed5-93e3c8bded12 tags:
### Exercise
Create a couple of strings and combine different quotations. And try to figure out how to include a \ in your string.
%% Cell type:markdown id:423663c9-ffc9-4932-bc39-e6c28ff5da46 tags:
Sometimes we need to know the length of a string and we can do that with a function called len(). Len() is a function that will return the number of items in a container. A container is a general term for data types that hold items. A string is a container the holds unicode characters.
%% Cell type:code id:823a3626-607c-4b36-9649-a2f2f6ddd89c tags:
``` python
len("Hello")
```
%% Cell type:markdown id:87e70f9a-3cf6-4eb8-880e-3486b022ab1a tags:
Other times we want to know the first character of a string. We can do that with an index. And in most programming languages we count from 0 when it comes to indexes. This confuses most beginner programmers but the is a clear historical and technical explanation for it. But I leave that for a coffee break if people are interested.
%% Cell type:code id:c474f9ce-6261-4367-b06d-7bed69957a95 tags:
``` python
# This gives the first character
"Hello World"[0]
```
%% Cell type:code id:ea1b0267-a714-4c29-937c-b530ce5f97f6 tags:
``` python
# This gives the last character
"Hello World"[-1]
```
%% Cell type:markdown id:6fc8ff90-9cf8-43db-8034-c0668ea282cb tags:
We can also take a slice of the string by giving up a range like so:
%% Cell type:code id:24172988-9803-4a3f-a403-ef9ffa047b9d tags:
``` python
"Hello World"[1:3]
```
%% Cell type:code id:2f218244-ae5a-4116-ac1e-491ae5b3e0c3 tags:
``` python
"Hello World"[-3:-1]
```
%% Cell type:markdown id:46cd2d57-af00-458f-9a34-69956ccf9eaa tags:
Notice that the range it up to and does not include the end of the range. You could also leave out a number of the range.
%% Cell type:code id:838eb491-4885-45d7-9df6-19c316602de5 tags:
``` python
# Here we don't care about the ending part. We only want to skip the first two chars
"Hello World"[2:]
```
%% Cell type:code id:9309812a-3170-4d59-b966-82166eb5c747 tags:
``` python
# Here we don't specify the 0. This is a form that is not used alot because it doesn't have any benefits.
"Hello World"[:4]
```
%% Cell type:code id:3fea243c-0b03-44e0-aa25-2f6374cd0e72 tags:
``` python
# Here we ask for a copy of the entire string and can be seen in code bases for that reason.
"Hello World"[:]
```
%% Cell type:markdown id:da426233-05e1-4b6c-a74d-d8e8221862d9 tags:
### Exercise
Get familiar with indexing and slices.
%% Cell type:markdown id:13062210-3974-4d3c-ad6e-488cb08e632b tags:
## Objects intermezzo
Even though we will not be discussing Object Oriented Programming in this course, I do need to discuss the concept of Objects because just about anything in Python is an object.
So an object is formally an instance of a class. Where the class forms the blueprint from which you can create objects. An object is a shell around data that can be manipulated with methods provided by the object. The data can be directly exposed but most of the time its hidden.
This gives us programmers a new form of syntax for dealing with objects. Methods are functions on an object and are called on the object by adding a . to the end of the instance and the name of the method.
For example:
%% Cell type:code id:a5c0b80c-7ced-48c5-8fda-c3296b824227 tags:
``` python
hello = "Hello"
hello.upper()
```
%% Cell type:markdown id:0ce2f5d1-4e21-4a51-bb47-6a7deed00cb5 tags:
And properties are data on an object and are used by adding a . to the end of the instance and the name of the property.
For example:
%% Cell type:code id:f1ef23d5-34c5-4184-9842-bb96a6940e79 tags:
``` python
a = 1+3J
print(a.imag)
print(a.real)
```
%% Cell type:markdown id:cd26d763-f070-4fea-a46a-645cd6c279ab tags:
A nice way to see what methods and properties are available is to use help and dir. Help we have already seen and gives you documentation on a functions, objects and other concepts. Dir provides all the attributes of an object:
%% Cell type:code id:600391b4-007b-4ae0-8548-0ee3debeccdd tags:
``` python
help(dir)
```
%% Cell type:code id:5d295fd9-09c8-4ecf-a31e-50d6ddc92db9 tags:
``` python
dir(1)
```
%% Cell type:code id:ba0abafd-c288-4cd3-946f-47cb4800e761 tags:
``` python
help(int)
```
%% Cell type:markdown id:6a5a49aa-e22c-4ba6-a2b9-6bf99e22df18 tags:
## Back to Strings
Lets have a look at some methods on Strings. For example the methods to make all letters uppercase or lowercase letters:
%% Cell type:code id:1d5f6a49-f49b-45e6-a64c-a925ca4b2814 tags:
``` python
"Hello World".upper()
```
%% Cell type:code id:f8fcdb48-5544-4d73-86a2-0725d13bdafe tags:
``` python
"Hello World".lower()
```
%% Cell type:markdown id:89070e58-8ade-405f-9b7d-0307a69a7d83 tags:
So when would this be useful? One use for it is to compare it some other text where you don't care about case sensitivity. There you would upper or lower both strings before comparing.
%% Cell type:markdown id:ddf2804a-5a22-4e59-9615-fdf6ceae07e4 tags:
We can also create a new string by combining strings.
%% Cell type:code id:c4f7171e-863f-48b0-abbc-e13e55e11c5d tags:
``` python
hello = "Hello" + " " + "World"
print(hello)
```
%% Cell type:markdown id:6c95d9cf-4370-47b4-b6da-1933f0333a5e tags:
We can also generate strings by multiplying strings or characters. Very useful if you need a specific amount.
%% Cell type:code id:606c5a7a-767e-43a7-81e0-04a2d17dae54 tags:
``` python
print('+' * 79)
print('|', " Hello " * 11, '|', sep="")
print('+' * 79)
```
%% Cell type:markdown id:ef7b8b6e-cf56-4e5f-ac49-528f88e1f183 tags:
Another way is to use Formatted string literals. This has a mini language on its own so I will only be showing some basic options. We start a formatted string with a f".
%% Cell type:code id:894f39c0-3073-4337-b30d-d991a51a38fc tags:
``` python
# Here we don't use formatting at all. Just a basic string
f"Hello world"
```
%% Cell type:code id:c6cabd8d-6ec8-4504-bc0d-d1b58d0d8c58 tags:
``` python
# Here we want to use the variable directly in the formatted string.
# Python will put the string representative of in the string.
name = "World"
age = 4.6E+9
f"Hello {name} you don't look a day older than {age} years"
```
%% Cell type:code id:91b20aa6-4d2e-4931-9a2e-d74b7987d376 tags:
``` python
# We can also provide hints on how to format things.
name = "World"
age = 4600000000
f"Hello {name} you don't look a day older than {age:.1E} years"
```
%% Cell type:markdown id:c1ef4501-0f22-44bf-9cb9-590c56d14028 tags:
Yet another way that can be used it the format string syntax. Its similar to a Formatted string literals but its a bit more explicit.
%% Cell type:code id:6dac110d-fe50-4fcc-832c-d2b8524b6191 tags:
``` python
"Hello {}".format("World")
```
%% Cell type:code id:ec76336b-afb9-4a8e-9c80-6a4d41061ada tags:
``` python
"Hello {name}".format(name="World")
```
%% Cell type:code id:8cd4909c-c1f4-4b2b-9016-48e695aa4c78 tags:
``` python
"Hello {}, my name is {}".format("World", "Python")
```
%% Cell type:code id:efdc5c29-475a-45e3-9e76-3f868ba30b51 tags:
``` python
"Hello {name}, my name is {program}. Have a nice day {name}.".format(name="World", program="Python")
```
%% Cell type:code id:2be4e458-3254-496b-add4-b82234981766 tags:
``` python
"Hello {0}, my name is {1}. Have a nice day {0}".format("World", "Python")
```
%% Cell type:markdown id:2293f47e-eacb-4132-9a5f-a056d62ff93b tags:
Now it up to you as a programmer to pick the right option. And when you do also go for the option that clearest to read. Usually if strings are repeated often or there are many of them the named options is cleaner. If you have only one or two in a short sentence the simple {} will do.
%% Cell type:markdown id:4e46aafd-a6af-478d-a045-5c050cb2bed1 tags:
### Exercise
Write a program where you ask for some input from the user with the help of input. And then display the user input into a formatted string using the three given options of creating new strings.
%% Cell type:code id:af86fc92-6cfb-4d3c-98b2-81b04d3bc5e4 tags:
``` python
#!/bin/env python3
user_input = input("What is your name?")
print("Hello " + user_input)
```
%% Cell type:markdown id:7c011488-f5dc-4cea-85db-1fa202c2c240 tags:
## Compound data types
So we have seen basic data types like numbers. And strings that are a chain of numbers interpreted as characters. In the end we only have numbers in memory. But as programmers we can give meaning to these numbers and with it we can build complex data structures. We can use numbers to point to memory locations and that is what happens under the hood with the following compound data types.
%% Cell type:markdown id:71fb49a5-69d2-4cbc-9685-8fa8f8f7e7d2 tags:
### lists
Now we don't want to keep track of the meaning of all numbers so we abstract that away in programming languages. One nice abstractions is a grouping of things. We call that a list in many languages. Other languages sometimes call these arrays. So what does a list look like in Python?
%% Cell type:code id:549f88c8-4087-4e97-98af-2983277b520a tags:
``` python
# This is an empty list
[]
```
%% Cell type:code id:a09f4e16-3843-44cd-8753-3b5bb92e7c3e tags:
``` python
# This is a list op numbers
[1, 2, 3, 4, 5]
```
%% Cell type:code id:0e9582a6-7bb5-4215-b54c-968d059f6bf8 tags:
``` python
# We can combine different types of data in a list
[1, "Hello"]
```
%% Cell type:markdown id:6c89200e-07b1-4398-b9e3-b2a37157098e tags:
Combining types is allowed, but for most algorithms that loop over a list it is required to have the items to be of the same type. What you see more often is that data of different types get added together in compound data type and those are then placed in a list. We will see some more examples of that later.
%% Cell type:markdown id:3e955f00-a29c-4c3b-89d9-15acfc02d000 tags:
We can ask the length of a list in the same manner as with strings with len()
%% Cell type:code id:c516367b-1273-4528-a9e6-e8cda17c2365 tags:
``` python
len([1, 2])
```
%% Cell type:markdown id:09da64e8-89b9-4213-8f11-9504a3ca1fd7 tags:
Just with string we can also index and slice lists.
%% Cell type:code id:bca4829b-ac84-49c8-b027-e32bb01cda4c tags:
``` python
[1, 2, 3, 4, 5][0]
```
%% Cell type:code id:9cd21b50-fcf2-4020-982a-bbbd345b5ad7 tags:
``` python
[1, 2, 3, 4, 5][-1]
```
%% Cell type:code id:f57bce1c-c387-4890-b807-6122868b2590 tags:
``` python
[1, 2, 3, 4, 5][1:]
```
%% Cell type:code id:72090cf8-0114-45c0-a708-585d380eb891 tags:
``` python
[1, 2, 3, 4, 5][2:4]
```
%% Cell type:markdown id:eb0019c3-1316-42d8-b475-8cf2c0dec51a tags:
Also just like with strings we can create new lists by adding lists together.
%% Cell type:code id:b31d312f-3ca6-481b-8297-886c3dc9820f tags:
``` python
[1, 2, 3] + [4, 5]
```
%% Cell type:markdown id:df929be9-697d-4360-8f5b-70a6ca400518 tags:
What we could not so with strings we can do with lists. We can alter the contents of the list.
%% Cell type:code id:84483bfd-ffbf-4d78-80d9-40169b9c9d52 tags:
``` python
items = [1, 2, 3]
print(items)
items[2] = 88
print(items)
```
%% Cell type:markdown id:48708919-e711-4983-b44e-d4946da2c868 tags:
We can append items to the list with .append()
%% Cell type:code id:42a9c653-8e46-4293-b3f0-a96fe9e721a4 tags:
``` python
items = []
print(items)
items.append(2)
print(items)
```
%% Cell type:markdown id:bdd33cc2-9399-488e-b33d-399983b0a0a4 tags:
We can also do fancy things with slices.
%% Cell type:code id:a350fa2d-6f81-4408-939d-9c6106cb591b tags:
``` python
items = [1, 2, 3, 4, 5]
print(items)
items[1:4] = [22, 33, 44]
print(items)
items[1:3] = []
print(items)
```
%% Cell type:markdown id:545fb3dd-f1ae-47b7-ae45-b9d231db20f4 tags:
And we can also nest lists.
%% Cell type:code id:c242b92e-9531-4099-9fe1-392b6c37b26c tags:
``` python
items = [[1, 2, 3], [4, 5]]
print(items)
print(items[0])
print(items[0][1])
```
%% Cell type:markdown id:f3c07249-6b68-4d26-89b1-27ddcbd2517b tags:
#### Exercise
Create some lists on your own. Add some together. Try some slices, indexing. Try to replace some items. Also think about a real world problem where lists could be useful.
%% Cell type:markdown id:d43526c9-a515-448d-96eb-16dc9b5e06fb tags:
### tuples
A tuple is an immutable container. One can create a tuple with the parentheses characters '(' and ')'.
%% Cell type:code id:8bc04d51-abd6-45fb-bd72-d31e6b9adddd tags:
``` python
# This is a empty tuple
tup = ()
print(tup)
```
%% Cell type:code id:5f6468cd-7e3b-4c00-8790-931ec09d0eb1 tags:
``` python
# This is a single item tuple notice the ,
tup = (1,)
print(tup)
```
%% Cell type:code id:76e881a3-1aec-4baa-afdd-9fb131c42937 tags:
``` python
# This is a tuple with multiple types
tup = (1, "Astron")
print(tup)
```
%% Cell type:code id:64952409-83b3-4b1a-a549-42ed695ca310 tags:
``` python
# we can index a tuple
(1, "Astron")[0]
```
%% Cell type:code id:25ef0a7b-982d-435b-a4da-59b35683e29b tags:
``` python
# We can't change a tuple once its created
tup = (1, "Astron")
tup[0] = 2
```
%% Cell type:code id:3fb1ef09-cb58-4a52-bc33-d7217f7c70a8 tags:
``` python
# We can also use len() on a tuple
len((1, 2, 3, "Hello"))
```
%% Cell type:markdown id:29f87318-a6a9-4d90-b352-6406720a9bf7 tags:
We can also combine compound data types to create more complex data objects.
%% Cell type:code id:ecd3864c-514c-4f44-aa81-cd273c231e36 tags:
``` python
organizations = []
organizations.append(("Jive", 26))
organizations.append(("Nova", 27))
organizations.append(("Astron", 209))
print(organizations)
```
%% Cell type:markdown id:5b30ebd2-d41d-479d-b472-8d81437e1d5e tags:
So when are tuples useful? If you don't want to have the data changed. It is also slightly more memory efficient since it can't be extended. This requirement does not come up often but the wish to extend or remove data is so lists are more popular then tuples.
Although not enforced by the language we see tuples more used a containers of different types and lists as a container for single types.
%% Cell type:markdown id:91495e4b-450b-4204-a8e7-c98773cc6dd2 tags:
### sets
%% Cell type:markdown id:b67c0e38-d444-4dc7-945f-0a2cd9b9ffd9 tags:
A set is an container for distinct hashable objects. This means it can contain only unique values.
A set is created with the curly braces characters '{' and '}'
%% Cell type:code id:de9a88b4-ebd6-4cc3-8daa-73646a32a4c2 tags:
``` python
individuals = {"Astron", "Jive", "Nova", "Nova"}
print(individuals)
```
%% Cell type:markdown id:6636255a-9de5-4d14-b210-33aed1dd7079 tags:
So what could we do with sets? We could get all the unique items out of a big list. Say we get a list of all the LOFAR stations that had an issue during an observation in the October. We could ask with a set which stations were had an issue during October.
%% Cell type:code id:42459f5d-0412-4204-8f57-67468767e416 tags:
``` python
obs1 = ['CS001']
obs2 = ['CS001', 'CS002']
obs3 = ['CS003']
obs4 = ['FR606', 'CS002']
unique = set(obs1 + obs2 + obs3 + obs4)
print(unique)
```
%% Cell type:markdown id:5824f33b-aef8-42c8-95c6-1cc7fe14add1 tags:
Or we could take out reserved stations from all the stations.
%% Cell type:code id:d78e8f01-b665-4864-b779-704d8bf83c47 tags:
``` python
stations = {'CS001', 'CS002', 'CS003', 'CS004'}
reserved = {'CS002'}
usable = stations - reserved
print(usable)
```
%% Cell type:markdown id:56b0535e-f4df-46e0-874c-65e679227a67 tags:
Or check for overlap:
%% Cell type:code id:4f71e542-a66a-4dcd-ad1e-73a2de07c24e tags:
``` python
obs1 = {'CS002', 'CS003', 'CS004'}
obs2 = {'CS001', 'CS002', 'CS003'}
both = obs1 & obs2
print(both)
```
%% Cell type:markdown id:c233a169-c95f-48a0-a5b4-24ee6f9807c2 tags:
### dictionaries
Dictionaries is a useful compound data type that is a set of key value pairs. They are also created by using curly braces but now it contains a key value pair.
%% Cell type:code id:601c3f43-6226-45ac-85bf-d335f6ad8953 tags:
``` python
item = {'name': "CasA", 'size': 20}
print(item)
```
%% Cell type:code id:483d5667-9b7b-49fe-8e1f-33ddb0cd7221 tags:
``` python
net_code = {'Dwingeloo': '0521', 'Assen': '0592'}
print(net_code)
```
%% Cell type:markdown id:a3aa915b-4b91-44c5-ab8c-12cf62a30674 tags:
One can ask for all the values in a dictionary with .values() and all the keys with .keys()
%% Cell type:code id:37390c12-2f84-45de-82a2-4610b9c9fefb tags:
``` python
net_code = {'Dwingeloo': '0521', 'Assen': '0592'}
print(net_code.keys())
```
%% Cell type:code id:1d5f6026-4e44-4f9e-8bec-8c7a3fef1ceb tags:
``` python
net_code = {'Dwingeloo': '0521', 'Assen': '0592'}
print(net_code.values())
```
%% Cell type:markdown id:d5ec52d1-7e41-4439-b4a8-a46caf0de825 tags:
### Exercise
#### Exercise
Create a program where you ask the user for a multiple items where you ask for some properties for each item. The properties can be stored in a dictionary and be added to a list. Print the list in the end. Try to use functions as well.
%% Cell type:markdown id:13e86fa7-c3ab-45fd-a1c0-876cc51c89c0 tags:
## Flow control
In flow control we decide to run or skip certain code based on truth values. Python has the two object True and False reserved as truth values. The meaning of these objects is quite self explanatory.
Lets get into what things result in truth values.
%% Cell type:code id:a7bbe9e7-fb0e-425b-99e0-bd5deaff739d tags:
``` python
# Comparisons
print(1 == 2)
print(1 != 2)
print(1 < 2)
print(1 > 2)
print(1 <= 2)
print(1 >= 2)
print(False is True)
print(False is not True)
print('a' in "abc")
print('A' in "abc")
```
%% Cell type:markdown id:d477c22c-1671-4eeb-badf-55da4b1df28d tags:
Besides False and True other values can be used as truth indicators. Lets take a quote from the python documentation. https://docs.python.org/3/library/stdtypes.html#boolean-operations-and-or-not
> By default, an object is considered true unless its class defines either a __bool__() method that returns False or a __len__() method that returns zero, when called with the object. 1 Here are most of the built-in objects considered false:
>> constants defined to be false: None and False.
>> zero of any numeric type: 0, 0.0, 0j, Decimal(0), Fraction(0, 1)
>> empty sequences and collections: '', (), [], {}, set(), range(0)
%% Cell type:markdown id:b35aee31-6f50-4bf2-9abb-94ec9df038b5 tags:
### If
Now the fun can begin. We can finally make choices in our programs. The if statement will take a truth value and a block of code to execute if the value is True.
%% Cell type:code id:8cfd8681-38ae-4e29-a32c-548a2466e7f1 tags:
``` python
if True:
print("Hello")
```
%% Cell type:code id:98550e33-e372-423a-9df8-603f92051179 tags:
``` python
if False:
print("Hello")
```
%% Cell type:markdown id:857f42fe-dccd-4ffd-8995-059865c14ddd tags:
We can also introduce a block for the False condition. For that we need the true block and introduce an else block.
%% Cell type:code id:10553bf9-a018-4ae5-9406-884075e5832f tags:
``` python
if False:
print("Hello")
else:
print("World")
```
%% Cell type:markdown id:2d9544e8-3f30-4e38-9cc7-f654f2a64938 tags:
We could also decide we need to check more things before we go into a else block by using elif. Short for else if.
%% Cell type:code id:2f70125b-5ff8-4605-a7c3-f83a8323001f tags:
``` python
if False:
print("Hello")
elif False:
print("World")
else:
print("Bye")
```
%% Cell type:markdown id:dcff0c1c-cb97-43c9-9232-1939dfc4ef0e tags:
What is important to understand is that only one block will be executed. The first that if True will be executed.
%% Cell type:code id:1d13bb5a-c243-4375-85e0-98a7b2fde930 tags:
``` python
if True:
print("Hello")
elif True:
print("World")
else:
print("Bye")
```
%% Cell type:markdown id:70dfd96c-bb7f-47ad-b84b-6388f6b0ce13 tags:
If we do want to also check for the other conditions we should not include it in an else if or elif block.
%% Cell type:code id:567b11d6-0902-4356-bd76-2a2d9df44aa0 tags:
``` python
if True:
print("Hello")
if True:
print("World")
else:
print("Bye")
```
%% Cell type:markdown id:30376e08-b2ce-4b07-8d69-c152d9ad28d1 tags:
We can also negate a truth statement by using "not":
%% Cell type:code id:a3e06ca4-510f-4a35-ba88-876a46209159 tags:
``` python
if not False:
print("True")
else:
print("False")
```
%% Cell type:markdown id:77804c8d-4a6b-4322-82a9-60696df3be31 tags:
So now take a more real world example:
%% Cell type:code id:32696c97-1b5b-4351-b80a-8281155e14e4 tags:
``` python
x = int(input("Please enter an integer: "))
if x < 0:
print('Negative number')
elif x == 0:
print('Zero')
else:
print('Positive number')
```
%% Cell type:markdown id:97a513bc-26ba-471e-ae3a-67b674bde3a9 tags:
### Exercise
#### Exercise
Create a text menu with options. Let the user enter a selection and print something out specific for that option. Use the else to catch an option that you didn't provide. Think about uppercase and lowercase if you don't use numbers as options.
%% Cell type:markdown id:0dfd5dd3-328d-445f-97b1-1ac26a48a0e5 tags:
### While
To repeat certain steps we could call a function multiple time but this is very limited. We could use a looping mechanism in the language. Luckily Python provides a could of those. One of them is the while loop.
It will perform a block until something becomes false.
%% Cell type:code id:d4ff0dac-fe36-4bbc-8a95-0fa73389c219 tags:
``` python
while value := input("Type an animal name: "):
if value.endswith("s"):
print("Ooh I like", value)
else:
print("Ooh I like a", value)
```
%% Cell type:code id:84b4cbea-d617-4502-8254-8038c4d52a66 tags:
``` python
value = 0
while value < 100:
print(value, end=", ")
value = value + value + 1
```
%% Cell type:markdown id:102f9376-db7e-4beb-855c-bbbf36fde65e tags:
### Exercise
#### Exercise
Create a program to calculate the Fibonacci series till a maximum of say 100. https://en.wikipedia.org/wiki/Fibonacci_number
%% Cell type:markdown id:00fa41bf-a364-49d0-9608-71508a7f1044 tags:
### For
The for loop allows an easy way to loop over items in a collection.
%% Cell type:code id:f880f6ff-a4b0-4757-8047-148c329d12a5 tags:
``` python
for item in ("Hello", "World", "And", "Thanks", "For", "The", "Fish"):
print(item, end=" ")
```
%% Cell type:markdown id:f56444df-a1d6-4413-b1e7-ac0b259ad5be tags:
### Exercise
#### Exercise
Loop over a list or tuple with numbers and print out the square of it. You could create a function for the square calculation if you want.
%% Cell type:markdown id:0d2014c1-fc60-4af6-862c-a08cef58cbaf tags:
#### Range
We sometime want to loop based up on a sequence of numbers. We can do this with a range.
%% Cell type:code id:c166c501-25ed-4cea-9e6b-f1849df8d090 tags:
``` python
print(range(5))
```
%% Cell type:code id:eae49e01-f8b9-4571-a769-75badfd83765 tags:
``` python
print(list(range(5)))
```
%% Cell type:code id:870ec3b2-4adb-4be1-83b2-cd5e873e6df8 tags:
``` python
for i in range(5):
print(i)
```
%% Cell type:code id:f77a3494-dcc3-41dd-827f-7145a550c7b7 tags:
``` python
greeting = "Hello World"
for i in range(len(greeting)):
print(i, greeting[i])
```
%% Cell type:code id:beb40a6a-2468-4fe5-8b9d-8dbd693365d9 tags:
``` python
greeting = "Hello World"
for i in range(0, len(greeting)):
print(greeting[i])
```
%% Cell type:code id:b7ebf73d-a58d-4ca5-8a00-b5519c847793 tags:
``` python
greeting = "Hello World"
for i in range(0, len(greeting), 2):
print(greeting[i])
```
%% Cell type:markdown id:ba7f4e9f-51c9-4516-975b-a6365aee1b86 tags:
#### Enumerate
We see that we had to do the indexing of the letter in the range examples. This is a repeating patter that used so often it got its own abstraction. Its the enumerate. It returns a tuple with the index and item.
%% Cell type:code id:6f049e8a-3915-4dca-a37f-ceeda4261f89 tags:
``` python
print(enumerate("Hello"))
print(list(enumerate("Hello")))
```
%% Cell type:code id:68e2e358-dbcd-4a24-a525-9ed5115a2b99 tags:
``` python
greeting = "Hello World"
for i, char in enumerate(greeting):
print(i, char)
```
%% Cell type:markdown id:0d025fb4-d651-431b-96fc-2605d2c18385 tags:
### Break / Continue
Sometimes there is a need to stop early in a loop. For example in searching for an item in a list. Once found you could break the loop early. This can be done with a break.
%% Cell type:code id:b36a44d5-5c5d-41fa-8651-fbbee188a79f tags:
``` python
print("I am looking for something")
for item in ("AMOLF", "ARCNL", "ASTRON", "CWI", "DIFFER", "Nikhef", "NIOZ", "NSCR", "SRON"):
if item.endswith('R'):
print("Ah here it is. It is an", item)
break;
print("Hmm its not", item)
```
%% Cell type:markdown id:c09672b8-61fd-465b-8079-8e970832efd1 tags:
We sometimes might want to skip certain items. For that we can use continue. It will go strait back to the beginning of the loop.
%% Cell type:code id:6d93a538-d310-4859-9696-a8da22a50ee0 tags:
``` python
print("I am looking for something")
for item in ("AMOLF", "ARCNL", "ASTRON", "CWI", "DIFFER", "Nikhef", "NIOZ", "NSCR", "SRON"):
if 'A' in item:
continue
print("Lets go visit", item)
```
%% Cell type:markdown id:bc2110b3-b30d-48d6-8f5a-479d0e69f460 tags:
### Exercise
So now lets combine a lot of things we have learned. Lets create a calculator. Lets take a while loop that is always True. Ask for input from the user. Say two values and an operator. Then print the answer. If the user provides wrong input we tell the user. If the user provides a 'q' character we want to quit the loop. There is no one right answer here.
%% Cell type:markdown id:e24b0155-ddec-4363-a111-a9d8b0670fc6 tags:
## Abstraction
Abstraction is a way to hide details and giving it a name.
We can abstract things in Python with compound data structures, functions, objects, etc.
The abstraction can be helpful in clearly writing down how our process works. And we do this by abstracting details away at the right level. We want to combine abstractions of the same detail level to create another layer of building block with a higher detail level.
We could give a complex check used in an "if" a name to give it a meaning. We want the reader of the code flowing through our code and not have interruptions with lower level details.
%% Cell type:code id:dec7e707-2306-4bc6-ab78-c57eae13b415 tags:
``` python
def turn_to(angle):
print("Turning to angle:", angle)
angle = 44
if angle > 30 and angle < 180:
if angle >= 30 and angle <= 180:
turn_to(angle)
else:
print("Unsafe angle:", angle)
```
%% Cell type:code id:42aee757-0979-401a-adfc-e132f9035e2b tags:
``` python
def turn_to(angle):
print("Turning to angle:", angle)
def is_safe_angle(angle):
return angle > 30 and angle < 180
def report_unsafe_angle(angle):
print("Unsafe angle:", angle)
# ------------------------------------
MIN_ALLOWED_ANGLE = 30
MAX_ALLOWED_ANGLE = 180
def turn_telescope(angle):
if is_safe_angle(angle):
turn_to(angle)
else:
report_unsafe_angle(angle)
def is_safe_angle(angle):
return angle >= MIN_ALLOWED_ANGLE and angle <= MAX_ALLOWED_ANGLE
def turn_to(angle):
print("Turning to angle:", angle)
def report_unsafe_angle(angle):
print("Unsafe angle:", angle)
turn_telescope(angle=44)
```
%% Cell type:markdown id:02b69029-abb4-417e-8258-46e01502e971 tags:
## How to solve problems with programming
Breaking up and composing
In one small sentence its about breaking up the problem into pieces that can be solved and then composing the small solutions to bigger solutions until the main problem is solved. Easy right? Not really.
Some problems can be solved by connecting existing solutions in libraries together. So for example I need to collect all the log files from all the servers running in Dwingeloo. There are libraries that can copy files from machines using SSH. So now we only need to know which servers are running in Dwingeloo. This could be a simple list we hard code. In that case we are almost done with a small loop over a list. We might need to think about when things go wrong. Server could be down. Network could have a glitch. The file might be locked. We could decide to ignore it because we run the script often enough and we don't mind a older file. But maybe we do care and we need to record any issues. Is it part of an automated system or can we report to a human that then can take action?
Some problems are more of the type that does not have a library for it. Then we might need to implement our own algorithm or set of more detailed functions.
Lets have a look at a relative simple problem of converting a string representing a binary number into a string that represents a hexadecimal number. We allow negative numbers. We raise an exception on empty strings.
https://github.com/TheAlgorithms/Python/blob/master/conversions/binary_to_hexadecimal.py
%% Cell type:code id:ce80b7da-75e3-42e1-a28e-9405a54094c0 tags:
``` python
def bin_to_hexadecimal(binary_str):
BITS_TO_HEX = {
"0000": "0",
"0001": "1",
"0010": "2",
"0011": "3",
"0100": "4",
"0101": "5",
"0110": "6",
"0111": "7",
"1000": "8",
"1001": "9",
"1010": "a",
"1011": "b",
"1100": "c",
"1101": "d",
"1110": "e",
"1111": "f",
}
# Sanitising parameter
binary_str = str(binary_str).strip()
# Exceptions
if not binary_str:
raise ValueError("Empty string was passed to the function")
is_negative = binary_str[0] == "-"
if is_negative:
binary_str = binary_str[1:]
if not set(binary_str) == {'0', '1'}:
raise ValueError("Non-binary value was passed to the function")
binary_str = (
"0" * (4 * (len(binary_str) // 4 + 1) - len(binary_str)) + binary_str
)
hexadecimal = []
for x in range(0, len(binary_str), 4):
hexadecimal.append(BITS_TO_HEX[binary_str[x : x + 4]])
hexadecimal_str = "0x" + "".join(hexadecimal)
if is_negative:
hexadecimal_str = "-" + hexadecimal_str
return hexadecimal_str
bin_to_hexadecimal(input("Provide a binary number:"))
```
%% Cell type:markdown id:43832b3a-2b0d-40d8-bb27-38c97b0b289c tags:
## Your are now a programmer
Thanks for joining the course. You now have learned all the basics of programming. There are many more concepts to learn, but you can now consider yourself a programmer. Go out and automate your life and please share your knowledge and experience. You could use the blog feature of confluence to share or use what ever platform you have access to.
%% Cell type:markdown id:c8f1f558-e241-49bc-a3de-11b9b1552cde tags:
## Further reading
* https://en.wikipedia.org/wiki/Computer_programming
* https://python.org
* Book - Automate the boring stuff with python : https://automatetheboringstuff.com/#toc
* Coding style - Pep8 : https://www.python.org/dev/peps/pep-0008/
## Community
* Slack #learn-python
* Slack #cop-programming
* Slack #software-development
* Slack #webdev
* Reddit /r/programming
* Reddit /r/learnprogramming
* Reddit /r/python
* Reddit /r/AskProgramming
* Reddit /r/learnpython
* Reddit /r/dailyprogrammer/
%% Cell type:markdown id:cb10d0e1-165c-4025-926b-0fac27423f75 tags:
# Bonus: Using files
%% Cell type:markdown id:8642ab98-424f-4edb-9463-a40ba9e428f0 tags:
# Bonus: Using libraries
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment