In [3]:
import typing

def controllableLeibnizPi(stopNow: typing.Callable) -> float:
    pi = 0.0
    sign = 1
    den = 1
    while not stopNow(pi):
        pi = pi + sign*4/den
        sign = sign * -1
        den = den + 2
    print(den)
    return pi

def tastyPi(pi: float) -> bool:
    return pi > 3.1415925 and pi < 3.1415927

print(controllableLeibnizPi(tastyPi))
13021705
3.1415925000000384
In [4]:
for c in "Hello, world!":
    print(c)
H
e
l
l
o
,
 
w
o
r
l
d
!
In [6]:
print("Hello, world!"[1])
print(range(1, 10)[2])
e
3
In [9]:
s = "Hello, world!"
print(len(s))
for i in range(len(s)):
    print(s[i])
13
H
e
l
l
o
,
 
w
o
r
l
d
!
In [10]:
x = "Hello, world!"
x[1] = "u"
<cell>2: error: Unsupported target for indexed assignment ("str")  [index]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [10], in <cell line: 2>()
      1 x = "Hello, world!"
----> 2 x[1] = "u"

TypeError: 'str' object does not support item assignment
In [12]:
x = [2, 4, 6, 0, 1]
print(x[2])
for val in x:
    print(val)
6
2
4
6
0
1
In [13]:
def averageOf(l: list[float]) -> float:
    sum = 0.0
    for val in l:
        sum = sum + val
    return sum / len(l)

print(averageOf([2, 4, 6, 0, 1]))
2.6
In [17]:
def contains(
    haystack: typing.Sequence,
    needle: typing.Any
) -> bool:
    for val in haystack:
        if val == needle:
            return True
    return False

print(contains([2, 4, 6, 0, 1], 6))
print(contains([2, 4, 6, 0, 1], 7))
print(contains("Hello, world!", "e"))
print(contains(range(1, 50), 23))
True
False
True
True
In [18]:
x = [2, 4, 6, 0, 1]
print(x)
x[1] = 8
print(x)
[2, 4, 6, 0, 1]
[2, 8, 6, 0, 1]
In [20]:
def runningAverage(l: list[float]) -> float:
    sum = 0.0
    for idx in range(len(l)):
        sum = sum + l[idx]
        l[idx] = sum / (idx+1)
    return sum / len(l)

x = [2.0, 4, 6, 0, 1]
print(runningAverage(x))
print(x)
2.6
[2.0, 3.0, 4.0, 3.0, 2.6]
In [22]:
for s in ["Excellent", "text", "box"]:
    print("In outer loop, s is", s)
    for c in s:
        print(c)
In outer loop, s is Excellent
E
x
c
e
l
l
e
n
t
In outer loop, s is text
t
e
x
t
In outer loop, s is box
b
o
x
In [24]:
x = [2, 4, 6, 0, 1]
y = x
x[1] = 8
print(y)
for i in y:
    i = 0
print(y)
[2, 8, 6, 0, 1]
[2, 8, 6, 0, 1]
In [26]:
def squareList(l: list[float]) -> None:
    for i in range(len(l)):
        l[i] = l[i]**2
        
x = [2.0, 4, 6, 0, 1]
squareList(x)
print(x)
[4.0, 16, 36, 0, 1]
In [29]:
def removeFactorsOfTwo(l: list[int]) -> None:
    for idx in range(len(l)):
        val = l[idx]
        while val%2 == 0 and val > 1:
            val = val // 2
        l[idx] = val
        
x = [2, 4, 6, 0, 1]
removeFactorsOfTwo(x)
print(x)
[1, 1, 3, 0, 1]