Colab

x = 10


x

10
y= 20
y
x


10
for i in range(10):
    print(i)

0
1
2
3
4
5
6
7
8
9
x = 100


100
print(x)

10
x = [1,2,3]
x.append(4)
x = x* 2
print(x)

[1, 2, 3, 4, 1, 2, 3, 4]
prices = {
    'pizza' : 45,
    'hamburger' : 59,
    'salad' : 33,
    'dessert' : 25,
    'soup' : 30,
    'pie' : 32
}

order = ['pizza', 'pizza', 'salad', 'dessert']


sum = 0
for item in order:
    sum+=prices[item]
print(sum)

148
sum( [prices[item] for item in order] )

148
i=0
while i<8:
    print(2**i)
    i+=1

1
2
4
8
16
32
64
128
for i in range(8):
    print(2**i)

1
2
4
8
16
32
64
128
newlist = []
for i in range(8):
    newitem = 2**i
    newlist.append(newitem)

newprices = { item : prices[item] * 2 for item in prices}
print(newprices)

{'pizza': 90, 'hamburger': 118, 'salad': 66, 'dessert': 50, 'soup': 60, 'pie': 64}
prices.items()

dict_items([('pizza', 45), ('hamburger', 59), ('salad', 33), ('dessert', 25), ('soup', 30), ('pie', 32)])
item = ('pizza', 45)
name = item[0]
price = item[1]

name, price = ('pizza', 45)
print(name, price)

pizza 45
name2, price2 = item
print(name2, price2)

pizza 45
for name, price in prices.items():
     print(name, '-->>', price)
    

newprices = { name : price * 2 for name, price in prices.items()}
print(newprices)

pizza -->> 45
hamburger -->> 59
salad -->> 33
dessert -->> 25
soup -->> 30
pie -->> 32
{'pizza': 90, 'hamburger': 118, 'salad': 66, 'dessert': 50, 'soup': 60, 'pie': 64}
order

['pizza', 'pizza', 'salad', 'dessert']
order[2:]

['salad', 'dessert']
order[:3]

['pizza', 'pizza', 'salad']
order[::-1]

['dessert', 'salad', 'pizza', 'pizza']
x = 10
y = x
x += 1
print(y)

10
x = [1,2,3]
y = x
x += [4]
print(y)

[1, 2, 3, 4]
{
    1 :  []
}

{1: []}
{
    [] : 1
}


    ---------------------------------------------------------------------------

    TypeError                                 Traceback (most recent call last)

    <ipython-input-25-8250d8df6268> in <module>
          1 {
    ----> 2     [] : 1
          3 }


    TypeError: unhashable type: 'list'


2/3

0.6666666666666666
2//3

0
float(2)

2.0
list(range(10))

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
int("42")

42
str(42)

'42'
[]

[]
[]

[]
()

()
(2)

2
(1,2,3)

(1, 2, 3)
(1,2)

(1, 2)
(1,)

(1,)
1,

(1,)
x = 10
y = 'blah'



z = x
x = y
y = x

x, y = y, x
print(x,y)

10 blah
order

['pizza', 'pizza', 'salad', 'dessert']
order[0]


'pizza'
order[1]

'pizza'
order[-1]

'dessert'
order[-2]

'salad'
order[-2 + len(order)]

'salad'
len(order)

4
order[-10]


    ---------------------------------------------------------------------------

    IndexError                                Traceback (most recent call last)

    <ipython-input-59-76e8da1ee12a> in <module>
    ----> 1 order[-10]
    

    IndexError: list index out of range


order[-3:]

['pizza', 'salad', 'dessert']
order

['pizza', 'pizza', 'salad', 'dessert']
'hello ' * 3

'hello hello hello '
[1] * 3

[1, 1, 1]
m = [ [ 0, 0, 0 ] ]* 3

m

[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
m[0][0] = 99
print(m)

[[99, 0, 0], [99, 0, 0], [99, 0, 0]]
x = [1,2,3, 2, 1]
sorted(x)

[1, 1, 2, 2, 3]
x

[1, 2, 3, 2, 1]
x.sort()
print(x)

[1, 1, 2, 2, 3]
fruits = ['watermelon', 'apple', 'grapes', 'melon', 'peach', 'citrus']

sorted(fruits)

['apple', 'grapes', 'melon', 'peach', 'watermelon']
len

<function len(obj, /)>
sorted(fruits, key=len)

['apple', 'melon', 'peach', 'grapes', 'watermelon']
prices = {
    'apple' : 20, 
    'melon' : 7, 
    'peach' : 12,
    'grapes' : 25,
    'watermelon' : 5,
    'citrus' : 5
}

def getprice(fruit):
    return prices[fruit]

sorted(fruits, key=getprice)

['watermelon', 'citrus', 'melon', 'peach', 'apple', 'grapes']
[1] < [2, 2]

True
[2] < [1, 1]

False
[2] < [10,1] 

True
[10, 2, 1000] < [10,100, 0] 

True
int

int
x = int

int = float

int(10)

10.0
type(10)

int
int = type(10)

a = len

a

<function len(obj, /)>
len = 10

len("hello")


    ---------------------------------------------------------------------------

    TypeError                                 Traceback (most recent call last)

    <ipython-input-101-3e2f615008d4> in <module>
    ----> 1 len("hello")
    

    TypeError: 'int' object is not callable


len = print

len("hello")

hello
import math

math

<module 'math' (built-in)>
x = math

x

<module 'math' (built-in)>
del x

len = a

len('hello')

5
a = {"hello"}

a

{'hello'}
a += {'hello', 'world' }


    ---------------------------------------------------------------------------

    TypeError                                 Traceback (most recent call last)

    <ipython-input-114-335b17adbe1a> in <module>
    ----> 1 a += {'hello', 'world' }
    

    TypeError: unsupported operand type(s) for +=: 'set' and 'set'


a = set()
x = """hello"""
a.update({x})
print(a)

{'hello'}
a

{'e', 'h', 'hello', 'l', 'o'}
x = 10

x < 20

True
x == [1,2,3]

False
bool(10)

True
bool(0)

False
bool([0])

True
bool([])

False
result = []

if result :
    print("got results")
else:
    print('failed | empty result | eof | eos')

failed | empty result | eof | eos
bool(result)

False
score = 87
if score > 0 and score < 100:
    print('yes')

yes
if 0<score<100<score**2< 10000:
    print('yes')

yes
x = "hello"
y = "HELLO".lower()
z = "hel" + "lo"
x == y == z == 'moshe'

False
2 in [1,2,3]

True
0 in [1,2,3]

False
fruits

['watermelon', 'apple', 'grapes', 'melon', 'peach', 'citrus']
"melon" in fruits

True
"car" in fruits

False
"car" not in fruits

True
max

<function max>
min

<function min>
sum

<function sum(iterable, start=0, /)>
all

<function all(iterable, /)>
any

<function any(iterable, /)>
all([1, [2], "3"])

True
all([1, [2], "3", 0])

False
all([1, [2], "3", ""])

False
fruits

['watermelon', 'apple', 'grapes', 'melon', 'peach', 'citrus']
prices

{'apple': 20,
 'melon': 7,
 'peach': 12,
 'grapes': 25,
 'watermelon': 5,
 'citrus': 5}
[ { 
    'name' : fruit, 
    'price' : prices[fruit], 
    '+vat' : prices[fruit]*1.17
  } 
    for fruit in fruits]

[{'name': 'watermelon', 'price': 5, '+vat': 5.85},
 {'name': 'apple', 'price': 20, '+vat': 23.4},
 {'name': 'grapes', 'price': 25, '+vat': 29.25},
 {'name': 'melon', 'price': 7, '+vat': 8.19},
 {'name': 'peach', 'price': 12, '+vat': 14.04},
 {'name': 'citrus', 'price': 5, '+vat': 5.85}]
[ [fruit, prices[fruit]] for fruit in fruits if prices[fruit] <= 10]

[['watermelon', 5], ['melon', 7], ['citrus', 5]]
def make_price_pair(fruit):
    return [fruit, prices[fruit]]

make_price_pair('melon')

['melon', 7]
list(map(make_price_pair, fruits))

[['watermelon', 5],
 ['apple', 20],
 ['grapes', 25],
 ['melon', 7],
 ['peach', 12],
 ['citrus', 5]]
[ [fruit, prices[fruit]] for fruit in fruits ]

[['watermelon', 5],
 ['apple', 20],
 ['grapes', 25],
 ['melon', 7],
 ['peach', 12],
 ['citrus', 5]]
def keep_cheap_fruits(fruit):
    return prices[fruit] <= 10

list(filter(keep_cheap_fruits, fruits))

['watermelon', 'melon', 'citrus']
[ [fruit, prices[fruit]] for fruit in fruits if prices[fruit] <= 10 and len(fruit)<= 5]

[['melon', 7]]
matrix = []
for i in range(1, 6):
    row = []
    matrix.append(row)
    for j in range(1, 11):
        row.append(i*j)

from pprint import pprint        
pprint(matrix)
    


[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
 [2, 4, 6, 8, 10, 12, 14, 16, 18, 20],
 [3, 6, 9, 12, 15, 18, 21, 24, 27, 30],
 [4, 8, 12, 16, 20, 24, 28, 32, 36, 40],
 [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]]
[ [i*j for i in range(1, 6)] for j in range(1, 11) ]

[[1, 2, 3, 4, 5],
 [2, 4, 6, 8, 10],
 [3, 6, 9, 12, 15],
 [4, 8, 12, 16, 20],
 [5, 10, 15, 20, 25],
 [6, 12, 18, 24, 30],
 [7, 14, 21, 28, 35],
 [8, 16, 24, 32, 40],
 [9, 18, 27, 36, 45],
 [10, 20, 30, 40, 50]]
matrix

[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
 [2, 4, 6, 8, 10, 12, 14, 16, 18, 20],
 [3, 6, 9, 12, 15, 18, 21, 24, 27, 30],
 [4, 8, 12, 16, 20, 24, 28, 32, 36, 40],
 [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]]
[ matrix[i][j] for i in range(5) for j in range(10)]

[1,
 2,
 3,
 4,
 5,
 6,
 7,
 8,
 9,
 10,
 2,
 4,
 6,
 8,
 10,
 12,
 14,
 16,
 18,
 20,
 3,
 6,
 9,
 12,
 15,
 18,
 21,
 24,
 27,
 30,
 4,
 8,
 12,
 16,
 20,
 24,
 28,
 32,
 36,
 40,
 5,
 10,
 15,
 20,
 25,
 30,
 35,
 40,
 45,
 50]
list(map(len, fruits))

[10, 5, 6, 5, 5, 6]
list(reversed(fruits))

['citrus', 'peach', 'melon', 'grapes', 'apple', 'watermelon']
enumerate(fruits)

<enumerate at 0x140b328>
range(10**12)

range(0, 1000000000000)
fruit_iterator = reversed(fruits)

next(fruit_iterator)


    ---------------------------------------------------------------------------

    StopIteration                             Traceback (most recent call last)

    <ipython-input-217-9c5f33135522> in <module>
    ----> 1 next(fruit_iterator)
    

    StopIteration: 


fruits

['watermelon', 'apple', 'grapes', 'melon', 'peach', 'citrus']
for fruit in reversed(fruits):
    print(fruit)

citrus
peach
melon
grapes
apple
watermelon
dir(fruit_iterator)

['__class__',
 '__delattr__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__iter__',
 '__le__',
 '__length_hint__',
 '__lt__',
 '__ne__',
 '__new__',
 '__next__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__setstate__',
 '__sizeof__',
 '__str__',
 '__subclasshook__']
a = range(10)
b = a.__iter__()
next(b)

0
list(reversed(fruits))

['citrus', 'peach', 'melon', 'grapes', 'apple', 'watermelon']
song = """\
Lovely Spam! Wonderful Spam!
Lovely Spam! Wonderful Spam
Spa-a-a-a-a-a-a-am
Spa-a-a-a-a-a-a-am
Spa-a-a-a-a-a-a-am
Spa-a-a-a-a-a-a-am
Lovely Spam! (Lovely Spam!)
Lovely Spam! (Lovely Spam!)
Lovely Spam!
Spam, Spam, Spam, Spam!
"""

with open('spam.txt', 'w') as f:
    print(song, file=f)

import os
os.system('spam.txt')

0
fin = open('spam.txt')

next(fin)

'Lovely Spam! Wonderful Spam!\n'
next(fin)

'Lovely Spam! Wonderful Spam\n'
for line in fin:
    print(line)

Spa-a-a-a-a-a-a-am

Spa-a-a-a-a-a-a-am

Spa-a-a-a-a-a-a-am

Spa-a-a-a-a-a-a-am

Lovely Spam! (Lovely Spam!)

Lovely Spam! (Lovely Spam!)

Lovely Spam!

Spam, Spam, Spam, Spam!



reduce


    ---------------------------------------------------------------------------

    NameError                                 Traceback (most recent call last)

    <ipython-input-237-62f6239f03f9> in <module>
    ----> 1 reduce
    

    NameError: name 'reduce' is not defined


for line in open('spam.txt'):
    print(line)

Lovely Spam! Wonderful Spam!

Lovely Spam! Wonderful Spam

Spa-a-a-a-a-a-a-am

Spa-a-a-a-a-a-a-am

Spa-a-a-a-a-a-a-am

Spa-a-a-a-a-a-a-am

Lovely Spam! (Lovely Spam!)

Lovely Spam! (Lovely Spam!)

Lovely Spam!

Spam, Spam, Spam, Spam!