## 04. Numbers, Strings, and Dictionaries¶

### Exercise 1¶

In [1]:
4 ** 3  # output is int

Out[1]:
64
In [2]:
2 + 3.4 ** 2  # output is float

Out[2]:
13.559999999999999
In [3]:
(1 + 1j) ** 2  # output is complex

Out[3]:
2j

### Exercise 2¶

In [4]:
# Define string
a = "Hello, egg world!"

# Find position of 'egg' word
pos = a.index('egg')

# Make new string
new_string = a[:pos] + a[pos+4:]

# Print out to check
print(new_string)

Hello, world!


### Exercise 3¶

In [5]:
s = "CAGTACCAAGTGAAAGAT"
s.count("A")

Out[5]:
8
In [6]:
a = [1, 2, 3]
b = [4, 5, 6]
a + b

Out[6]:
[1, 2, 3, 4, 5, 6]

## 05. Booleans, Tuples, and Dictionaries¶

### Exercise 1¶

In [7]:
x = 3.7
(x > 3.4 and x <= 6.6) or x == 2

Out[7]:
True

### Exercise 2¶

In [8]:
words = {}
words['Table'] = 'Tisch'
words['Chair'] = 'Stuhl'
words['Snake'] = 'Schlange'

In [9]:
words['Chair']

Out[9]:
'Stuhl'

## 06. Control Flow¶

### Exercise 1 and 2¶

In [10]:
for i in range(2, 51):  # just to 50 for this example

# Set is_prime 'flag' to initial value
is_prime = True

# Try and divide i by all values between 2 and i-1, and if none of them
# work, then the value is prime.
for j in range(2, i):

# Check if i is divisible by j
if i % j == 0:
is_prime = False
break

if is_prime:
print(i)

2
3
5
7
11
13
17
19
23
29
31
37
41
43
47


There are other ways of doing this, e.g.:

In [11]:
for i in range(2, 51):
for j in range(2, i):
if i % j == 0:
break
else:  # this gets executed if break is not called
print(i)

2
3
5
7
11
13
17
19
23
29
31
37
41
43
47


### Exercise 2¶

In [12]:
a = 0
b = 1
while a < 100000:
print(a)
c = a  # save a to old variable
a = b
b = c + b

0
1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584
4181
6765
10946
17711
28657
46368
75025


Even simpler:

In [13]:
a, b = 0, 1
while a < 100000:
print(a)
a, b = b, a + b

0
1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584
4181
6765
10946
17711
28657
46368
75025


With a list:

In [14]:
fib = [0, 1]
while fib[-1] + fib[-2] < 100000:
fib.append(fib[-1] + fib[-2])
print(fib)

[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025]