<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">#!/usr/bin/env python
# coding: utf-8

# # Computational Programming with Python
# ### Lecture 1: Lists and elementary plotting
# 
# ### Center for Mathematical Sciences, Lund University
# Lecturer: Claus FÃ¼hrer, Malin Christersson, `Robert KlÃ¶fkorn`, Viktor Linders
# 

# ## This lecture
# 
# - Training exercise discussion
# - Data types and variables
# - Concept: `list`
# - `while` and `for` loops again
# - Elementary plotting

# ## Data types and variables
# 
# ### Numerical data types
# 
# A number is an *integer* (`int`), a *real number* (`float`) or a *complex number* (`complex`).
# 
# The usual operations are
# - `+` and `-` addition and subtraction
# - `*` and `/` multiplication and division
# - `**`power

# In[ ]:


2**(2+2)


# In[ ]:


1j**2


# ### Variables
# 
#  A variable is a reference to an object. One uses the assignment operator `=` to assign a value to a variable.

# In[ ]:


my_int = 42
my_float = 3.14
my_float2 = float(3)
print(my_float2)
my_complex = 5+1j
my_sum = my_float+my_complex
print(my_sum)
print(type(my_sum))

my_int2 = int(3.14)
print(my_int2)


# For complex numbers, `j`is a suffix to the imaginary part. The code `5+j` will not work.

# ### Assignment operators
# 
# The equality symbol does not denote an equality but an assignment.
# 
# `a = 5`
# 
# `a = a + 3`
# 
# You can also use a **compound assignment** that adds to the variable:
# 
# `a += 3`
# 
# There are several **compound assignment operators** for arithmetic operations:
# 
# - `+=` `-=`  (addition and substraction)
# - `*=` `/=`  (multiplication and division)
# - `**=` (power or exponentiation)
# - `%=` `//=` (floor division and and modulus operation)

# In[ ]:


a = 5      # assigment 
a = a + 3  # add 
print(a)   
a += 3     # compound assignment (inplace add)
print(a)

a -= 4     # inplace subtraction
print(a) 
a *= 5     # inplace multiply
print(a)


# ### Strings
# 
# Strings are "lists" of characters enclosed by simple or double quotes.
# 
# `str1 = '"Eureka" he shouted.'`
# 
# `str2 = "He had found what is now known as Archimedes' principle."`

# ### Multiple lines
# 
# You may also use triple quotes for strings including multiple lines:

# In[ ]:


str3 = """This is
a long,
long string."""
print(str3)


# ### Boolean variables
# 
# We can assign Boolean values to variables in different ways.

# In[ ]:


a = True
b = 0 &lt; 3 &lt; 6
c = (3*15 == 10)
print("b =", b)
print("c =", c)
print(type(c))


# ## Concept: Lists
# 
# A Python list is an ordered list of objects, enclosed in __square brackets__. 
# 
# One accesses elements of a list using zero-based indices inside __square brackets__.

# ### List examples

# In[ ]:


L1 = [1, 2]
print(L1[0])
print(L1[1])
print(type(L1))
# print(L1[2]) # raises IndexError


# In[ ]:


L2 = ['a', 1, [3, 4]] 
print(L2[0])
print(L2[2])
print(L2[2][0])


# ### Negative indices

# In[ ]:


L2 = ['a', 1, [3, 4]] 
print(L2[-1]) # last element
print(L2[-2]) # second last element
# print(L2[-4])


# ### List utilities &amp;hyphen;  `range`
# 
# `range(n)` can be used to fill a list with $n$ elements starting with zero.

# In[ ]:


L3 = list(range(2,5))
print(L3)


# ### The `range` function
# 
# You can use:
# 
# `range(stop)` a sequence of integers &amp;ge; `0` and &amp;lt; `stop`
# 
# `range(start, stop)` a sequence of integers &amp;ge; `start` and &amp;lt; `stop`
# 
# `range(start, stop, step)` a sequence of integers that starts with `start` and then increases by `step` as long as the number is &amp;lt; `stop`.  
# 
# **Example**: Show all non-negative multiples of 15 that are less than 100.

# In[ ]:


for i in range(0, 100, 15):
    print(i)


# ### List utilities &amp;hyphen;  `len`
# 
# The function `len(L)` gives the the length of a list:

# In[ ]:


L4 = ["Stockholm", "Paris", "Berlin"]
L5 = [[0,1], [10, 100, 1000, 10000]]
print(len(L4))
print(len(L5))
print(len(L5[-1]))

print(len(['a', 'b', 'c', 'd', 'e']))


# ### List utilities &amp;hyphen;  `append`
# 
# Use the method `append` to append an element at the end of the list.

# In[ ]:


L6 = ['a', 'b', 'c']
print(L6[-1])
print(len(L6))
L6.append('d')
print(L6[-1])
print(len(L6))


# ### List comprehension
# 
# A convenient way to build up lists is to use the `list comprehension` construct, possibly with a conditional inside.
# 
# #### Definition
# The syntax of  a list comprehension is
# 
# `[&lt;expr&gt; for &lt;variable&gt; in &lt;list&gt;]`
# 
# Example:
# 

# In[ ]:


L1 = [2, 3, 10, 1, 5]
L2 = [x*2 for x in L1]
L3 = [x*2 for x in L1 if 4 &lt; x &lt;= 10]

print(L1)
print(L2)
print(L3)


# ### List comprehension in mathematics
# 
# #### Mathematical notation
# This is very close to the mathematical notation for sets. Compare:
# 
# $$ L_2 = \{2x;\ x\in L_1\} $$
# 
# with
# 
# `L2 = [2*x for x in L1]`
# 

# ### Operations on lists
# 
# Adding two lists *concatenates* (sammanfogar) them:

# In[ ]:


L1 = [1, 2]
L2 = [2, 4]
L3 = L1 + L2
print(L3)


# ### More operations on lists
# 
# Logically, multiplying a list with an integer concatenates the
# list with itself several times: `n*L` is equivalent to
# 
# $\underbrace{L+L+\cdots+L}_{n \text{ times}}$

# In[ ]:


L = [1, 2]
print(3*L)


# ## Some more functions
# 
# Given a list `lst`:
# 
# - `sum(lst)`
# - `max(lst)`
# - `min(lst)`

# In[ ]:


L = [4, 9, -1, 2]
print("The sum is", sum(L))
print("The minimum value is", min(L))
print("The maximum value is", max(L))

L = ['ahfg', 'Berlin', 'check', [0]]
print(min(L))


# ## Some more methods
# 
# Given a list `lst`:
# 
# - `lst.reverse()`
# - `lst.sort()`
# - `lst.sort(reverse=True|False, key=myFunc)`
# 

# In[ ]:


L = [4, 9, -1, 2]
print("L =", L)
L.reverse()
print("L =", L)
L.sort()
print("L =", L)


# ## for loops
# 
# A `for loop` allows to loop through a list using an index variable. This variable takes succesively the values of the elements in the list.
# 
# Example:

# In[ ]:


L = [1, 2, 10] 
for s in L:
    print(s * 2)


# ### Repeating a task
# 
# One typical use of the for loop is to repeat a certain task a fixed number of times:
# 

# In[ ]:


# a function (will be discussed in the next lecture)
def do_something(i):
    print(i)
    
n = 15
for i in range(n):
    do_something(i) # this gets executed n times


# ### Indentation
# 
# The part to be repeated in the for loop has to be properly **indented**.

# In[ ]:


for elt in my_list:
    do_something()
    something_else()
    etc
print("loop finished") # outside of the for loop


# In contrast to other programming languages, the indentation in Python is **mandatory**.
# 
# Many other kinds of Python structures also have to be indented and this will be covered when introduced.

# ## The full `for` statement &amp;hyphen; `break`
# 
# `break` gets out of the for loop before all elements of the list are used.
# 
# In the following example we possibly don't use all values of the list `x_values`.

# In[ ]:


x_values=[0,2,3,4,5]
threshold=3.5
for x in x_values:
    if x &gt; threshold:
        break
    print(x)


# ## The full `while` statement &amp;hyphen; `break`
# 
# `break` gets out of the `while` loop idependently of the while condition.

# In[ ]:


i = 0
while i &lt; 20: 
    i += 1 
    if i &gt; 10:
        break
       
print(i)


# ## The full `for` statement &amp;hyphen; `else`
# 
# `else` checks if the loop was not *broken* by the `break` keyword.

# In[ ]:


threshold=6
for x in x_values:
    if x &gt; threshold:
        break
    print(x)
else:
    print("all the x are below the threshold")


# If we did not break, the else-block is executed.

# ## The full `while` statement &amp;hyphen; `else`
# 
# else checks if the `while` loop was not broken by the break keyword.

# In[ ]:


i = 0
while i &lt; 20: 
    i += 1 
    if i &gt; 30:
        break
else:
    print("while loop finished as expected!")
       
print(i)


# ## Programming example
# 
# How do we calculate 
# 
# $$ \sum_{i=0}^{n}i$$
# 
# using a for loop? using a list? using something else?
# 

# In[ ]:


# 5 min - let's go!
n = 40
L = [i for i in range(0,n+1)]
print(sum(L))

def summation(n):
    return (n + 1 )* n / 2
L = print(summation(n))

print(sum(range(n+1)))


# ## Programming example
# 
# How do we calculate 
# 
# $$ \sum_{i=0}^{n}i$$
# 

# In[ ]:


# for loop
s = 0
for i in range(0,101): # n = 100
    s += i
print(s)


# In[ ]:


# list
L = [i for i in range(0,101)]
print(sum(L))


# In[ ]:


# range
s = sum(range(101))
print(s)


# 
# ## Elementary plotting
# 
# 
# We must first make the central visualization tool in Python available:

# In[ ]:


from matplotlib.pyplot import *
from numpy import *


# Then we generate two lists:

# In[ ]:


x_list = list(range(100))
y_list = [sqrt(x) for x in x_list]


# Then we make a graph:

# In[ ]:


# from above
from matplotlib.pyplot import *
from numpy import *
x_list = list(range(100))
y_list = [sqrt(x) for x in x_list]
# plotting commands 
plot(x_list, y_list, 'o')
title('My first plot')
xlabel('x')
ylabel('Square root of x')
show() # not always needed, but does not hurt

</pre></body></html>