In [2]:
import sys

print(sys.version)


3.6.0 |Anaconda custom (x86_64)| (default, Dec 23 2016, 13:19:00) 
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)]

In [6]:
import random

random.randint(1, 10)


Out[6]:
2

Пример программы на Python


In [8]:
# Задача: найти 10 самых популярных Python-репозиториев на GitHub

# Можно посмотреть стандартный модуль urllib — https://docs.python.org/3/library/urllib.html
import requests


API_URL = 'https://api.github.com/search/repositories?q=language:python&sort=stars&order=desc'


def get_most_starred_github_repositories():
    response = requests.get(API_URL)
                            
    if response.status_code == 200:
        return response.json()['items'][:10]

    return


for repo in get_most_starred_github_repositories():
    print(repo['name'])


awesome-python
httpie
thefuck
flask
youtube-dl
django
requests
awesome-machine-learning
ansible
scrapy

Переменные и базовые типы данных

Что такое переменная? Garbage Collector

variable = 1

variable = '2'


In [10]:
%%html
<style>
table {float:left}
</style>



In [15]:
variable = 1
variable = '1'

Именование переменных

my_variable = 'value'


In [16]:
a, b = 0, 1
print(a, b)


0 1

In [17]:
a, b = b, a
print(a, b)


1 0

Числа

Тип Пример
Integer 42
Integer (Hex) 0xA
Integer (Binary) 0b110101
Float 2.7182
Float 1.4e3
Complex 14+0j
Underscore 100_000

In [18]:
year = 2017
pi = 3.1415

print(year)
print(year + 1)


2017
2018

In [ ]:
amount = 100_000_000

In [ ]:


In [20]:
type(pi)


Out[20]:
float

In [22]:
int('wat?')


---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-22-b903d6c382bb> in <module>()
----> 1 int('wat?')

ValueError: invalid literal for int() with base 10: 'wat?'

In [23]:
round(10.2), round(10.6)


Out[23]:
(10, 11)

In [25]:
type(10.)


Out[25]:
float
Операция Результат
num + num2 Сложение
num - num2 Вычитание
num == num2 Равенство
num != num2 Неравенство
num >= num2 Больше-равно
num > num2 Больше
num * num2 Умножение
num / num2 Деление
num // num2 Целочисленное деление
num % num2 Модуль
num ** num2 Степень

In [26]:
6 / 3


Out[26]:
2.0

In [28]:
6 // 4


Out[28]:
1

In [29]:
6 / 0


---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-29-6823326f452a> in <module>()
----> 1 6 / 0

ZeroDivisionError: division by zero

In [31]:
(2 + 2) * 2


Out[31]:
8

Строки

Тип Пример
Строка 'hello'
Строка "hello"
Строка '''hello'''
Raw string r'hello'
Byte string b'hello'

In [32]:
s = '"Python" is the capital of Great Britain'
print(s)


"Python" is the capital of Great Britain

In [33]:
type(s)


Out[33]:
str

In [34]:
print("\"Python\" is the capital of Great Britain")


"Python" is the capital of Great Britain

In [35]:
print('hi \n there')
print(r'hi \n there')


hi 
 there
hi \n there

In [36]:
course_name = 'Курс Python Programming'  # строки в Python 3 — Unicode
course_name = "Курс Python Programming"

print(course_name)


Курс Python Programming

In [ ]:
long_string = "Perl — это тот язык, который одинаково " \
              "выглядит как до, так и после RSA шифрования." \
              "(Keith Bostic)"
        
long_string = """
    Обычно в таких кавычках
    пишут докстринги к функциям
"""
Операция Результат
s + s2 Сложение
'foo' in s2 Вхождение
s == s2 Равенство
s != s2 Неравенство
s >= s2 Больше-равно
s > s2 Больше
s * num Умножение
s[0] Доступ по индексу
len(s) Длина

In [37]:
'one' + 'two'


Out[37]:
'onetwo'

In [38]:
'one' * 10


Out[38]:
'oneoneoneoneoneoneoneoneoneone'

In [40]:
s1 = 'first'
print(id(s1))

s1 += '\n'
print(id(s1))


4494092080
4533714200

In [43]:
print('python'[10])


---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-43-ba6fc6278ce3> in <module>()
----> 1 print('python'[10])

IndexError: string index out of range

In [44]:
len('python')  # O(1)


Out[44]:
6

In [47]:
'python'[:3]


Out[47]:
'pyt'

In [48]:
'python'[::-1]


Out[48]:
'nohtyp'

In [49]:
'p' in 'python'


Out[49]:
True

In [51]:
'python'.capitalize()


Out[51]:
'Python'

In [52]:
byte_string = b'python'
print(byte_string[0])


112

Форматирование строк


In [56]:
name = 'World'

print('Hello, {}{}'.format(name, '!'))


Hello, World!

In [58]:
print('Hello, %s' % (name,))


Hello, World

In [60]:
print(f'Hello, {name}!')


Hello, World!

In [ ]:


In [61]:
tag_list = 'park, mstu, 21.09'
splitted = tag_list.split(', ')

print(splitted)


['park', 'mstu', '21.09']

In [62]:
':'.join(splitted)


Out[62]:
'park:mstu:21.09'

In [64]:
input_string = ' 79261234567  '
input_string.strip(' 7')


Out[64]:
'926123456'

In [ ]:


In [65]:
dir(str)


Out[65]:
['__add__',
 '__class__',
 '__contains__',
 '__delattr__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__getnewargs__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__iter__',
 '__le__',
 '__len__',
 '__lt__',
 '__mod__',
 '__mul__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__rmod__',
 '__rmul__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 'capitalize',
 'casefold',
 'center',
 'count',
 'encode',
 'endswith',
 'expandtabs',
 'find',
 'format',
 'format_map',
 'index',
 'isalnum',
 'isalpha',
 'isdecimal',
 'isdigit',
 'isidentifier',
 'islower',
 'isnumeric',
 'isprintable',
 'isspace',
 'istitle',
 'isupper',
 'join',
 'ljust',
 'lower',
 'lstrip',
 'maketrans',
 'partition',
 'replace',
 'rfind',
 'rindex',
 'rjust',
 'rpartition',
 'rsplit',
 'rstrip',
 'split',
 'splitlines',
 'startswith',
 'strip',
 'swapcase',
 'title',
 'translate',
 'upper',
 'zfill']

In [66]:
help(int)


Help on class int in module builtins:

class int(object)
 |  int(x=0) -> integer
 |  int(x, base=10) -> integer
 |  
 |  Convert a number or string to an integer, or return 0 if no arguments
 |  are given.  If x is a number, return x.__int__().  For floating point
 |  numbers, this truncates towards zero.
 |  
 |  If x is not a number or if base is given, then x must be a string,
 |  bytes, or bytearray instance representing an integer literal in the
 |  given base.  The literal can be preceded by '+' or '-' and be surrounded
 |  by whitespace.  The base defaults to 10.  Valid bases are 0 and 2-36.
 |  Base 0 means to interpret the base from the string as an integer literal.
 |  >>> int('0b100', base=0)
 |  4
 |  
 |  Methods defined here:
 |  
 |  __abs__(self, /)
 |      abs(self)
 |  
 |  __add__(self, value, /)
 |      Return self+value.
 |  
 |  __and__(self, value, /)
 |      Return self&value.
 |  
 |  __bool__(self, /)
 |      self != 0
 |  
 |  __ceil__(...)
 |      Ceiling of an Integral returns itself.
 |  
 |  __divmod__(self, value, /)
 |      Return divmod(self, value).
 |  
 |  __eq__(self, value, /)
 |      Return self==value.
 |  
 |  __float__(self, /)
 |      float(self)
 |  
 |  __floor__(...)
 |      Flooring an Integral returns itself.
 |  
 |  __floordiv__(self, value, /)
 |      Return self//value.
 |  
 |  __format__(...)
 |      default object formatter
 |  
 |  __ge__(self, value, /)
 |      Return self>=value.
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __getnewargs__(...)
 |  
 |  __gt__(self, value, /)
 |      Return self>value.
 |  
 |  __hash__(self, /)
 |      Return hash(self).
 |  
 |  __index__(self, /)
 |      Return self converted to an integer, if self is suitable for use as an index into a list.
 |  
 |  __int__(self, /)
 |      int(self)
 |  
 |  __invert__(self, /)
 |      ~self
 |  
 |  __le__(self, value, /)
 |      Return self<=value.
 |  
 |  __lshift__(self, value, /)
 |      Return self<<value.
 |  
 |  __lt__(self, value, /)
 |      Return self<value.
 |  
 |  __mod__(self, value, /)
 |      Return self%value.
 |  
 |  __mul__(self, value, /)
 |      Return self*value.
 |  
 |  __ne__(self, value, /)
 |      Return self!=value.
 |  
 |  __neg__(self, /)
 |      -self
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  __or__(self, value, /)
 |      Return self|value.
 |  
 |  __pos__(self, /)
 |      +self
 |  
 |  __pow__(self, value, mod=None, /)
 |      Return pow(self, value, mod).
 |  
 |  __radd__(self, value, /)
 |      Return value+self.
 |  
 |  __rand__(self, value, /)
 |      Return value&self.
 |  
 |  __rdivmod__(self, value, /)
 |      Return divmod(value, self).
 |  
 |  __repr__(self, /)
 |      Return repr(self).
 |  
 |  __rfloordiv__(self, value, /)
 |      Return value//self.
 |  
 |  __rlshift__(self, value, /)
 |      Return value<<self.
 |  
 |  __rmod__(self, value, /)
 |      Return value%self.
 |  
 |  __rmul__(self, value, /)
 |      Return value*self.
 |  
 |  __ror__(self, value, /)
 |      Return value|self.
 |  
 |  __round__(...)
 |      Rounding an Integral returns itself.
 |      Rounding with an ndigits argument also returns an integer.
 |  
 |  __rpow__(self, value, mod=None, /)
 |      Return pow(value, self, mod).
 |  
 |  __rrshift__(self, value, /)
 |      Return value>>self.
 |  
 |  __rshift__(self, value, /)
 |      Return self>>value.
 |  
 |  __rsub__(self, value, /)
 |      Return value-self.
 |  
 |  __rtruediv__(self, value, /)
 |      Return value/self.
 |  
 |  __rxor__(self, value, /)
 |      Return value^self.
 |  
 |  __sizeof__(...)
 |      Returns size in memory, in bytes
 |  
 |  __str__(self, /)
 |      Return str(self).
 |  
 |  __sub__(self, value, /)
 |      Return self-value.
 |  
 |  __truediv__(self, value, /)
 |      Return self/value.
 |  
 |  __trunc__(...)
 |      Truncating an Integral returns itself.
 |  
 |  __xor__(self, value, /)
 |      Return self^value.
 |  
 |  bit_length(...)
 |      int.bit_length() -> int
 |      
 |      Number of bits necessary to represent self in binary.
 |      >>> bin(37)
 |      '0b100101'
 |      >>> (37).bit_length()
 |      6
 |  
 |  conjugate(...)
 |      Returns self, the complex conjugate of any int.
 |  
 |  from_bytes(...) from builtins.type
 |      int.from_bytes(bytes, byteorder, *, signed=False) -> int
 |      
 |      Return the integer represented by the given array of bytes.
 |      
 |      The bytes argument must be a bytes-like object (e.g. bytes or bytearray).
 |      
 |      The byteorder argument determines the byte order used to represent the
 |      integer.  If byteorder is 'big', the most significant byte is at the
 |      beginning of the byte array.  If byteorder is 'little', the most
 |      significant byte is at the end of the byte array.  To request the native
 |      byte order of the host system, use `sys.byteorder' as the byte order value.
 |      
 |      The signed keyword-only argument indicates whether two's complement is
 |      used to represent the integer.
 |  
 |  to_bytes(...)
 |      int.to_bytes(length, byteorder, *, signed=False) -> bytes
 |      
 |      Return an array of bytes representing an integer.
 |      
 |      The integer is represented using length bytes.  An OverflowError is
 |      raised if the integer is not representable with the given number of
 |      bytes.
 |      
 |      The byteorder argument determines the byte order used to represent the
 |      integer.  If byteorder is 'big', the most significant byte is at the
 |      beginning of the byte array.  If byteorder is 'little', the most
 |      significant byte is at the end of the byte array.  To request the native
 |      byte order of the host system, use `sys.byteorder' as the byte order value.
 |      
 |      The signed keyword-only argument determines whether two's complement is
 |      used to represent the integer.  If signed is False and a negative integer
 |      is given, an OverflowError is raised.
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  denominator
 |      the denominator of a rational number in lowest terms
 |  
 |  imag
 |      the imaginary part of a complex number
 |  
 |  numerator
 |      the numerator of a rational number in lowest terms
 |  
 |  real
 |      the real part of a complex number


In [ ]:


In [67]:
import this  # знать хотя бы первые 3 пункта


The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

Базовые конструкции

Условный оператор


In [70]:
type(10 > 9)


Out[70]:
bool

In [69]:
10 < 9


Out[69]:
False

In [71]:
type(False)


Out[71]:
bool

Boolean

True / False (__bool__)

True False
True False
Большинство объектов None
1 0
3.2 0.0
'string' ""

In [77]:
a = 10
b = 10

print(a == b)
print(a is b)  # magic


True
True

In [73]:
bool(0.0)


Out[73]:
False

In [74]:
bool('')


Out[74]:
False

In [81]:
13 < 12 < foo_call()


Out[81]:
False

In [ ]:


In [82]:
import random


temperature_tomorrow = random.randint(18, 27)
if temperature_tomorrow >= 23:
    print('Срочно на пляж!')

else:
    print(':(')


Срочно на пляж!

In [ ]:
temperature_tomorrow = random.randint(18, 27)

decision = 'пляж' if temperature_tomorrow >= 23 else 'дома посижу'
print(decision)

In [85]:
answer = input('The answer to life the universe and everything is: ')
answer = answer.strip().lower()


if answer == '42':
    print('Точно!')

elif (answer == 'сорок два') or (answer == 'forty two'):
    print('Тоже вариант!')

else:
    print('Нет')


The answer to life the universe and everything is: 42
Точно!

In [86]:
bool(None)


Out[86]:
False

In [ ]:
type(None)

In [ ]:
a = None
print(a is None)

Задача

Определить, является ли введеный год високосным. Год является високосным, если его номер кратен 4, но не кратен 100, а также если он кратен 400


In [88]:
import calendar


calendar.isleap(1980)


Out[88]:
True

In [90]:
raw_year = input('Year: ')
year = int(raw_year)

if year % 400 == 0:
    print('Високосный')
    
elif year % 4 == 0 and not year % 100 == 0:
    print('Високосный')

else:
    print('Нет :(')


Year: 1980
Високосный

Циклы


In [91]:
for letter in 'python':
    print(letter)


p
y
t
h
o
n

In [94]:
s = 'python'
for idx in range(10):
    print(idx)


0
1
2
3
4
5
6
7
8
9

In [96]:
for idx, letter in enumerate('python'):
    print(idx, letter)


0 p
1 y
2 t
3 h
4 o
5 n

In [98]:
for letter in 'Python, Ruby. Perl, PHP.':
    if letter == ',':
        continue

    elif letter == '.':
        break

    print(letter)


P
y
t
h
o
n
 
R
u
b
y

for/while-else — знать можно, использовать лучше не стоит


In [99]:
patience = 5

while patience != 0:
    patience -= 1
    
    print(patience)


4
3
2
1
0

In [ ]:

Ошибки


In [100]:
user_range = int(input('Введите максимальное число диапазона: '))
for num in range(user_range):
    print(num)


Введите максимальное число диапазона: dfghj
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-100-26050a7027b5> in <module>()
----> 1 user_range = int(input('Введите максимальное число диапазона: '))
      2 for num in range(user_range):
      3     print(num)

ValueError: invalid literal for int() with base 10: 'dfghj'

In [ ]:

FizzBuzz

Напишите программу, которая выводит на экран числа от 1 до 100. При этом вместо чисел, кратных трем, программа должна выводить слово Fizz, а вместо чисел, кратных пяти — слово Buzz. Если число кратно пятнадцати, то программа должна выводить слово FizzBuzz.


In [101]:
for number in range(1, 101):
    result = ''
    
    if number % 3 == 0:
        result += 'Fizz'
    
    if number % 5 == 0:
        result += 'Buzz'
    
    print(result or number)


1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz
Fizz
22
23
Fizz
Buzz
26
Fizz
28
29
FizzBuzz
31
32
Fizz
34
Buzz
Fizz
37
38
Fizz
Buzz
41
Fizz
43
44
FizzBuzz
46
47
Fizz
49
Buzz
Fizz
52
53
Fizz
Buzz
56
Fizz
58
59
FizzBuzz
61
62
Fizz
64
Buzz
Fizz
67
68
Fizz
Buzz
71
Fizz
73
74
FizzBuzz
76
77
Fizz
79
Buzz
Fizz
82
83
Fizz
Buzz
86
Fizz
88
89
FizzBuzz
91
92
Fizz
94
Buzz
Fizz
97
98
Fizz
Buzz

ProjectEuler

1

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below 1000.


In [105]:
# multiples_sum = 0
# for number in range(1000):
#     if number % 3 == 0 or number % 5 == 0:
#         multiples_sum += number
        
# print(multiples_sum)

sum(
    num for num in range(1000)
    if num % 3 == 0 or num % 5 == 0
)


Out[105]:
233168

2

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.


In [109]:
a, b = 1, 1
fib_sum = 0
while b < 4_000_000:
    if b % 2 == 0:
        fib_sum += b
    
    a, b = b, a + b

print(fib_sum)


4613732

In [ ]:

4

A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.

Find the largest palindrome made from the product of two distinct 3-digit numbers.


In [113]:
def is_palindrome(number):
    str_number = str(number)
    return str_number == str_number[::-1]

In [111]:
is_palindrome(9009)


Out[111]:
True

In [115]:
max_palindrome = 0
for a in range(999, 100, -1):
    for b in range(999, 100, -1):
        multiple = a * b
        if multiple > max_palindrome and is_palindrome(multiple):
            max_palindrome = multiple
            break

print(max_palindrome)


906609

Функции


In [ ]:
def add_numbers(x, y):
    return x + y


add_numbers(10, 5)