In [2]:
import sys
print(sys.version)
In [6]:
import random
random.randint(1, 10)
Out[6]:
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'])
In [10]:
%%html
<style>
table {float:left}
</style>
In [15]:
variable = 1
variable = '1'
In [16]:
a, b = 0, 1
print(a, b)
In [17]:
a, b = b, a
print(a, b)
In [18]:
year = 2017
pi = 3.1415
print(year)
print(year + 1)
In [ ]:
amount = 100_000_000
In [ ]:
In [20]:
type(pi)
Out[20]:
In [22]:
int('wat?')
In [23]:
round(10.2), round(10.6)
Out[23]:
In [25]:
type(10.)
Out[25]:
Операция | Результат |
---|---|
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]:
In [28]:
6 // 4
Out[28]:
In [29]:
6 / 0
In [31]:
(2 + 2) * 2
Out[31]:
In [32]:
s = '"Python" is the capital of Great Britain'
print(s)
In [33]:
type(s)
Out[33]:
In [34]:
print("\"Python\" is the capital of Great Britain")
In [35]:
print('hi \n there')
print(r'hi \n there')
In [36]:
course_name = 'Курс Python Programming' # строки в Python 3 — Unicode
course_name = "Курс Python Programming"
print(course_name)
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]:
In [38]:
'one' * 10
Out[38]:
In [40]:
s1 = 'first'
print(id(s1))
s1 += '\n'
print(id(s1))
In [43]:
print('python'[10])
In [44]:
len('python') # O(1)
Out[44]:
In [47]:
'python'[:3]
Out[47]:
In [48]:
'python'[::-1]
Out[48]:
In [49]:
'p' in 'python'
Out[49]:
In [51]:
'python'.capitalize()
Out[51]:
In [52]:
byte_string = b'python'
print(byte_string[0])
In [56]:
name = 'World'
print('Hello, {}{}'.format(name, '!'))
In [58]:
print('Hello, %s' % (name,))
In [60]:
print(f'Hello, {name}!')
In [ ]:
In [61]:
tag_list = 'park, mstu, 21.09'
splitted = tag_list.split(', ')
print(splitted)
In [62]:
':'.join(splitted)
Out[62]:
In [64]:
input_string = ' 79261234567 '
input_string.strip(' 7')
Out[64]:
In [ ]:
In [65]:
dir(str)
Out[65]:
In [66]:
help(int)
In [ ]:
In [67]:
import this # знать хотя бы первые 3 пункта
In [70]:
type(10 > 9)
Out[70]:
In [69]:
10 < 9
Out[69]:
In [71]:
type(False)
Out[71]:
In [77]:
a = 10
b = 10
print(a == b)
print(a is b) # magic
In [73]:
bool(0.0)
Out[73]:
In [74]:
bool('')
Out[74]:
In [81]:
13 < 12 < foo_call()
Out[81]:
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('Нет')
In [86]:
bool(None)
Out[86]:
In [ ]:
type(None)
In [ ]:
a = None
print(a is None)
In [88]:
import calendar
calendar.isleap(1980)
Out[88]:
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('Нет :(')
In [91]:
for letter in 'python':
print(letter)
In [94]:
s = 'python'
for idx in range(10):
print(idx)
In [96]:
for idx, letter in enumerate('python'):
print(idx, letter)
In [98]:
for letter in 'Python, Ruby. Perl, PHP.':
if letter == ',':
continue
elif letter == '.':
break
print(letter)
for/while-else — знать можно, использовать лучше не стоит
In [99]:
patience = 5
while patience != 0:
patience -= 1
print(patience)
In [ ]:
In [100]:
user_range = int(input('Введите максимальное число диапазона: '))
for num in range(user_range):
print(num)
In [ ]:
Напишите программу, которая выводит на экран числа от 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)
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]:
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)
In [ ]:
In [113]:
def is_palindrome(number):
str_number = str(number)
return str_number == str_number[::-1]
In [111]:
is_palindrome(9009)
Out[111]:
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)
In [ ]:
def add_numbers(x, y):
return x + y
add_numbers(10, 5)