Въведение в Python

„ Програмиране с Python“, ФМИ

08.03.2011г.

Python Shell

>>> word = "Ni!"
>>> knights = "We Are The Knights Who Say"
>>> print(knights, word)
We Are The Knights Who Say Ni!
>>> 2 * 2
4

Програма на Python

name = "Guido"
print("Hello, I'm Python and", name, "created me!")
Hello, I'm Python and Guido created me!

Обекти, имена, променливи

answer = "Forty Two"
answer = 42
>>> print(question)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'question' is not defined

Основни типове

Операции с числа

Текстови низове

Дефиниране на низове

>>> food = 'spam'
>>> taste = "yum"
>>> "spam" == 'spam'
True
>>> 'I can\'t taste your ' + food + ', can I?'
>>> "Yes, you can't"

Джордж Бул

Булеви Операции

Блокове

what if

if name == "King Arthur":
    print("What is the average speed of a swallow?")
elif name == "Sir Robin":
    print("What is the capital of Assyria")
elif name == "Sir Lancelot":
    print("What is your favourite color?")
else:
    print("Run! It's the Legendary Black Beast of Aaarrgh!")

while

connected = False

while not connected:
    print("Trying...")
    connected = retry()

print("We're now connected")

for

for n in range(12, 22):
    if 2 * 7 == n:
        print("Middle brother")
    else:
        print("Sad unicorn")    

break/continue

for age in range(1, 10000):
    if age > 169:
        print("You reached super-human limits!")
        break
    if age % 17 == 1:
        print("So lucky!")
        continue
    print("So ordinary my leg hurts.")

факториел

def f(n):
    if n <= 1:
        return 1
    return n*f(n-1)

Колекции в Python

Списъци

Списъци (2)

["Lancelot", ["Ni!", 8, []], "Pidgeon"]

Да си направим списък

>>> actor = "Eric Idle"
>>> sketch = "Spam"
>>> stuff = [actor, 42, sketch]
>>> print(stuff)
['Eric Idle', 42, 'Spam']

Операции със списъци (1)

>>> len(["Foo", "Bar", "Baz", "Qux"])
4

Операции със списъци (2)

>>> [1, 2] + [3, 4]
[1, 2, 3, 4]

Операции със списъци (3)

>>> "Spam" in ["Eggs", "Bacon", "Spam"]
True

Операции със списъци (4)

>>> "Spam" not in ["Eggs", "Bacon", "Spam"]
False

Индексиране и рязане на списъци

>>> cheese = ['Red Leicester', 'Cheddar', 'Emmental', 'Mozzarella', 'Tilsit', 'Limburger']
>>> cheese[0]
'Red Leicester'
>>> cheese[-1]
'Limburger'
>>> cheese[1:4]
['Cheddar', 'Emmental', 'Mozzarella']
>>> cheese[1:-1]
['Cheddar', 'Emmental', 'Mozzarella', 'Tilsit']
>>> cheese[1:]
['Cheddar', 'Emmental', 'Mozzarella', 'Tilsit', 'Limburger']
>>> cheese[:3]
['Red Leicester', 'Cheddar', 'Emmental']
>>> cheese[0:6:2]
['Red Leicester', 'Emmental', 'Tilsit']
>>> cheese[::2]
['Red Leicester', 'Emmental', 'Tilsit']
>>> cheese[::-1]
['Limburger', 'Tilsit', 'Mozzarella', 'Emmental', 'Cheddar', 'Red Leicester']

Промяна на списъци

>>> food = ['eggs', 'bacon', 'spam']
>>> print(food)
['eggs', 'bacon', 'spam']
>>> food[1] = 'sausage'
>>> print(food)
['eggs', 'sausage', 'spam']
>>> food.append('spam')
>>> print(food)
['eggs', 'sausage', 'spam', 'spam']
>>> food.append(['манджа', 'грозде'])
>>> print(food)
['eggs', 'sausage', 'spam', 'spam', ['манджа', 'грозде']]
>>> del food[4]
>>> print(food)
['eggs', 'sausage', 'spam', 'spam']

Интересни методи на списъците

>>> knights = ["Arthur", "Galahad"]
>>> knights.append('Bedevere')
>>> knights
['Arthur', 'Galahad', 'Bedevere']
>>> knights.extend(['Lancelot', 'Robin']) # Може и knigts += ['Lancelot', 'Robin']
>>> knights
['Arthur', 'Galahad', 'Bedevere', 'Lancelot', 'Robin']
>>> knights.sort()
>>> knights
['Arthur', 'Bedevere', 'Galahad', 'Lancelot', 'Robin']
>>> knights.reverse()
>>> knights
['Robin', 'Lancelot', 'Galahad', 'Bedevere', 'Arthur']
>>> someone = knights.pop()
>>> print(someone, knights)
Arthur ['Robin', 'Lancelot', 'Galahad', 'Bedevere']
>>> someone = knights.pop(2)
>>> print(someone, knights)
Galahad ['Robin', 'Lancelot', 'Bedevere']

Хайде пак малко за for

for ⟨име⟩ in ⟨нещо-за-обхождане⟩:
    ⟨блок код⟩

Обхождане на списъци

>>> numbers = [1, 2, 3, 5, 7, 11, 13]
>>> answer = 0
>>> 
>>> for n in numbers:
        answer += n
>>> print(answer)
42

Ние нали ви казахме, че става лесно?

Имена и обекти

>>> spam = ['Lancelot', 'Arthur']
>>> eggs = spam
>>> eggs[1] = 'Bedevere'
>>> spam
['Lancelot', 'Bedevere']

Нищо

В Python нищото е None

>>> print(None)
None
>>> 1 is None
False
>>> if not None:
        print('None is treated as "False"')
None is treated as „False“

Още въпроси?