Author: christophe@pallier.org

In [ ]:

```
if 2 + 2 == 5:
print("Oops")
else:
print("Fine")
print("2 + 2 = 4")
```

**indentation** rather than delimiters to regroup series of instructions into a block

In [ ]:

```
name = raw_input("What is your name? ")
print("Hello " + name + "!")
```

Remarks:

- '+' as the string concatenation operator
- (in Python3: raw_input -> input)

In [ ]:

```
x = raw_input("Enter a number: ")
if int(x) % 2 == 0: # '%' is the modulo operator
print(x + " is even")
else:
print (x + " is odd")
```

In [ ]:

```
while True:
x = raw_input('Enter a number ("q" to stop)')
if x == 'q':
break # interupts the while loop
if int(x) % 2 == 0: # '%' is the modulo operator
print(x + " is even")
else:
print (x + " is odd")
```

In [ ]:

```
x = 1
while x <= 10:
print(x)
x = x + 1
```

In [ ]:

```
reg1, reg2 = 5, 2
while reg1 > 0:
reg2 += 1
reg1 -= 1
print(reg1, reg2)
```

...

In [ ]:

```
# the elements do not have to be of the same type
a = [3, 4, 'dog']
print(a[0]) # change the index 0 into 1, then 2
```

In [ ]:

```
# you can even embbed lists inside lists
sentence = [['the', 'dog'], [ 'bites', [['the', 'cat']]]]
sentence[1][1]
```

In [ ]:

```
a = [1, 2, 3]
b = a
a[1] = 666
b
```

This is because `a`

and `b`

point to the same memory area!

In [ ]:

```
a = [1, 2, 3]
b = a[:] # makes a copy in memory
a[1] = 666
b
```

In [ ]:

```
a = [1, 2, 3]
b = a
a = [4, 5, 6]
b
```

In [ ]:

```
sum = 0
for i in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
sum = sum + i
print(sum)
```

Remark: we could have used the expression 'for x in range(11)'

...

Remarks:

In [ ]:

```
# python's for has some nifty features
for n, item in enumerate(['alpha', 'beta', 'gamma']):
print n, item
for _ in range(10):
print('All work and no play make Jack a dull boy!')
```

In [ ]:

```
def somme(n):
sum = 0
for i in range(n + 1):
sum = sum + i
return sum
print(somme(10))
print(somme(20))
```

...

In [36]:

```
def is_factor(a, b):
return b % a == 0
print(is_factor(3, 27))
print(is_factor(3, 28))
```

In [ ]:

```
def prod(x):
p = 1
for e in x:
p = p * e
return p
prod([4, 5, 6])
```

In [41]:

```
import turtle
turtle.forward(100)
turtle.left(120)
turtle.forward(100)
turtle.left(120)
turtle.forward(100)
turtle.done()
```

In [ ]:

```
def fact(n):
if n == 0:
return 1
else:
return n * fact(n - 1)
print(fact(10))
```

F(0)=1; F(1)=1; F(n)=F(n-1)+F(n-2)

In [ ]:

```
import random # module importation
n = random.randint(1, 99)
guess = input('Guess a number between 1 and 99 ? ')
while guess != n:
if guess > n:
print('Too large!')
if guess < n:
print('Too Small!')
guess = input('New guess?')
print("Correct!")
```

...

...

...

The input is a a list of instructions, e.g. [['inc',1,1], ['deb',1,0,3], ['end']] (no need for line number)