Основни типове и конструкции за управление

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

Стефан Кънев & Николай Бачийски & Димитър Димитров

27.02.2008г.

Python shell

Позволява изпълняването на малки парчета код, без да се налага да пишете цели програми


>>> animal = "Badger "
>>> print animal * 6
Badger Badger Badger Badger Badger Badger
>>> food = "Mushroom "
>>> print animal * 6 + food * 2
Badger Badger Badger Badger Badger Badger Mushroom Mushroom
>>> answer = 42
>>> print "The answer: %s" % answer
The answer: 42

Програми на python

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

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

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

Цели числа

float и complex

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

Операции с числа (2)


>>> 6 * 7
42
>>> 10 / 3
3
>>> 10.0 / 3
3.3333333333333335
>>> 10.0 // 3
3.0
>>> 10 % 3
1
>>> 2 ** 31 -1
2147483647
>>> 1j * 1j
(-1+0j)

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

Текстови низове (2)


"Hello world!"
'Quoth the Raven "Nevermore"'
"We don't have any \"cheese\", sir!"

"""Within "heredocs", we don't need
to escape single or double qoutes...
Or care about newlines"""

r'C:\Program Files\Python\'
"Subsequent " 'literals ' r'are ' """concatenated."""

Булеви данни

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

Булеви операции (2)

Конструкции за управление

Класическо:

if answer == 42:
    print "- We know the answer!"
    print "- Erm... what was the question again?"
else:
    print "Something went wrong. Let's try it again"

Две думи за блоковете в Python

Обратно към 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 Aaaaarrrrrrggghhh"

Не, в Python няма case. Може би в следващата версия :(

Троен if

while statement

Отново, while цикълът в Python е съвсем класически:


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

print "We're now connected"

break


retries = 3
connected = False

while retries:
	print "Trying to connect"
	connected = connect()

	if connected: break

	retries -= 1
	print "Failed. Trying again - %d times left..." % retries

if connected:
	print "Connected succesfully"
else:
	print "Failed miserably"

while... else?!


retries = 3
connected = False

while retries:
	print "Trying to connect"
	connected = connect()

	if connected: break

	retries -= 1
	print "Failed. Trying again - %d times left..." % retries
else:
	print "Failed :("