Объекты и переменные

In [1]:
a = [1, 2, 3]
b = a
b[1] = 4
print(a)
print(b)
[1, 4, 3]
[1, 4, 3]
In [2]:
a = [1, 2, 3]
b = list(a)
b[1] = 4
print(a)
print(b) 
[1, 2, 3]
[1, 4, 3]
In [3]:
a = [1, [2, 3]]
b = list(a)
b[1][0] = 4
print(a)
print(b) 
[1, [4, 3]]
[1, [4, 3]]
In [4]:
import copy
a = [1, [2, 3]]
b = copy.copy(a)
b[1][0] = 4
print(a)
print(b) 
[1, [4, 3]]
[1, [4, 3]]
In [5]:
import copy
a = [1, [2, 3]]
b = copy.deepcopy(a)
b[1][0] = 4
print(a)
print(b) 
[1, [2, 3]]
[1, [4, 3]]

if

In [1]:
import math
In [2]:
def sample_function(t):
    if t < -2:
        return -2
    elif -2 <= t < 0:
        return t
    elif t == 0:
        return 0
    else:
        return t * math.sin(1 / t)
In [3]:
sample_function(-5)
Out[3]:
-2
In [4]:
sample_function(-1)
Out[4]:
-1
In [5]:
sample_function(0)
Out[5]:
0
In [6]:
sample_function(1)
Out[6]:
0.8414709848078965
In [7]:
%pylab inline
Populating the interactive namespace from numpy and matplotlib
In [8]:
t = arange(-5, 5, 0.01)
In [9]:
grid()
plot(t, list(map(sample_function, t)))
Out[9]:
[<matplotlib.lines.Line2D at 0x10efddc50>]
In [10]:
x = 1 if True else 2
x
Out[10]:
1
In [11]:
x = 1 if False else 2
x
Out[11]:
2

for

In [1]:
a = [[1, 2], [3, 4]]
In [2]:
for x in a:
    for y in x:
        print(y)
1
2
3
4
In [3]:
for x, y in a:
    print(x, y)
1 2
3 4

Функции

In [1]:
def f(a, b, c):
    print(a, b, c, sep=", ")
In [2]:
f(1, 2, 3)
1, 2, 3
In [3]:
f(1, c=3, b=2)
1, 2, 3
In [4]:
a = [1, 2, 3]
In [5]:
f(a)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-6a4ba51a6ef9> in <module>()
----> 1 f(a)

TypeError: f() missing 2 required positional arguments: 'b' and 'c'
In [6]:
f(*a)
1, 2, 3
In [7]:
a = [2, 3]
In [8]:
f(1, *a)
1, 2, 3
In [9]:
d = {'c': 3, 'b': 2, 'a': 1}
In [10]:
f(**d)
1, 2, 3
In [11]:
def f(a, b=2, c=3):
    print(a, b, c, sep=", ")
In [12]:
f(1)
1, 2, 3
In [13]:
f(1, 4)
1, 4, 3
In [14]:
f(1, 4, 5)
1, 4, 5
In [15]:
def f(a, b=[]):
    b.append(a)
    print(b)
In [16]:
f(1)
[1]
In [17]:
f(2)
[1, 2]
In [18]:
f(3)
[1, 2, 3]
In [19]:
def f(*args, **kwargs):
    print(args, kwargs, sep=", ")
In [20]:
f(1, 2, 3, x=4, y=5)
(1, 2, 3), {'y': 5, 'x': 4}

str.format

In [1]:
name = 'Alice'
In [2]:
"Hello, {0}".format(name)
Out[2]:
'Hello, Alice'
In [3]:
"Hello, {}".format(name)
Out[3]:
'Hello, Alice'
In [4]:
name1 = 'Bob'
name2 = 'Malory'
In [5]:
"Hello, {} and {}".format(name1, name2)
Out[5]:
'Hello, Bob and Malory'
In [6]:
"{0}cad{0}".format("abra")
Out[6]:
'abracadabra'
In [7]:
"{0.real} + {0.imag}i".format(1 + 2j)
Out[7]:
'1.0 + 2.0i'
In [8]:
"Hello, {name}".format(name="Guido")
Out[8]:
'Hello, Guido'
In [9]:
"Hello, {name[0]} and {name[1]}".format(name=["Jack", "Jill"])
Out[9]:
'Hello, Jack and Jill'
In [10]:
a = 1
b = 2
"{a} + {b} = {}".format(a + b, **locals())
Out[10]:
'1 + 2 = 3'