Unterschiede
Hier werden die Unterschiede zwischen zwei Versionen der Seite angezeigt.
Beide Seiten, vorherige Überarbeitung Vorherige Überarbeitung Nächste Überarbeitung | Vorherige Überarbeitung | ||
talit:python_basics [2019-12-23 11:19] – [Types] sca | talit:python_basics [2020-02-09 21:42] (aktuell) – sca | ||
---|---|---|---|
Zeile 9: | Zeile 9: | ||
Programming requires a lot of practice! | Programming requires a lot of practice! | ||
- | For each section, take your time to play around and, very importantly, make mistakes, produce error messages and try to understand and solve the errors. | + | For each section, take your time to play around and, this is quite important, make mistakes, produce error messages and try to understand and solve them. |
Some subsections contain questions you are supposed to answer. | Some subsections contain questions you are supposed to answer. | ||
Zeile 18: | Zeile 18: | ||
Python knows many different types, such as | Python knows many different types, such as | ||
- | * string: `'' | + | * string: `"Hello World"` |
* integer: `-7` | * integer: `-7` | ||
* float: `3.14159` | * float: `3.14159` | ||
Zeile 33: | Zeile 33: | ||
You can declare a string by just assigning some text in quotes to a variable. | You can declare a string by just assigning some text in quotes to a variable. | ||
Let's consider the following example | Let's consider the following example | ||
- | ```python | + | < |
- | s = '' | + | s = "Hello World" |
print(s) | print(s) | ||
- | ``` | + | </ |
- | The first line just assigns the string `'' | + | The first line just assigns the string `"Hello World"` to the variable `s`. |
- | %Python figures out itself that you assign a string since you're using quotes. | + | Python figures out itself that you assign a string since you're using quotes. |
If you run the code with this line only, nothing will happen. | If you run the code with this line only, nothing will happen. | ||
However, the second line tells your computer to print the value of the variable `s` to the screen. The output is | However, the second line tells your computer to print the value of the variable `s` to the screen. The output is | ||
- | ```bash | + | < |
Hello World | Hello World | ||
- | ``` | + | </ |
- | To define a string, you have to use quotation marks, either use single `'` or double `'' | + | To define a string, you have to use quotation marks, either use single `'` or double `"` quotes. |
- | You see that Python is quite smart: Since `'' | + | You see that Python is quite smart: Since `"Hello World"` is a string, Python realizes that also `s` must be a string. This is different in many other programming languages. |
To check the type of a variable, just type `print(type(name_of_the_variable))`, | To check the type of a variable, just type `print(type(name_of_the_variable))`, | ||
- | ```python | + | < |
- | s = '' | + | s = "Hello World" |
print(type(s)) | print(type(s)) | ||
- | ``` | + | </ |
the output is | the output is | ||
- | ```bash | + | < |
<class ' | <class ' | ||
- | ``` | + | </ |
- | Note that you can also write a number as a string, e.g., `{s = ' | + | Note that you can also write a number as a string, e.g., `s = ' |
However, `s` will be treated as text and not as a number, therefore, you cannot do any calculations with it. | However, `s` will be treated as text and not as a number, therefore, you cannot do any calculations with it. | ||
- | Also, you can use variables with more than one character, e.g., `mystring = '' | + | Also, you can use variables with more than one character, e.g., `mystring = "Hello World"`, but you are not allowed to use blanks in variable names. |
- | You can add {\bf comments} to your code using the symbol `#`: | + | You can add **comments** to your code using the symbol `#`: |
In a line of code, everything that follows the hashtag symbol will be ignored when running. | In a line of code, everything that follows the hashtag symbol will be ignored when running. | ||
So if you run | So if you run | ||
- | ```python | + | < |
- | s = '' | + | s = "Hello World" |
#print(s) | #print(s) | ||
- | ``` | + | </ |
the second line will be ignored and nothing will be printed to the screen. | the second line will be ignored and nothing will be printed to the screen. | ||
The same way, you can add explanations to your code that help you and others to understand your code. | The same way, you can add explanations to your code that help you and others to understand your code. | ||
This is strongly recommended, | This is strongly recommended, | ||
If you have multi-line comments, you can use | If you have multi-line comments, you can use | ||
- | ```python | + | < |
""" | """ | ||
this | this | ||
Zeile 80: | Zeile 80: | ||
comment | comment | ||
""" | """ | ||
- | ``` | + | </ |
There are many operations to manipulate strings, like cutting strings, appending two strings, read off individual letters and so on. | There are many operations to manipulate strings, like cutting strings, appending two strings, read off individual letters and so on. | ||
Two equivalent methods of composing strings are | Two equivalent methods of composing strings are | ||
- | ```python | + | < |
- | s1 = '' | + | s1 = "I like "+"chocolate"+" |
- | s2 = '' | + | s2 = "I like {} and {}!".format("chocolate","cheese") |
- | ``` | + | </ |
The two strings `s1` and `s2` are identical. | The two strings `s1` and `s2` are identical. | ||
Zeile 93: | Zeile 93: | ||
1. Can you use numbers or special characters like `?, | 1. Can you use numbers or special characters like `?, | ||
- | <!-- You can even use numbers in variable names, as long as they are not in the beginning, e.g., `mystring13 = '' | ||
- | But you can NOT use special characters in variable names | ||
- | --> | ||
2. How can you add a line break to a string? | 2. How can you add a line break to a string? | ||
- | <!-- % mystring = '' | ||
3. Is Python case-sensitive? | 3. Is Python case-sensitive? | ||
4. Given a (long enough) string `s`, what do the commands | 4. Given a (long enough) string `s`, what do the commands | ||
`s[2:5], s[:5], s[5:]` mean? | `s[2:5], s[:5], s[5:]` mean? | ||
- | 5. Define some variables that contain information about you, like: `name='' | + | 5. Define some variables that contain information about you, like: `name="Fritzli Mueller",age="45", |
and so on. Then print your personal details in a handful of complete sentences to the screen. Use the variables defined above to fill in the details. | and so on. Then print your personal details in a handful of complete sentences to the screen. Use the variables defined above to fill in the details. | ||
- | %--------------------------------- | ||
## Integers & floats | ## Integers & floats | ||
- | \label{sec integers and floats} | ||
Next, let's have a look at numbers, in particular integers and floats. | Next, let's have a look at numbers, in particular integers and floats. | ||
Let us do some simple calculations. | Let us do some simple calculations. | ||
- | We can assign the {\bf integer} $5$ to the variable `a` by typing | + | We can assign the **integer** $5$ to the variable `a` by typing |
- | ```python | + | < |
a = 5 | a = 5 | ||
- | ``` | + | </ |
Note that we don't use any quotes here. If we would, `a` would be a string. | Note that we don't use any quotes here. If we would, `a` would be a string. | ||
To check that `a` is indeed an integer (short: int), run `print(type(a))`. | To check that `a` is indeed an integer (short: int), run `print(type(a))`. | ||
Now we can do some simple calculations | Now we can do some simple calculations | ||
- | ```python | + | < |
a = 7 | a = 7 | ||
b = 4 | b = 4 | ||
Zeile 127: | Zeile 121: | ||
print(d) | print(d) | ||
print(3*a+c-4) | print(3*a+c-4) | ||
- | ``` | + | </ |
outputting | outputting | ||
- | ```bash | + | < |
3 | 3 | ||
84 | 84 | ||
20 | 20 | ||
- | ``` | + | </ |
- | {\bf Floats} are decimal numbers and are declared by | + | |
- | ```python | + | **Floats** are decimal numbers and are declared by |
+ | < | ||
b = 5. | b = 5. | ||
c = 3.14159 | c = 3.14159 | ||
- | ``` | + | </ |
The basic operations work the same as with integers. | The basic operations work the same as with integers. | ||
Note that as soon as you add a decimal point, the number is a float. | Note that as soon as you add a decimal point, the number is a float. | ||
Zeile 146: | Zeile 141: | ||
It is worth mentioning the different kinds of division by means of examples. | It is worth mentioning the different kinds of division by means of examples. | ||
- | ```python | + | < |
print(7/4) | print(7/4) | ||
print(7./4) | print(7./4) | ||
print(7/4.) | print(7/4.) | ||
print(7./ | print(7./ | ||
- | ``` | + | </ |
This is the normal division and all four statements give exactly the same result $1.75$ - a float. | This is the normal division and all four statements give exactly the same result $1.75$ - a float. | ||
Python can also do division with remainder. For example, we have the divisions | Python can also do division with remainder. For example, we have the divisions | ||
- | ```python | + | < |
print(13// | print(13// | ||
print(13%4) | print(13%4) | ||
- | ``` | + | </ |
with output | with output | ||
- | ```bash | + | < |
3 | 3 | ||
1 | 1 | ||
- | ``` | + | </ |
Note that $13 = 4 \cdot 3 + 1$. | Note that $13 = 4 \cdot 3 + 1$. | ||
This means that the former operation is the integer division the latter operation gives the remainder of the division. | This means that the former operation is the integer division the latter operation gives the remainder of the division. | ||
Zeile 170: | Zeile 165: | ||
A specialty of programming is the following: | A specialty of programming is the following: | ||
- | ```python | + | < |
a = 4 | a = 4 | ||
print(a) | print(a) | ||
a = a + 3 | a = a + 3 | ||
print(a) | print(a) | ||
- | ``` | + | </ |
The output is | The output is | ||
- | ```bash | + | < |
4 | 4 | ||
7 | 7 | ||
- | ``` | + | </ |
In the first line, we assign the value $4$ to the variable `a`. | In the first line, we assign the value $4$ to the variable `a`. | ||
Then, in line 3, we use the value of `a` to assign a new value for `a`. | Then, in line 3, we use the value of `a` to assign a new value for `a`. | ||
Zeile 186: | Zeile 181: | ||
As you have (hopefully) noticed, we do something (`a = a + 3`) that looks mathematically wrong, since obviously $4 \neq 4 + 3$! | As you have (hopefully) noticed, we do something (`a = a + 3`) that looks mathematically wrong, since obviously $4 \neq 4 + 3$! | ||
- | Notice that in Python, the symbol `=` *is not the equality sign you would have in an equation*. It can rather be compared to the symbol $:=$ used in definitions: | + | Notice that in Python, the symbol `=` *is not the equality sign you would have in an equation*. It can rather be compared to the symbol $:=$ used in mathematical |
The equal sign in an equation is given by `==`, which will be discussed later on. | The equal sign in an equation is given by `==`, which will be discussed later on. | ||
Zeile 210: | Zeile 205: | ||
A list is (not very surprisingly) a list of elements. For example | A list is (not very surprisingly) a list of elements. For example | ||
- | ```python | + | < |
- | mylist = [-4.13,'' | + | mylist = [-4.13,"red",3,78,3,"I like chocolate",[6,7,8]] |
- | ``` | + | </ |
As you can see, it is not a problem to have elements of different types and it is even possible to have an element of a list that is a list itself! Also, you can have elements that appear multiple times. | As you can see, it is not a problem to have elements of different types and it is even possible to have an element of a list that is a list itself! Also, you can have elements that appear multiple times. | ||
Zeile 218: | Zeile 213: | ||
The list in our example has 7 elements. They are labeled according to their position, **starting at 0!** | The list in our example has 7 elements. They are labeled according to their position, **starting at 0!** | ||
I.e., the 0th element is `-4.13`, the 1st element is `" | I.e., the 0th element is `-4.13`, the 1st element is `" | ||
- | ```python | + | < |
- | mylist = [-4.13,'' | + | mylist = [-4.13,"red",3,78,3,"I like chocolate",[6,7,8]] |
print(mylist) | print(mylist) | ||
print(mylist[0]) | print(mylist[0]) | ||
print(mylist[1]) | print(mylist[1]) | ||
print(mylist[6]) | print(mylist[6]) | ||
- | ``` | + | </ |
This can be a bit confusing: **Python starts counting at 0!** | This can be a bit confusing: **Python starts counting at 0!** | ||
Also, you can read the elements of a list starting at the end by `mylist[-1]` and so on. | Also, you can read the elements of a list starting at the end by `mylist[-1]` and so on. | ||
It is often useful to initialize an empty list and add (append) elements successively: | It is often useful to initialize an empty list and add (append) elements successively: | ||
- | ```python | + | < |
mylist = [] | mylist = [] | ||
mylist.append(3) | mylist.append(3) | ||
mylist.append(7) | mylist.append(7) | ||
print(mylist) | print(mylist) | ||
- | ``` | + | </ |
This gives a list containing two elements: | This gives a list containing two elements: | ||
- | ```bash | + | < |
[3, 7] | [3, 7] | ||
- | ``` | + | </ |
The length (number of elements) of a list can be determined by | The length (number of elements) of a list can be determined by | ||
- | ```python | + | < |
A = [3, | A = [3, | ||
print(len(A)) | print(len(A)) | ||
- | ``` | + | </ |
which outputs the value `4`. | which outputs the value `4`. | ||
Zeile 257: | Zeile 252: | ||
We want to define a very simple (and not very useful) function called *myaddition* that takes any two numbers and returns the sum of these two numbers. | We want to define a very simple (and not very useful) function called *myaddition* that takes any two numbers and returns the sum of these two numbers. | ||
We can define this function by | We can define this function by | ||
- | ```python | + | < |
def myaddition(a, | def myaddition(a, | ||
- | c = a + b | + | |
- | return(c) | + | return(c) |
- | ``` | + | </ |
Let us go through this step by step. | Let us go through this step by step. | ||
Zeile 282: | Zeile 277: | ||
Simple functions can equivalently be defined as follows: | Simple functions can equivalently be defined as follows: | ||
- | ```python | + | < |
myaddition = lambda a,b: a+b | myaddition = lambda a,b: a+b | ||
- | ``` | + | </ |
This definition and the definition in the beginning of this section using the `def` statement are equivalent. | This definition and the definition in the beginning of this section using the `def` statement are equivalent. | ||
Zeile 294: | Zeile 289: | ||
- | %--------------------------------- | ||
- | # Conditions | + | # Conditions & Booleans |
We can check if one or multiple conditions are satisfied. | We can check if one or multiple conditions are satisfied. | ||
Zeile 302: | Zeile 296: | ||
For example, we can check whether or not a variable has a certain value: | For example, we can check whether or not a variable has a certain value: | ||
- | ```python | + | < |
a = 5 | a = 5 | ||
print(a==3) | print(a==3) | ||
print(a==5) | print(a==5) | ||
- | ``` | + | </ |
Output: | Output: | ||
- | ```bash | + | < |
False | False | ||
True | True | ||
- | ``` | + | </ |
Here, we use a double equal sign `==`. It compares the left and the right side and takes the value `True` if they are the same and `False` otherwise. | Here, we use a double equal sign `==`. It compares the left and the right side and takes the value `True` if they are the same and `False` otherwise. | ||
- | Remember that the symbols `=` and `==` are fundamentally different, as explained above in Sec. \ref{sec integers | + | Remember that the symbols `=` and `==` are fundamentally different: While the `==` symbol corresponds to $=$ in a mathematical equation |
- | <!-- %Note that, in contrast, the single-equal sign {\codetxt | + | |
You can assign Boolean values to variables, e.g.: | You can assign Boolean values to variables, e.g.: | ||
- | ```python | + | < |
a = 5 | a = 5 | ||
b = a == 3 | b = a == 3 | ||
Zeile 323: | Zeile 316: | ||
print(type(b)) | print(type(b)) | ||
print(b == False) | print(b == False) | ||
- | ``` | + | </ |
Output: | Output: | ||
- | ```bash | + | < |
False | False | ||
<class ' | <class ' | ||
True | True | ||
- | ``` | + | </ |
In the second line, we assign the Boolean value `False` (since $5 \neq 3$) to the variable `b`. | In the second line, we assign the Boolean value `False` (since $5 \neq 3$) to the variable `b`. | ||
What happens in line 5? | What happens in line 5? | ||
Besides checking for equality, we can, for example, check if the value on the left side is larger than the value on the right side. | Besides checking for equality, we can, for example, check if the value on the left side is larger than the value on the right side. | ||
- | Some important conditions are | + | Some important conditions are: |
- | \bit | + | |
- | \item {\codetxt | + | * `a == b`: a and b are equal |
- | \item {\codetxt | + | * `a > b`: a is larger b (similarly |
- | \item {\codetxt | + | * `a >= b`: a is larger equal b (similarly |
- | \item {\codetxt | + | * `a != b`: a and b are not equal |
- | \item {\codetxt | + | * `a in A`: a is element of list A |
- | \item {\codetxt | + | * `a not in A`: a is not element of list A |
- | \eit | + | |
- | %--------------------------------- | ||
# If statements | # If statements | ||
- | In an `if' | + | In an `if` statement, the action depends on conditions. |
Let's say we are given some number $a$ and want to determine its absolute value. It is given by $a$ if $a \geq 0$ and by $-a$ if $a < 0$. | Let's say we are given some number $a$ and want to determine its absolute value. It is given by $a$ if $a \geq 0$ and by $-a$ if $a < 0$. | ||
We can realize this by | We can realize this by | ||
- | ```python | + | < |
a = -8 | a = -8 | ||
- | + | | |
if a < 0: | if a < 0: | ||
- | print(-a) | + | |
else: | else: | ||
- | print(a) | + | |
- | ``` | + | </ |
In the first line, we just choose some number. | In the first line, we just choose some number. | ||
Feel free to play around with its value. | Feel free to play around with its value. | ||
- | In line 3, the `if' | + | In line 3, the `if` statement begins. |
- | It starts with {\codetxt | + | It starts with `if` and is followed by a condition, here `a < 0`, and a mandatory colon. |
- | If the condition is {\codetxt | + | If the condition is `True` (satisfied), |
- | If the condition is {\codetxt | + | If the condition is `False` (not satisfied), it jumps to `else:` and runs what is written there: |
Also, here it is important to do the indentation correctly. | Also, here it is important to do the indentation correctly. | ||
- | If there are more than two possibilities, | + | If there are more than two possibilities, |
- | ```python | + | < |
a = 4. | a = 4. | ||
- | + | | |
if a > 7 : | if a > 7 : | ||
- | print('' | + | |
elif a >= 0 and a <= 7: | elif a >= 0 and a <= 7: | ||
- | print('' | + | |
else: | else: | ||
- | print('' | + | |
- | ``` | + | </ |
As you can see, a condition can consist of multiple sub-conditions. | As you can see, a condition can consist of multiple sub-conditions. | ||
- | These can be connected, e.g., using {\codetxt | + | These can be connected, e.g., using `and` or `or`: |
- | \bit | + | |
- | \item {\codetxt condition1 and condition2}: | + | |
- | \item {\codetxt condition1 or condition2}: | + | |
- | \eit | + | |
+ | * `condition1 and condition2`: | ||
+ | * `condition1 or condition2`: | ||
- | {\bf Questions:} | ||
- | \ben | ||
- | \item Define a function `myabs(x)' | ||
- | \item How do indentations work in nested if statements? Play around with if statements inside an if statement. | ||
- | \een | ||
- | %--------------------------------- | + | *Questions: |
+ | |||
+ | * Define a function `myabs(x)` that takes a number x as an argument and returns the absolute value of this number. | ||
+ | * How do indentations work in nested if statements? Play around with if statements inside an if statement. | ||
# Loops | # Loops | ||
Zeile 399: | Zeile 388: | ||
If you want to repeat an action several times, you can use loop statements. | If you want to repeat an action several times, you can use loop statements. | ||
- | First, let us discuss a {\bf for-loop}. A typical example is | + | First, let us discuss a *for-loop*. A typical example is |
- | ```python | + | |
+ | < | ||
for i in range(4): | for i in range(4): | ||
- | print(i) | + | |
- | ``` | + | </ |
which outputs the numbers | which outputs the numbers | ||
- | ```bash | + | |
+ | < | ||
0 | 0 | ||
1 | 1 | ||
2 | 2 | ||
3 | 3 | ||
- | ``` | + | </ |
This for-loop runs through all indices $i=0, | This for-loop runs through all indices $i=0, | ||
First, it runs the code that follows for $i=0$, then for $i=1$, then for $i=2$, and finally for $i=3$; thus $4$ times in total. | First, it runs the code that follows for $i=0$, then for $i=1$, then for $i=2$, and finally for $i=3$; thus $4$ times in total. | ||
Again, notice that Python starts counting at $0$! | Again, notice that Python starts counting at $0$! | ||
- | Second, we discuss the {\bf while-loop}. It repeats a piece of code as long as a condition is satisfied. | + | Second, we discuss the **while-loop**. It repeats a piece of code as long as a condition is satisfied. |
- | Careful: If you have a bug in your code and the condition is always true, you have an `infinite loop': the code will never stop running and you will have to kill the process manually. | + | Careful: If you have a bug in your code and the condition is always true, you have an **infinite loop**: the code will never stop running and you will have to kill the process manually. |
A simple example of a while-loop is: | A simple example of a while-loop is: | ||
- | ```python | + | < |
i = 0 | i = 0 | ||
- | + | | |
while i < 4: | while i < 4: | ||
- | print(i) | + | |
- | i = i+1 | + | i = i+1 |
- | ``` | + | </ |
This piece of code has exactly the same output as the for-loop above. | This piece of code has exactly the same output as the for-loop above. | ||
- | In the first line, we set {\codetxt | + | In the first line, we set `i = 0`. |
- | Then, in line 3, we say that we want to run the following code as long as the condition | + | Then, in line 3, we say that we want to run the following code as long as the condition |
In line 4, we print the current value of the index. | In line 4, we print the current value of the index. | ||
Very important is the last line: Here, we increase the value of $i$ by $1$ for the next run. | Very important is the last line: Here, we increase the value of $i$ by $1$ for the next run. | ||
Zeile 434: | Zeile 427: | ||
As soon as this condition is not true anymore, which will be when $i = 4$, the loop will be terminated. | As soon as this condition is not true anymore, which will be when $i = 4$, the loop will be terminated. | ||
- | {\bf Questions:} | + | **Questions:** |
- | \ben | + | |
- | \item What happens to the if-loop if we write {\codetxt range} with two arguments, like {\codetxt range(3, | + | |
- | \item Take the while-loop given in this section and modify it to obtain an infinite loop. You should then kill the process. | + | |
- | \een | + | |
- | + | ||
+ | * What happens to the if-loop if we write `range` with two arguments, like `range(3, | ||
+ | * Take the while-loop given in this section and modify it to obtain an infinite loop. You should then kill the process (CTRL + C). | ||
Zeile 447: | Zeile 436: | ||
There are many additional packages that can be imported. | There are many additional packages that can be imported. | ||
- | For doing math, `numpy' | + | For doing math, `numpy` is particular useful. |
For example, it contains a lot of predefined functions like trigonometric functions. | For example, it contains a lot of predefined functions like trigonometric functions. | ||
Let us do an example | Let us do an example | ||
- | ```python | + | < |
import numpy as np | import numpy as np | ||
- | + | | |
print(np.sin(2)) | print(np.sin(2)) | ||
print(np.pi) | print(np.pi) | ||
- | ``` | + | </ |
- | In the first line, we import the `numpy' | + | In the first line, we import the `numpy` package and give it the short name `np`. Of course, you could use a different name than `np` but this is the common choice. |
- | Each time we call a function (or something else) from numpy, we have to start with `np.', in order for Python to know that it has to look inside the numpy package. This is exactly what we do on line 3: We call the sine function defined in numpy and evaluate it for the argument $2$. In the last line, we print the value of the constant $\pi$. | + | Each time we call a function (or something else) from numpy, we have to start with `np.`, in order for Python to know that it has to look inside the numpy package. This is exactly what we do on line 3: We call the sine function defined in numpy and evaluate it for the argument $2$. In the last line, we print the value of the constant $\pi$. |
- | %Of course, you could use a different name than `np' | + | **Questions:** |
- | + | ||
- | {\bf Questions:} | + | |
\ben | \ben | ||
- | \item From trigonometry, | + | |
- | \item Two very useful functions within numpy are:\\ | + | * Two very useful functions within numpy are:\\ |
- | {\codetxt | + | `np.linspace(a, |
Find out what they do. | Find out what they do. | ||
\een | \een | ||
Zeile 471: | Zeile 458: | ||
# Elapsed time | # Elapsed time | ||
- | \label{sec elapsed time} | ||
If you want to test the efficiency of your code, it is useful to measure the time needed for the calculation: | If you want to test the efficiency of your code, it is useful to measure the time needed for the calculation: | ||
- | ```python | + | < |
import time as time | import time as time | ||
#... write some code here ... | #... write some code here ... | ||
Zeile 483: | Zeile 469: | ||
print(t_elapsed) # print elapsed time | print(t_elapsed) # print elapsed time | ||
#... continue coding here ... | #... continue coding here ... | ||
- | ``` | + | </ |