Python Basics

Abstract

Here we discuss the most important commands in Python (and programming in general). Many snippets of code together with the corresponding output are shown. You should type in all these snippets yourself (type - not just copy-paste!) and try to understand every line.

Programming requires a lot of practice! 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 of these questions can be answered by trial and error, others require an online search.

Types

Python knows many different types, such as

  • string: "Hello World"
  • integer: -7
  • float: 3.14159
  • list: [3,1,-4]
  • bool: True and False

and many more.

Let us have a look at this types one after another.

First, let's have a look at strings. You can declare a string by just assigning some text in quotes to a variable. Let's consider the following example

s = "Hello World"
print(s)

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. 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

Hello World

To define a string, you have to use quotation marks, either use single ' or double " quotes. 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)), in our example

s = "Hello World"
print(type(s))

the output is

<class 'str'>

Note that you can also write a number as a string, e.g., s = '5'. 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 = "Hello World", but you are not allowed to use blanks in variable names.

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. So if you run

s = "Hello World"
#print(s)

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. This is strongly recommended, especially in long and complicated codes! If you have multi-line comments, you can use

"""
this
is
a
multi-line
comment
"""

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

s1 = "I like "+"chocolate"+" and "+"cheese"+"!"
s2 = "I like {} and {}!".format("chocolate","cheese")

The two strings s1 and s2 are identical.

Questions:

  1. Can you use numbers or special characters like ?,!,.,\%,- or _ in variable names? Give it a try!
  2. How can you add a line break to a string?
  3. Is Python case-sensitive?
  4. Given a (long enough) string s, what do the commands s[2:5], s[:5], s[5:] mean?
  5. Define some variables that contain information about you, like: name="Fritzli Mueller",age="45",placeofresidence=...,hobby=...} 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.

\label{sec integers and floats}

Next, let's have a look at numbers, in particular integers and floats. Let us do some simple calculations.

We can assign the integer $5$ to the variable a by typing

a = 5

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)). Now we can do some simple calculations

a = 7
b = 4
c = a - b
d = 3*a*b
print(c)
print(d)
print(3*a+c-4)

outputting

3
84
20

Floats are decimal numbers and are declared by

b = 5.
c = 3.14159

The basic operations work the same as with integers. Note that as soon as you add a decimal point, the number is a float. Also note that even though 5 and 5. are mathematically identical, in programming they are not since they have a different type!

However, Python is (compared to other languages) quite tolerant! You can do calculations where you mix floats and integers without getting in trouble, e.g., print(5+5.).

It is worth mentioning the different kinds of division by means of examples.

print(7/4)
print(7./4)
print(7/4.)
print(7./4.)

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

print(13//4)
print(13%4)

with output

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.

Powers are realized as follows: 7**3 gives the value of $7^3$.

A specialty of programming is the following:

a = 4
print(a)
a = a + 3
print(a)

The output is

4
7

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. After this declaration, a will not have the value $4$ anymore, but $7$.

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 mathematical definitions: It assigns the value on the right to the symbol on the left. The equal sign in an equation is given by ==, which will be discussed later on.

If you're given a string containing a number you can convert it into a number. You can convert the string "3" into an integer int("3") or a float float("3").

Questions:

  1. Is there a difference between 7 and 7.? Explain!
  2. Is there a difference between 7 and "7"? Explain!
  3. You have seen that you can write something like x = x + 5. You can also write statements like: * x += 3 * x -= 6 * x *= 7 * x /= 4
  4. Play around with these statements and find out what they do.
  5. You know how to convert a string into an integer or a float. Figure out how to do it the other way around.

A list is (not very surprisingly) a list of elements. For example

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.

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 "red" and the 6th element is [6,7,8], as you can check by running

mylist = [-4.13,"red",3,78,3,"I like chocolate",[6,7,8]]
print(mylist)
print(mylist[0])
print(mylist[1])
print(mylist[6])

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.

It is often useful to initialize an empty list and add (append) elements successively:

mylist = []
mylist.append(3)
mylist.append(7)
print(mylist)

This gives a list containing two elements:

[3, 7]

The length (number of elements) of a list can be determined by

A = [3,5,12,144]
print(len(A))

which outputs the value 4.

Questions:

  1. What happens if you add two lists? Do lists behave like vectors?
  2. What happens if you multiply a list with some number or if you multiply two lists?
  3. How can you delete individual elements from a list?

Functions

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

def myaddition(a,b):
    c = a + b
    return(c)

Let us go through this step by step. It is mandatory to start with def, followed by the name you want to assign to your function. Then, in parentheses we have the arguments of the function. It is also possible to have no arguments at all, corresponding to empty parentheses. In our example, we have two arguments, called a and b. After the parentheses, it is mandatory to have a :. Then, we can start defining the rules of the function. We define a new variable that is the sum of the two arguments c = a + b and return its value return(c). Note that you don't need to have a return statement in a function.

We can now call our function to add two numbers, say $3$ and $7$, by typing myaddition(3,7). This returns an integer of value $10$, as you can see by typing print(myaddition(3,7)).

Notice the indentation in the definition of our function: Python is very sensitive to indentation and if this is not done properly, you will get an error! If, for example, we remove the indentation in front of either the c or the return statement (or both), we get an error message. Indentations are best done using the tab key on your keyboard.

Optional:

Simple functions can equivalently be defined as follows:

myaddition = lambda a,b: a+b

This definition and the definition in the beginning of this section using the def statement are equivalent.

Also it is important to remark that you need to define a function before you call it!

Questions:

Define a function that takes one list as an argument. Let the list consist of three numbers. The function should return the sum of these three numbers.

Conditions & Booleans

We can check if one or multiple conditions are satisfied. The result of such a check is a Boolean: True or False.

For example, we can check whether or not a variable has a certain value:

a = 5
print(a==3)
print(a==5)

Output:

False
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. Remember that the symbols = and == are fundamentally different: While the == symbol corresponds to $=$ in a mathematical equation and can be considered the normal equal sign, the single-equal sign = assigns the value on the right to the variable on the left. It is similar to the $:=$ symbol used in mathematical definitions.

You can assign Boolean values to variables, e.g.:

a = 5
b = a == 3
print(b)
print(type(b))
print(b == False)

Output:

False
<class 'bool'>
True

In the second line, we assign the Boolean value False (since $5 \neq 3$) to the variable b. 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. Some important conditions are:

  • a == b: a and b are equal
  • a > b: a is larger b (similarly a < b)
  • a >= b: a is larger equal b (similarly a <= b)
  • a != b: a and b are not equal
  • a in A: a is element of list A
    • a not in A: a is not element of list A

If statements

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$. We can realize this by

a = -8
 
if a < 0:
    print(-a)
else:
    print(a)

In the first line, we just choose some number. Feel free to play around with its value. In line 3, the if statement begins. It starts with if and is followed by a condition, here a < 0, and a mandatory colon. If the condition is True (satisfied), i.e., if $a < 0$, it runs the commands that follow, here print(-a). If the condition is False (not satisfied), it jumps to else: and runs what is written there: print(a). Also, here it is important to do the indentation correctly.

If there are more than two possibilities, we can add elif statements as in the following example:

a = 4.
 
if a > 7 :
    print("a > 7")
elif a >= 0 and a <= 7:
    print("a >= 0 and a <= 7")
else:
    print("a < 0")

As you can see, a condition can consist of multiple sub-conditions. These can be connected, e.g., using and or or:

  • condition1 and condition2: is true only if both conditions are true
  • condition1 or condition2: is true if one or both conditions are true

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

If you want to repeat an action several times, you can use loop statements.

First, let us discuss a for-loop. A typical example is

for i in range(4):
    print(i)

which outputs the numbers

0
1
2
3

This for-loop runs through all indices $i=0,1,2,3$. 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$!

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.

A simple example of a while-loop is:

i = 0
 
while i < 4:
    print(i)
    i = i+1

This piece of code has exactly the same output as the for-loop above. 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 i < 4 is true. 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.

As soon as this condition is not true anymore, which will be when $i = 4$, the loop will be terminated.

Questions:

  • What happens to the if-loop if we write range with two arguments, like range(3,7)?
  • Take the while-loop given in this section and modify it to obtain an infinite loop. You should then kill the process (CTRL + C).

Advanced math with numpy

There are many additional packages that can be imported. For doing math, numpy is particular useful. For example, it contains a lot of predefined functions like trigonometric functions. Let us do an example

import numpy as np 
 
print(np.sin(2))
print(np.pi)

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$.

Questions: \ben

  • From trigonometry, you (should) remember the relation $\sin^2x + \cos^2x = 1$, holding for any $x \el \R$. Show explicitly that this relation holds different values for $x$.
  • Two very useful functions within numpy are:

np.linspace(a,b,c) and np.arange(a,b,c)
Find out what they do. \een

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:

import time as time
#... write some code here ...
t_start = time.time() # start measuring time
#... write the code you want to time ...
t_end = time.time() # stop measuring time
t_elapsed = t_end - t_start # take difference
print(t_elapsed) # print elapsed time
#... continue coding here ...
  • talit/python_basics.1581284522.txt.gz
  • Zuletzt geändert: 2020-02-09 21:42
  • von sca