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

Big chunck of the basics are in

parent 539009b2
Branches
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 takes 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 yourney 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 these days you will know how to program in a basic way that will already be helpfull in automating your life. And just with running you can call yourself a runner if you run, you will be a programmer when you program.
%% Cell type:markdown id:785876cb-ef7d-46cf-aa9e-20950b6e8574 tags:
## What is programming?
## 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 perfom certain task. It also has some form of temporary storage (memory). And to be usefull it has some interfaces to the outside world. 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 to solve a problem. If one of taks is missing or performed in a wrong order the program is incorrect. So one has te 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 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 toggeling switches to represent numbers and a nother switch to tell the computer to process that number. Luckely 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 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 we later extended to help with repeating common patterns in the instructions. For example a sequence of code was repeated many times and 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 abandond mere and more, where certain instructions in the programming language resulted in multiple computer instructions. These languages provided abstractions for common patterns. Now the reversal becames very difficult and not guaranteed to be the same as the original.
In this sense programming language provide higher building blocks than the computer is providing. This makes the life of the programmer easier by giving up on some of the flexibily 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 programmin, funtional program, etc. Some programming language work only well with one paradigms where others cater to more.
Usually one gets away with using a general-purpose programming language, but at other times one might need to look into a specialised 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 you might have guessed already.
%% 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 a install packages 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 reproducable code. It can also be used to log your work/experiments.
https://jupyter.org/install
%% Cell type:markdown id:ecf1f80a-3312-4f3c-85c8-6199daad071d tags:
## Python 3 introduction
%% Cell type:markdown id:cf433491-7990-443f-ae1a-3157a09a3c37 tags:
%% Cell type:markdown id:f4e3dffa-63dd-4301-ac18-762be4b55cfc tags:
### Python 2
We used to have python2. It had a long life (20 years), but its no longer supported. You will find a lot of code examples and libraries around. Please don't use it anymore. The operating systems will stop supporting it as well soon. Luckely we still have python3 which is a mature successor (12 years old).
%% 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 coourse, 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 Laucher 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 but 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")
```
%% Output
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 standar 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)
```
%% Output
Help on built-in function print in module builtins:
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
%% 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.
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 alot, especially in the beginning, so lets see how to deal with that.
%% Cell type:code id:0c656ee3-870f-4f51-aad4-4fd2dbf160b6 tags:
%% Cell type:code id:6d99111d-b279-4f22-8862-8c59df632237 tags:
``` python
#!/bin/env python3
print("Hello World")
printer("Hello World")
```
%% Cell type:markdown id:95082acd-7c8b-4138-9189-84af128a0a93 tags:
This program will give a NameError.
%% Cell type:code id:6d99111d-b279-4f22-8862-8c59df632237 tags:
%% Cell type:code id:0c656ee3-870f-4f51-aad4-4fd2dbf160b6 tags:
``` python
#!/bin/env python3
printer("Hello World")
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.
%% 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
%% Cell type:markdown id:4df3af9b-23e2-45c5-82ed-e7deb2b376aa tags:
### Exercise
Try to break your program in more ways.
Try to break your program in the same and more ways.
%% Cell type:markdown id:2d5d509d-2735-4ff0-9417-d2969f991958 tags:
%% Cell type:markdown id:5a83d289-4df8-47b8-8187-e103319f85e2 tags:
## Functions
## 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
```
%% Output
1
%% Cell type:code id:63970c76-b3cc-4baf-9cf3-56e411c5c172 tags:
``` python
#!/bin/env python3
# this is a float
1.1
```
%% Output
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)
```
%% Output
int
%% Cell type:code id:fc018a67-d3b8-4a60-8e06-ce40d4fa1f42 tags:
``` python
type(1.1)
```
%% Output
float
%% Cell type:code id:7a382ce2-76e1-4fc7-8c94-a8301aca22b2 tags:
``` python
type(1+2J)
```
%% Output
complex
%% 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
```
%% Output
3
%% Cell type:code id:bfa6e62e-063c-4f47-b255-709736ba2c15 tags:
``` python
1 - 2
```
%% Output
-1
%% Cell type:code id:7527ea33-fda7-4f7b-b315-149a998f528d tags:
``` python
1 / 2
```
%% Output
0.5
%% Cell type:code id:fffb310a-c899-43be-a6f0-f0187d2321e6 tags:
``` python
1 * 2
```
%% Output
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
```
%% Output
0
%% Cell type:code id:2efad625-5a60-4ffd-828e-8b4a1689cf17 tags:
``` python
1 % 2
```
%% Output
1
%% Cell type:code id:550ed6ac-026c-4c3b-b7f0-12e2cc56d4ae tags:
``` python
2 ** 2
```
%% Output
4
%% 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
```
%% Output
15.8
%% 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 parenthese '(' and ')'.
%% Cell type:code id:a11d00c0-c61d-4cd2-bc9b-0c6ca856cccb tags:
``` python
6 * (3 - 2)
```
%% Output
6
%% 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
%% Cell type:code id:68528cd0-d4c1-4e86-93c1-f5e1d187fc84 tags:
``` python
user_input = input("What is your name?")
print(user_input)
```
%% Output
What is your name? Auke
Auke
%% Cell type:markdown id:65ae8a92-a9cd-4994-b443-0a987cf12c36 tags:
### Scope
%% 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 parenthese. Between the parenthese we can specify parameters if they are required.
We could create long programs without any function created by ourselfs. 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("*******")
```
%% Output
*******
Hello
*******
*******
World
*******
%% 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 prown. I might forgot 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")
```
%% Output
*******
Hello
*******
*******
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 choosen 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")
```
%% Output
*******
Hello
*******
*******
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 alot 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")
```
%% Output
Hi World
Hello World
Yo World
%% 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)
```
%% Output
9
%% 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)
```
%% Output
Lofar
Astron
%% 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)
```
%% Output
Astron
Astron
%% 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)
```
%% Output
Lofar
Lofar
%% 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:
## Numbers and Strings
## 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
#!/bin/env python3
# Double quoted
print("Hello world")
```
%% Output
Hello world
%% Cell type:code id:02fa86ad-deea-4faf-88c6-4c58cc20da4b tags:
``` python
# Single quoted
print('Hello world')
```
%% Output
Hello world
%% Cell type:code id:e5ba08fc-c1f6-480f-b266-5e5588088e42 tags:
``` python
# Tripple double or single quoted
print("""Hello
World""")
print('''Hello
World''')
```
%% Output
Hello
World
Hello
World
%% Cell type:markdown id:2aee0843-6262-4437-9b28-1f7a343353b7 tags:
The tripple 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'")
```
%% Output
Hello 'world'
%% Cell type:code id:3a669e92-3d70-4a6f-a63e-7297dbb2b23b tags:
``` python
print('Hello "world"')
```
%% Output
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\"")
```
%% Output
'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")
```
%% Output
5
%% 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 hirstorical 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]
```
%% Output
'H'
%% Cell type:code id:ea1b0267-a714-4c29-937c-b530ce5f97f6 tags:
``` python
# This gives the last character
"Hello World"[-1]
```
%% Output
'd'
%% 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]
```
%% Output
'el'
%% Cell type:code id:2f218244-ae5a-4116-ac1e-491ae5b3e0c3 tags:
``` python
"Hello World"[-3:-1]
```
%% Output
'rl'
%% 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:]
```
%% Output
'llo World'
%% 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]
```
%% Output
'Hell'
%% 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"[:]
```
%% Output
'Hello World'
%% Cell type:markdown id:da426233-05e1-4b6c-a74d-d8e8221862d9 tags:
### Excercise
Get familiar with indexing and slices.
%% Cell type:markdown id:13062210-3974-4d3c-ad6e-488cb08e632b tags:
## Objects intermezzo
"Hello world"
Eventhough 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()
```
%% Output
'HELLO'
%% Cell type:markdown id:0ce2f5d1-4e21-4a51-bb47-6a7deed00cb5 tags:
And properties are data on an object and are used byt 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)
```
%% Output
3.0
1.0
%% 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 attibutes of an object:
%% Cell type:code id:600391b4-007b-4ae0-8548-0ee3debeccdd tags:
``` python
help(dir)
```
%% Output
Help on built-in function dir in module builtins:
dir(...)
dir([object]) -> list of strings
If called without an argument, return the names in the current scope.
Else, return an alphabetized list of names comprising (some of) the attributes
of the given object, and of attributes reachable from it.
If the object supplies a method named __dir__, it will be used; otherwise
the default dir() logic is used and returns:
for a module object: the module's attributes.
for a class object: its attributes, and recursively the attributes
of its bases.
for any other object: its attributes, its class's attributes, and
recursively the attributes of its class's base classes.
%% 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 methodes to make all letters uppercase or lowercase letters:
%% Cell type:code id:1d5f6a49-f49b-45e6-a64c-a925ca4b2814 tags:
``` python
"Hello World".upper()
```
%% Output
'HELLO WORLD'
%% Cell type:code id:f8fcdb48-5544-4d73-86a2-0725d13bdafe tags:
``` python
"Hello World".lower()
```
%% Output
'hello world'
%% 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 sensetivity. 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)
```
%% Output
Hello World
%% Cell type:markdown id:ef7b8b6e-cf56-4e5f-ac49-528f88e1f183 tags:
Another way is to use Formated string literals. This has a mini language on its own so I will only be showing some basic options. We start a formated 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"
```
%% Output
'Hello world'
%% Cell type:markdown id:32d8f383-db80-479a-9aab-20cc430e9739 tags:
%% Cell type:code id:c6cabd8d-6ec8-4504-bc0d-d1b58d0d8c58 tags:
## Basic math
``` 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"
```
%% Output
"Hello World you don't look a day older than 4600000000.0 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"
```
%% Output
"Hello World you don't look a day older than 4.6E+09 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 Formated string literals but its a bit more explicit.
%% Cell type:code id:6dac110d-fe50-4fcc-832c-d2b8524b6191 tags:
``` python
"Hello {}".format("World")
```
%% Output
'Hello World'
%% Cell type:code id:ec76336b-afb9-4a8e-9c80-6a4d41061ada tags:
``` python
"Hello {name}".format(name="World")
```
%% Output
'Hello World'
%% Cell type:code id:8cd4909c-c1f4-4b2b-9016-48e695aa4c78 tags:
``` python
"Hello {}, my name is {}".format("World", "Python")
```
%% Output
'Hello World, my name is 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")
```
%% Output
'Hello World, my name is Python. Have a nice day World.'
%% 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")
```
%% Output
'Hello World, my name is Python. Have a nice day World'
%% 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 formated 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)
```
%% Output
What is your name? Auke
Hello Auke
%% Cell type:markdown id:7c011488-f5dc-4cea-85db-1fa202c2c240 tags:
## Data types
### lists
### dictionaries
### sets
### tuples
%% 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 explanetory.
### If
### While
### For
### Break / Continue
%% Cell type:markdown id:e24b0155-ddec-4363-a111-a9d8b0670fc6 tags:
## Abstraction
%% Cell type:markdown id:02b69029-abb4-417e-8258-46e01502e971 tags:
## How to solve problems with programming
Breaking up and composing
%% 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
## Community
* 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/
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment