вівторок, 23 квітня 2013 р.

Найбільший спільний дільник і найменше спільне кратне

Приклади знаходження найбільшого спільного дільника і найменшого спільного кратного на Python.

Найбі́льший спі́льний дільни́к (НСД) — найбільше натуральне число, на яке ці числа діляться без залишку.

Найменше спільне кратне (НСК) для (a, b) — найменше натуральне число яке ділиться без залишку на обидва числа a, b.

Варіант перший:
a = int(input('a = '))
b = int(input('b = '))

def evklid(a, b): # Функція знаходження найбільшого спільного дільника
    if a % b == 0:
        return b
    else:
        return evklid(b, a%b)

print (evklid(a, b))

nsk = a * b // evklid(a, b) # Знаходимо найменше спільне кратне
print (nsk)

Варіант другий:
a = int(input('a = '))
b = int(input('b = '))

def nsd(a, b): # Функція знаходження найбільшого спільного дільника
    while a*b != 0:
        if a >= b:
            a = a % b
        else:
            b = b % a
    return a + b            

print (nsd(a, b))

nsk = a * b // nsd(a, b) # Знаходимо найменше спільне кратне
print (nsk)

неділя, 21 квітня 2013 р.

ЗАДАЧА №9

Розв’язання завдання №9 на Python.

infile = open("INPUT.TXT")
outfile = open("OUTPUT.TXT", "w")

infile.readline()

line = [int(x) for x in infile.readline().split()]

summ = 0
for x in line:
    if x > 0:
        summ += x
        
mul = 1
nmin = line.index(min(line))
nmax = line.index(max(line))

if nmin > nmax:
    for x in line[nmax+1:nmin]:
        mul *= x
else:
    for x in line[nmin+1:nmax]:
        mul *= x

outfile.write(str(summ) + ' ' + str(mul))        
      
infile.close()
outfile.close()



ЗАДАЧА №8

Розв’язання завдання №8 на Python.

infile = open("INPUT.TXT")
outfile = open("OUTPUT.TXT", "w")

lst = [int(x) for x in infile.readline().split()]

if lst[2] == lst[0] * lst[1]:
    outfile.write('YES')
else:
    outfile.write('NO')        
      
infile.close()
outfile.close()



ЗАДАЧА №7

Розв’язання завдання №7 на Python.

infile = open("INPUT.TXT")
outfile = open("OUTPUT.TXT", "w")

line = [int(x) for x in infile.readline().split()]

outfile.write(str(max(line)))        
        
infile.close()
outfile.close()     



ЗАДАЧА №6

Розв’язання завдання №6 на Python.

infile = open("INPUT.TXT")
outfile = open("OUTPUT.TXT", "w")

line = infile.readline()

try:
    if (64 < ord(line[0]) and ord(line[3]) < 73) and (0 < int(line[1]) and int(line[4]) < 9):
        if abs(ord(line[0]) - ord(line[3])) == 2 and abs(int(line[1]) - int(line[4])) == 1:
            outfile.write('YES')
        elif abs(ord(line[0]) - ord(line[3])) == 1 and abs(int(line[1]) - int(line[4])) == 2:
            outfile.write('YES')
        else:
            outfile.write('NO')
except:
    outfile.write('ERROR')        
        
infile.close()
outfile.close()       

пʼятниця, 19 квітня 2013 р.

ЗАДАЧА №5

Розв’язання завдання №5 на Python.

infile = open('INPUT.TXT')
outfile = open('OUTPUT.TXT', 'w')

lines = infile.readlines()
lines[1] = [int(x) for x in lines[1].split()]

odd = []
even = []

for e in lines[1]:
    if e % 2:
        odd.append(e)
    else:
        even.append(e)
        
for e in odd:
    outfile.write(str(e) + ' ')
outfile.write('\n')            

for e in even:
    outfile.write(str(e) + ' ')
outfile.write('\n')            

if len(odd) < len(even):
    outfile.write('YES')
else:
    outfile.write('NO')        

ЗАДАЧА №4

Розв’язання завдання №4 на Python.

n = input('Введіть число: ')
print(n + '9' + str(9 - int(n)))



ЗАДАЧА №3

Розв’язання завдання №3 на Python.

def pw(n):
    if len(n) == 1:
        return int(n) ** 2
    else:
        return str(int(n[:-1]) * (int(n[:-1]) + 1)) + '25'

n = input('Введіть число: ')
print(pw(n))



середа, 17 квітня 2013 р.

ЗАДАЧА №2

Розв’язання завдання №2 на Python. Потрібно порахувати суму цілих чисел від 1 до N.

Варіант перший:
infile = open('input.txt')
outfile = open('output.txt', 'w')
 
N = int(infile.readline())
 
s = 0
for x in range(0, N+1):
    s += x

outfile.write(str(s))
 
infile.close()
outfile.close()

Варіант другий:
infile = open('input.txt')
outfile = open('output.txt', 'w')
 
N = int(infile.readline())
 
s = 0
while N > 0:
    s += N
    N -= 1

outfile.write(str(s))
 
infile.close()
outfile.close()          



Бульбашкове сортування

Бульбашкове сортування — у поданому наборі даних (списку чи масиві) порівнюються два сусідні елементи, якщо один з елементів не відповідає критерію сортування (є більшим, або ж, навпаки, меншим за свого сусіда), то ці два елементи міняються місцями. Прохід по списку продовжується до тих пір, доки дані не будуть відсортованими.

Перший варіант:
a = [1, 8, 3, 5, 7, 4]

print(a)

j = 1
while j < len(a):
    k = 0
    while k < (len(a) - 1):
        if a[k] > a[k+1]:
            a[k], a[k+1] = a[k+1], a[k]
        k += 1
    j += 1
     
print(a)            

Другий варіант:
a = [1, 8, 3, 5, 7, 4]

print(a)

for i in range(len(a), 0, -1):
    for j in range(0, len(a) - 1):
        if a[j] > a[j+1]:
            a[j], a[j+1] = a[j+1], a[j]
            
print(a)    



вівторок, 16 квітня 2013 р.

ЗАДАЧА №1 (A+B)

Розв’язання завдання №1 на Python
infile = open('input.txt')
outfile = open('output.txt', 'w')

line = infile.readline().split()

outfile.write(str(int(line[0]) + int(line[1])))

infile.close()
outfile.close()



Послідовність Фібоначчі

Послідовність Фібоначчі — послідовність в якій кожне наступне число дорівнює сумі двох попередніх чисел.

a, b = 0, 1
while b < 10000:
    print(b)
    a, b = b, a+b

понеділок, 15 квітня 2013 р.

Виведення числа у вигляді «великих цифр»

space = ['        ',
         '        ',
         '        ',
         '        ',
         '        ',
         '        ',
         '        ']

zero = ['   ***  ',
        '  *   * ',
        ' *     *',
        ' *     *',
        ' *     *',
        '  *   * ',
        '   ***  ']

one = ['   **   ',
       '  * *   ',
       ' *  *   ',
       '    *   ',
       '    *   ',
       '    *   ',
       ' * * * *']

two = [' * * * *',
       '       *',
       '       *',
       ' * * * *',
       ' *      ',
       ' *      ',
       ' * * * *']
       
three = [' * * * *',
         '       *',
         '       *',
         '   * * *',
         '       *',
         '       *',
         ' * * * *']

four = [' *     *',
        ' *     *',
        ' *     *',
        ' * * * *',
        '       *',
        '       *',
        '       *']
             
five = [' * * * *',
        ' *      ',
        ' *      ',
        ' * * * *',
        '       *',
        '       *',
        ' * * * *']

six = [' * * * *',
       ' *      ',
       ' *      ',
       ' * * * *',
       ' *     *',
       ' *     *',
       ' * * * *']
       
seven = [' * * * *',
         '      * ',
         '     *  ',
         '    *   ',
         '    *   ',
         '    *   ',
         '    *   ']       

eight = [' * * * *',
         ' *     *',
         ' *     *',
         ' * * * *',
         ' *     *',
         ' *     *',
         ' * * * *']           

nine = [' * * * *',
        ' *     *',
        ' *     *',
        ' * * * *',
        '       *',
        '       *',
        ' * * * *']
         
numbers = {'0': zero, '1': one, '2': two, '3': three,
           '4': four, '5': five, '6': six, '7': seven,
           '8': eight, '9': nine, ' ': space}

number = input('Веедіть число: ')

digits = []
for char in number:
    digits.append(char)
    
row = 0

while row < 7:
    for column in digits:
        print(numbers[column][row], end=' ')
    print()
    row += 1

неділя, 14 квітня 2013 р.

Алгоритм Евкліда. Рекурсія.

Алгоритм Евкліда — ефективний метод обчислення найбільшого спільного дільника.
import sys

def evklid(m, n):
    if m%n == 0:
        return n
    else:
        return evklid(n, m%n)
        
def main():
    print('Файл називається', sys.argv[0])
    if len(sys.argv) == 3:
        m, n = (int(sys.argv[1]), int(sys.argv[2]))
    else:
        m = int(input('Введіть значення m: '))
        n = int(input('Введіть значення n: '))
        
    print(evklid(m, n))
    
if __name__ == '__main__':
    main()



неділя, 24 березня 2013 р.

ЗАДАЧА №10

Розв’язання завдання №10 на Python
infile = open('INPUT.TXT')
outfile = open('OUTPUT.TXT', 'w')

line = [int(x) for x in infile.readline().split()]

a, b, c, d = line

for x in range(-100, 101):
    if a*x**3 + b*x*x + c*x + d == 0:
        outfile.write(str(x) + ' ')
        print x
    
infile.close()
outfile.close()



Приклади з лекції «Transforming code into Beautiful, Idiomatic Python by Raymond Hettinger»

Цикли в діапазоні чисел

for i in [0,1,2,3,4,5]:
    print i**2
    
for i in range(6):
    print i**2
    
for i in xrange(6):
    print i**2

Цикл по колекції

colors = ['red','green','blue','yellow']

for i in range(len(colors)):
    print colors[i]

for color in colors:
    print color 

Зворотній цикл

colors=['red','green','blue','yellow']

for i in range(len(colors)-1,-1,-1):
    print colors[i]

for color in reversed(colors):
    print color

Цикл за індексами

colors=['red','green','blue','yellow']

for i in range(len(colors)):
    print i, '-->', colors[i]
    
for i, color in enumerate(colors):
    print i, '-->', colors[i]

Цикл двох колекцій

names=['raymond','rachel','matthew']
colors=['red','green','blue','yellow']

n = min(len(names), len(colors))

for i in range(n):
    print names[i], '-->', colors[i]

for name, color in zip(names, colors):
    print name, '-->', color

for name, color in izip(names, colors):
    print name, '-->', color

Цикл в певному порядку

colors=['red','green','blue','yellow']

for color in sorted(colors):
    print color

for color in sorted(colors, reverse=True):
    print color

Користувальницький порядок сортування

colors=['red','green','blue','yellow']

def compare_length(c1, c2):
    if len(c1) < len(c2):
        return -1
    if len(c1) > len(c2):
        return 1
    return 0

print sorted(colors,cmp=compare_length)
print sorted(colors, key=len)

Цикл за ключем словника

d = {'matthew':'blue','rachel':'green','raymond':'red'}

for k in d:
    print k

for k in d.keys():
    if k.startswith('r'):
        del d[k]

d = {k : d[k] for k in d if not k.startswith('r')}

Цикл за ключем і значенням словника

d = {'matthew':'blue','rachel':'green','raymond':'red'}

for k in d:
    print k, '-->', d[k]

for k, v in d.items():
    print k, '-->', v

for k, v in d.iteritems():
    print k, '-->', v

Побудова словника з одного або двох списків

names=['raymond','rachel','matthew']
colors=['red','green','blue']

d = dict(izip(names, colors))
{'matthew':'blue','rachel':'green','raymond':'red'}

d = dict(enumerate(names))
{0:'raymond', 1:'rachel', 2:'matthew'}

Підрахунок в словнику

colors=['red','green','red','blue','green','red']

d = {}
for color in colors:
    if color not in d:
        d[color] = 0
    d[color] += 1

{'blue': 1,'green': 2,'red': 3}

d = {}
for color in colors:
    d[color] = d.get(color, 0) + 1

d = defaultdict(int)
for color in colors:
    d[color] += 1

Групування словників - І

names=['raymond','rachel','matthew','roger',
       'betty','melissa','judith','charlie']
d = {}
for name in names:
    key = len(name)
    if key not in d:
        d[key] = []
    d[key].append(name)
    
{5: ['roger','betty'], 6: ['rachel','judith'],
 7: ['raymond','matthew','melissa','charlie']} 

Групування словників - ІІ

names=['raymond','rachel','matthew','roger',
       'betty','melissa','judith','charlie']

d = {}
for name in names:
    key = len (name)
    d.setdefault(key, []).append(name)

d = defaultdict(list)
for name in names:
    key = len(name)
    d[key].append(name)

Is a dictionary popitem() atomic?

d = {'matthew':'blue','rachel':'green','raymond':'red'}

while d:
    key, value = d.popitem()
    print key, '-->', value

Розпакування послідовності

p = 'Raymond','Hettinger', 0x30,'python@example.com'

fname = p[0]
lname = p[1]
age = p[2]
email = p[3]

fname, lname, age, email = p

Оновлення декількох змінних

def fibonacci(n):
    x = 0
    y = 1
    for i in range(n):
        print x
        t = y
        y = x+y
        x = t

def fibonacci(n):
    x, y = 0, 1
    for i in range(n):
        print x
        x, y = y, x+y

Зчеплення(конкатенація) рядків

names = ['raymond','rachel','matthew','roger',
         'betty','melissa','judith','charlie']

s = names[0]
for name in names[1:]:
    s += ', ' + name
print s

print ', ' .join(names)

Як відкривати і закривати файли

f = open('data.txt')
try:
    data = f.read()
finally:
    f.close()

with open('data.txt') as f:
    data = f.read()

Списки і генератор виразу

result = []
for i in range(10):
    s = i**2
    result.append(s)
print sum(result)

print sum([i**2 for i in xrange(10)])

print sum(i**2 for i in xrange(10))



середа, 20 березня 2013 р.

Вибірка з книги «A Byte of Python» (продовження)

Модулі

Модуль можна «імпортувати» до іншої програми, щоб використовувати функції з нього. Точно так само ми використовуємо стандартну бібліотеку Python. Спершу подивимося, як використовувати модулі стандартної бібліотеки.

(Якщо ви хочете імпортувати змінну argv прямо у вашу програму (щоб не писати щоразу sys. при зверненні до неї), ви можете скористатися оператором from sys import argv. Якщо ви хочете імпортувати всі імена, що використовуються в модулі sys, ви можете виконати команду from sys import *. Це працює для будь-яких модулів.

У загальному випадку вам «слід уникати» використання цього оператора, і використовувати замість цього оператор import, оскільки це не допустить конфліктів імен, і програму буде легше читати).

#!/usr/bin/python
# Filename: using_sys.py
import sys
print('The command line arguments are:')
for i in sys.argv:
print(i)
print('\n\nThe PYTHONPATH is', sys.path, '\n')
$ python using_sys.py we are arguments
The command line arguments are:
using_sys.py
we
are
arguments
The PYTHONPATH is ['', 'C:\\Windows\\system32\\python30.zip',
'C:\\Python30\\DLLs', 'C:\\Python30\\lib',
'C:\\Python30\\lib\\plat-win', 'C:\\Python30',
'C:\\Python30\\lib\\site-packages']

Ім'я модуля — __name__

У кожного модуля є ім'я, і команди в модулі можуть дізнатися ім'я їх модуля. Це корисно, коли потрібно знати, чи запущений модуль сам по собі або імпортований. Як уже згадувалося вище, коли модуль імпортується вперше, код, який в ньому міститься, виконується. Ми можемо скористатися цим для того, щоб змусити модуль вести себе по-різному в залежності від того, чи використовується він сам по собі або імпортується в інший модуль. Цього можна досягти із застосуванням атрибуту модуля під назвою __name__.
#!/usr/bin/python
# Filename: using_name.py
if __name__ == '__main__':
print('This program is being run by itself')
else:
print('I am being imported from another module')
$ python using_name.py
This program is being run by itself
$ python
>>> import using_name
I am being imported from another module
>>>

Функція dir

Ви можете використовувати вбудовану функцію dir, щоб отримати список ідентифікаторів, які об'єкт визначає. Наприклад, до ідентифікатора модуля входять функції, класи і змінні, визначені в цьому модулі.

Коли ви передаєте функції dir() ім'я модуля, вона повертає список імен, визначених в цьому модулі. Якщо ніякого аргументу не передавати, вона поверне список імен, визначених в поточному модулі.
$ python
>>> import sys # отримаємо список атрибутів модуля «sys»
>>> dir(sys)
['__displayhook__', '__doc__', '__excepthook__', '__name__',
'__package__', '__s
tderr__', '__stdin__', '__stdout__', '_clear_type_cache',
'_compact_freelists',
'_current_frames', '_getframe', 'api_version', 'argv',
'builtin_module_names', '
byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook',
'dllhandle'
, 'dont_write_bytecode', 'exc_info', 'excepthook', 'exec_prefix',
'executable',
'exit', 'flags', 'float_info', 'getcheckinterval',
'getdefaultencoding', 'getfil
esystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount',
'getsizeof',
'gettrace', 'getwindowsversion', 'hexversion', 'intern', 'maxsize',
'maxunicode
', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache',
'platfor
m', 'prefix', 'ps1', 'ps2', 'setcheckinterval', 'setprofile',
'setrecursionlimit
', 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version',
'version_in
fo', 'warnoptions', 'winver']

>>> dir() # отримаємо список атрибутів поточного модуля
['__builtins__', '__doc__', '__name__', '__package__', 'sys']

>>> a = 5 # створимо нову змінну «a»

>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'a', 'sys']

>>> del a # видалимо ім'я «a»

>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'sys']
>>>

Пакунки

Пакунки — це каталоги з модулями і спеціальним файлом __init__.py, який показує Python, що цей каталог особливий, бо містить модулі Python.

Уявімо, що ви хочете створити пакет під назвою «world» з субпакетами «asia», «africa» і т.д, а субпакети ці повинні містити модулі «india», «madagascar» і т.д.

Для цього вам слід було б створити таку структуру каталогів:
| - <деякий каталог із sys.path>/
| |---- world/
|      |---- __init__.py
|      |---- asia/
|      |    |---- __init__.py
|      |    |---- india/
|      |         |---- __init__.py
|      |         |---- foo.py
|      |---- africa/
|           |---- __init__.py
|           |---- madagascar/
|                |---- __init__.py
|                |---- bar.py

Структури даних — Список

Список — це структура даних, яка містить упорядкований набір елементів, тобто ви можете зберігати в списку послідовність елементів.

Список елементів повинен бути укладений у квадратні дужки, щоб Python зрозумів, що ви вказуєте список. Як тільки ви створили список, ви можете додавати, видаляти або шукати елементи в цьому списку. Оскільки ми можемо додавати і видаляти елементи, ми говоримо, що список — це змінюваний тип даних, тобто його можна змінювати.

(Зверніть увагу на використання ключового аргументу end в функції print, який показує, що ми хочемо закінчити виведення пробілом замість звичайного переведення рядка).
#!/usr/bin/python
# Filename: using_list.py

# This is my shopping list
shoplist = ['apple', 'mango', 'carrot', 'banana']

print('I have', len(shoplist), 'items to purchase.')

print('These items are:', end=' ')
for item in shoplist:
    print(item, end=' ')

print('\nI also have to buy rice.')
shoplist.append('rice')
print('My shopping list is now', shoplist)

print('I will sort my list now')
shoplist.sort()
print('Sorted shopping list is', shoplist)

print('The first item I will buy is', shoplist[0])
olditem = shoplist[0]
del shoplist[0]
print('I bought the', olditem)
print('My shopping list is now', shoplist)
$ python using_list.py
I have 4 items to purchase.
These items are: apple mango carrot banana
I also have to buy rice.
My shopping list is now ['apple', 'mango', 'carrot', 'banana',
'rice']
I will sort my list now
Sorted shopping list is ['apple', 'banana', 'carrot', 'mango',
'rice']
The first item I will buy is apple
I bought the apple
My shopping list is now ['banana', 'carrot', 'mango', 'rice']

Структури даних — Кортеж

Кортежі служать для зберігання кількох об'єктів разом. Одна з найважливіших особливостей кортежів, це те, що вони незмінні, так само, як і рядки.

Кортежі зазвичай використовуються в тих випадках, коли оператор або функція повинні напевно знати, що набір значень, тобто кортеж значень, не зміниться.
#!/usr/bin/python
# Filename: using_tuple.py

zoo = ('python', 'elephant', 'penguin') # remember the parentheses are
optional
print('Number of animals in the zoo is', len(zoo))

new_zoo = ('monkey', 'camel', zoo)
print('Number of cages in the new zoo is', len(new_zoo))
print('All animals in new zoo are', new_zoo)
print('Animals brought from old zoo are', new_zoo[2])
print('Last animal brought from old zoo is', new_zoo[2][2])
print('Number of animals in the new zoo is',
len(new_zoo)-1+len(new_zoo[2]))
$ python using_tuple.py
Number of animals in the zoo is 3
Number of cages in the new zoo is 3
All animals in new zoo are ('monkey', 'camel', ('python',
'elephant', 'penguin'))
Animals brought from old zoo are ('python', 'elephant', 'penguin')
Last animal brought from old zoo is penguin
Number of animals in the new zoo is 5

Структури даних — Словник

Словник — аналог адресної книги, де ви можете знайти адресу або контактну інформацію про людину, знаючи лише її ім'я, тобто ми пов'язуємо деякі ключі (імена) зі значеннями (інформацією). Зауважте, що ключ повинен бути унікальним.

В якості ключів ви можете використовувати тільки незмінні об'єкти, а в якості значень можна використовувати як незмінні, так і змінні об'єкти. Це, по суті, означає, що ви повинні використовувати тільки прості об'єкти в якості ключів.

Пари ключ-значення вказуються в словнику таким чином: d = {key1: value1, key2: value2}. Зверніть увагу, як ключ і значення розділяються двокрапкою, а пари один від одного відокремлюються комами, а потім все це укладається у фігурні дужки.

Пам'ятайте, що пари ключ-значення жодним чином не впорядковані в словнику. Якщо вам необхідний деякий порядок, вам доведеться окремо відсортувати словник перед зверненням до нього.
#!/usr/bin/python
# Filename: using_dict.py

# 'ab' - скорочення від 'a'ddress'b'ook

ab = {  'Swaroop'   : 'swaroop@swaroopch.com',
        'Larry'     : 'larry@wall.org',
        'Matsumoto' : 'matz@ruby-lang.org',
        'Spammer'   : 'spammer@hotmail.com'
     }

print("Адреса Swaroop'а:", ab['Swaroop'])

# Видалення пари ключ-значення
del ab['Spammer']

print('\nВ адресній книзі {0} контактів\n'.format(len(ab)))

for name, address in ab.items():
    print('Контакт {0} з адресою {1}'.format(name, address))

# Додавання пари ключ-значення
ab['Guido'] = 'guido@python.org'

if 'Guido' in ab:
    print("\nАдреса Guido:", ab['Guido'])
$ python using_dict.py
Адреса Swaroop’а: swaroop@swaroopch.com

В адресній книзі 3 контактів

Контакт Swaroop з адресою swaroop@swaroopch.com
Контакт Matsumoto з адресою matz@ruby-lang.org
Контакт Larry з адресою larry@wall.org

Адреса Guido: guido@python.org

Структури даних — Множина

Множини — це невпорядковані набори простих об'єктів. Це необхідно тоді, коли присутність об'єкта в наборі важливіше порядку або того, скільки разів даний об'єкт там зустрічається.

Використовуючи множини, ви можете здійснювати перевірку належності, чи є дана множина підмножиною іншої множини, знаходити перетин множин і так далі.
>>> bri = set(['brazil', 'russia', 'india'])
>>> 'india' in bri
True
>>> 'usa' in bri
False
>>> bric = bri.copy()
>>> bric.add('china')
>>> bric.issuperset(bri)
True
>>> bri.remove('russia')
>>> bri & bric # OR bri.intersection(bric)
{'brazil', 'india'}

Структури даних — Рядки

Всі рядки, що використовуються вами в програмах, є об'єктами класу str. Деякі корисні методи цього класу продемонстровані на прикладі нижче. Щоб подивитися весь список методів, виконайте help (str).
#!/usr/bin/python
# Filename: str_methods.py

name = 'Swaroop' # This is a string object

if name.startswith('Swa'):
    print('Yes, the string starts with "Swa"')

if 'a' in name:
    print('Yes, it contains the string "a"')

if name.find('war') != -1:
    print('Yes, it contains the string "war"')

delimiter = '_*_'
mylist = ['Brazil', 'Russia', 'India', 'China']
print(delimiter.join(mylist))
$ python str_methods.py
Yes, the string starts with "Swa"
Yes, it contains the string "a"
Yes, it contains the string "war"
Brazil_*_Russia_*_India_*_China

пʼятниця, 1 березня 2013 р.

Вибірка з книги «A Byte of Python»

Метод Format

#!/usr/bin/python
# Filename: str_format.py

age = 26
name = 'Swaroop'

print('{0} is {1} years old'.format(name, age))
print('Why is {0} playing with that python?'.format(name))
$ python str_format.py
Swaroop is 25 years old
Why is Swaroop playing with that python?

Використання змінних і констант

# Filename : var.py

i = 5
print(i)
i = i + 1
print(i)

s = '''This is a multi-line string.
This is the second line.'''
print(s)
$ python var.py
5
6
This is a multi-line string.
This is the second line.

Вирази

#!/usr/bin/python
# Filename: expression.py

length = 5
breadth = 2

area = length * breadth
print('Area is', area)
print('Perimeter is', 2 * (length + breadth))
$ python expression.py
Area is 10
Perimeter is 14

Оператор if

Оператор if використовується для перевірки умов: «якщо» умова вірна, виконується блок виразів «if-блок», «інакше» виконується інший блок виразів «else-блок». Блок «else» не є обов'язковим.
#!/usr/bin/python
# Filename: if.py

number = 23
guess = int(input('Enter an integer : '))

if guess == number:
    print('Congratulations, you guessed it.') # New block starts here
    print('(but you do not win any prizes!)') # New block ends here
elif guess < number:
    print('No, it is a little higher than that') # Another block
    # You can do whatever you want in a block ...
else:
    print('No, it is a little lower than that')
    # you must have guess > number to reach here

print('Done')
# This last statement is always executed, after the if statement is
executed
$ python if.py
Enter an integer : 50
No, it is a little lower than that
Done
$ python if.py
Enter an integer : 22

Оператор while

Оператор while дозволяє вам багаторазово виконувати блок команд до тих пір, поки виконується умова. Оператор while — приклад того, що називають оператором циклу. Оператор while може мати необов'язковий пункт else.
#!/usr/bin/python
# Filename: while.py

number = 23
running = True

while running:
    guess = int(input('Enter an integer : '))

    if guess == number:
        print('Congratulations, you guessed it.')
        running = False # this causes the while loop to stop
    elif guess < number:
        print('No, it is a little higher than that.')
    else:
        print('No, it is a little lower than that.')
else:
    print('The while loop is over.')
    # Do anything else you want to do here

print('Done')
$ python while.py
Enter an integer : 50
No, it is a little lower than that.
Enter an integer : 22
No, it is a little higher than that.
Enter an integer : 23
Congratulations, you guessed it.
The while loop is over.
Done

Цикл for

#!/usr/bin/python
# Filename: for.py

for i in range(1, 5):
    print(i)
else:
    print('The for loop is over')
$ python for.py
1
2
3
4
The for loop is over

Оператор break

Оператор break слугує для «переривання» циклу, тобто зупинення виконання команд навіть якщо умова виконання циклу ще не прийняла значення False або послідовність елементів не закінчилася. Важливо відзначити, що якщо ви перериваєте цикл for чи while оператором break, відповідні їм блоки else виконуватиметься не будуть.
#!/usr/bin/python
# Filename: break.py

while True:
    s = (input('Enter something : '))
    if s == 'quit':
        break
    print('Length of the string is', len(s))
print('Done')
$ python break.py
Enter something : Programming is fun
Length of the string is 18
Enter something : When the work is done
Length of the string is 21
Enter something : if you wanna make your work also fun:
Length of the string is 37
Enter something :       use Python!
Length of the string is 12
Enter something : quit
Done

Оператор continue

Оператор continue використовується для вказівки, що необхідно пропустити всі команди, які залишилися в поточному блоці циклу і «продовжити» з наступної ітерації циклу.
#!/usr/bin/python
# Filename: continue.py

while True:
    s = input('Enter something : ')
    if s == 'quit':
        break
    if len(s) < 3:
        print('Too small')
        continue
    print('Input is of sufficient length')
    # Do other kinds of processing here...
$ python test.py
Enter something : a
Too small
Enter something : 12
Too small
Enter something : abc
Input is of sufficient length
Enter something : quit

Функції

Функції — це фрагменти програми, які багаторазово використовуються. Вони дозволяють вам дати ім'я певному блоку команд з тим, щоби згодом запускати цей блок, використовуючи вказане ім'я. Функції визначаються за допомогою зарезервованого слова «def». Після цього слова вказується «ім'я» функції, за яким слідує пара дужок, в яких можна вказати імена деяких змінних, і заключна двокрапка в кінці рядка.
#!/usr/bin/python
# Filename: function1.py

def sayHello():
    print('Hello World!') # block belonging to the function
# End of function

sayHello() # call the function
sayHello() # call the function again
$ python function1.py
Hello World!
Hello World!

Параметри функцій

Параметри вказуються в дужках при оголошенні функції та розділяються комами. Аналогічно ми передаємо значення, коли викликаємо функцію. Зверніть увагу на термінологію: імена, зазначені в оголошенні функції, називаються «параметрами», тоді як значення, які ви передаєте до функції при її виклику, «аргументами».
#!/usr/bin/python
# Filename: func_param.py

def printMax(a, b):
    if a > b:
        print(a, 'is maximum')
    elif a == b:
        print(a, 'is equal to', b)
    else:
        print(b, 'is maximum')

printMax(3, 4) # directly give literal values

x = 5
y = 7

printMax(x, y) # give variables as arguments
$ python func_param.py
4 is maximum
7 is maximum

Локальні змінні

Коли ви оголошуєте змінні всередині визначення функції, вони жодним чином не пов'язані з іншими змінними з таким же ім'ям поза функцією — тобто імена змінних є «локальними» в функції. Це називається «областю видимості» змінної. Область видимості всіх змінних обмежена блоком, в якому вони оголошені.
#!/usr/bin/python
# Filename: func_local.py

x = 50

def func(x):
    print('x is', x)
    x = 2
    print('Changed local x to', x)

func(x)
print('x is still', x)
$ python func_local.py
x is 50
Changed local x to 2
x is still 50

Зарезервоване слово global

Якщо ви хочете присвоїти деяке значення змінній, що визначена на вищому рівні програми, ви повинні вказати, що її ім'я не локальне, а глобальне (global).
#!/usr/bin/python
# Filename: func_global.py

x = 50

def func():
    global x
    
    print('x is', x)
    x = 2
    print('Changed global x to', x)

func()
print('Value of x is', x)
$ python func_global.py
x is 50
Changed global x to 2
Value of x is 2

Зарезервоване слово nonlocal

Ще один тип області видимості, так звана «нелокальна» (nonlocal), яка являє собою щось середнє між «глобальною» і «локальною». Нелокальні області видимості зустрічаються, коли ви визначаєте функції всередині функцій.
#!/usr/bin/python
# Filename: func_nonlocal.py

def func_outer():
    x = 2
    print('x is', x)
    
    def func_inner():
        nonlocal x
        x = 5

    func_inner()
    print('Changed local x to', x)

func_outer()
$ python func_nonlocal.py
x is 2
Changed local x to 5

Значення аргументів за замовчуванням

Для деяких функцій ви можете зробити частину параметрів «необов'язковими» і використовувати деякі задані значення за замовчуванням, якщо користувач не бажає вказувати власні значення для них. Ви можете вказати значення аргументів за замовчуванням, додавши до імені параметра у визначенні функції оператор присвоювання «=» з наступним значенням.
#!/usr/bin/python
# Filename: func_default.py

def say(message, times = 1):
    print(message * times)

say('Hello')
say('World', 5)
$ python func_default.py
Hello
WorldWorldWorldWorldWorld

Ключові аргументи

Якщо у вас є деяка функція з великим числом параметрів, і ви хочете вказувати тільки деякі з них при виклику, ви можете задавати значення цих параметрах за їхнім ім’ям — це називається «ключові параметри». У цьому випадку ми використовуємо ім'я (ключ) замість позиції (як було досі), щоб передати аргументи функції.

Є дві «переваги» такого підходу: по-перше, використання функції стає простіше, оскільки немає необхідності відстежувати порядок аргументів; по-друге, ми можемо задавати значення тільки деяким обраним аргументам, за умови, що інші параметри мають значення аргументу за замовчуванням.
#!/usr/bin/python
# Filename: func_key.py

def func(a, b=5, c=10):
    print('a is', a, 'and b is', b, 'and c is', c)

func(3, 7)
func(25, c=24)
func(c=50, a=100)
$ python func_key.py
a is 3 and b is 7 and c is 10
a is 25 and b is 5 and c is 24
a is 100 and b is 5 and c is 50

Змінне число параметрів

Вам може іноді знадобитися визначити функцію, здатну приймати будь яке число параметрів. Цього можна досягти із застосуванням зірочок.

Коли ми оголошуємо параметр із зірочкою, як наприклад, «*numbers», всі позиційні аргументи починаючи з цієї позиції і до кінця будуть зібрані в кортеж під ім'ям «numbers».

Аналогічно, коли ми оголошуємо параметри з двома зірочками, як наприклад «**keywords», всі ключові аргументи починаючи з цієї позиції і до кінця будуть зібрані в словник під ім'ям «keywords».
#!/usr/bin/python
# Filename: total.py

def total(initial=5, *numbers, **keywords):
    count = initial
    for number in numbers:
        count += number
    for key in keywords:
        count += keywords[key]
    return count

print(total(10, 1, 2, 3, vegetables=50, fruits=100))
$ python total.py
166

Тільки ключові параметри

Якщо ми хочемо зазначити, що деякі ключові параметри повинні бути доступні тільки по ключу, а не як позиційні аргументи, їх можна оголосити після параметра із зірочкою. Оголошення параметрів після параметра із зірочкою дає тільки ключові аргументи. Якщо для таких аргументів не вказано значення за замовчуванням, звернення до функції викличе помилку.
#!/usr/bin/python
# Filename: keyword_only.py

def total(initial=5, *numbers, vegetables):
    count = initial
    for number in numbers:
        count += number
    count += vegetables
    return count

print(total(10, 1, 2, 3, vegetables=50))
print(total(10, 1, 2, 3))
# Raises error because we have not supplied a default argument value
for 'vegetables'
$ python keyword_only.py
66
Traceback (most recent call last):
File "test.py", line 12, in 
print(total(10, 1, 2, 3))
TypeError: total() needs keyword-only argument vegetables

Оператор return

Оператор return використовується для повернення з функції, тобто для припинення її роботи і виходу з неї. При цьому можна також «повернути деяке значення» з функції.
#!/usr/bin/python
# Filename: func_return.py

def maximum(x, y):
    if x > y:
        return x
    else:
        return y

print(maximum(2, 3))
$ python func_return.py
3

Рядки документації

Python має особливість, так звані «рядки документації», які зазвичай позначаються скорочено «docstrings». Це дуже важливий інструмент, яким ви повинні користуватись, оскільки він допомагає краще документувати програму і полегшує її розуміння. Вражаюче, але ми можемо отримати рядок документації, наприклад, з функції, навіть під час виконання програми!
#!/usr/bin/python
# Filename: func_doc.py

def printMax(x, y):
    '''Prints the maximum of two numbers.

    The two values must be integers.'''
    x = int(x) # convert to integers, if possible
    y = int(y)

    if x > y:
        print(x, 'is maximum')
    else:
        print(y, 'is maximum')

printMax(3, 5)
print(printMax.__doc__)
$ python func_doc.py
5 is maximum
Prints the maximum of two numbers.
The two values must be integers.