As easy as pi.py

Calculations and loops in python

Motivation

Motivation

for python

for-loops in python operate on so-called iterables, this makes them very versatile

Python provides a lot of iterables. For now we will focus on lists, ranges and strings

for python

1 >>> for elem in range(4):
2 >>>    print(elem)
3 0
4 1
5 2
6 3

Ranges start at 0 and do not include the end

for python

1 >>> fruits= ['apples', 'bananas', 'strawberries']
2 >>> for fruit in fruits:
3 >>>    print(fruit)
4 apples
5 bananas
6 strawberries

for can also iterate over the elements of a list

for python

1 >>> for letter in 'café':
2 >>>    print(letter)
3 c
4 a
5 f
6 é

Strings in python 3 can handle special unicode characters

Strings are also iterables

notepad.exe

Open a text editor and save the content of the next slide in a file called count.py

Make sure that the editor does not add a filename-extension like .txt

count.py

1 #!/usr/bin/env python3
2 
3 for i in range(10):
4     print(i)

cmd.exe

Open a terminal window and use cd to navigate to the directory where you stored count.py

Type python count.py (on Windows) / python3 count.py (on Linux) and hit enter⏎ to execute count.py

Hint: Use the Tab⭾ key to automatically complete directory/file/program names

Division 10

Edit count.py so that it outputs the numbers from 0.0 to 0.9 in steps of 0.1.

0.0
0.1
0.2
0.3
0.4
…

for for

Edit count.py so that its output looks like this example

x   y
0.0 0.4
0.0 0.5
0.0 0.6
0.0 0.7
0.0 0.8
0.0 0.9
0.1 0.0
0.1 0.1

thagoras.py

Python has an exponentiation operator b**e

A square root is an exponentiation by ½

Thus, in python, the distance d between two points in a cartesian coordinate system can be calculated as d= (x**2 + y**2)**0.5

pi.py

Add a variable inside=0 to count.py that is incremented by one whenever (x**2 + y**2) is smaller than 1

At the end of the program print(inside*4/100)

pi.py

Decrease the step size from 0.1 to 0.001

At the end of the program print(inside*4/(1000**2))

Try to recognize the number and find out why it is the result of the calculation