Позволява изпълняването на малки парчета код, без да се налага да пишете цели програми
>>> 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
name = "Guido"
familyName = "van Rosum"
print "Welcome, " + name + " " + familyName + " to Python!"
python hello.py
answer = 42
answer = "Fourty two"print question
Traceback (most recent call last):
File "<stdin%gt;", line 1, in <module>
NameError: name 'question' is not definedОсновни типове в Python
int, longfloat, complexstr, unicodebool1 42 256 123454321L
int — с големината на думата на процесораlong — колкото може да побере оперативната ви паметint към long става автоматично при препълванеint или longfloat — 1. 0.314е1 217Е-2
decimalcomplex — 0+1j complex(1,2) 3.0+4.0j
+), изваждане (−), умножение (*)/), целочислено деление (//), деление с остатък (%)
**)<<, >>, &, |, ^, ~
>>> 6 * 7
42
>>> 10 / 3
3
>>> 10 % 3
1
>>> 10.0 // 3
3.0
>>> 10.0 / 3
3.3333333333333335
>>> 2 ** 31 -1
2147483647
>>> 1j * 1j
(-1+0j)
strunicode"spam and eggs" 'larodi'\\ \' \" \a \b \f \n \r \t \v
"""This is heredoc"""r'C:\"Windows"\regedit.exe' и r"(bb|[^b]{2})|\d+"
"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."""
bool - True FalseTrue и False са други имена на 1 и 0True + True връща 2True и False - така кодът се чете по-лесноand, or и not работят точно както очаквате== и != също действат както очаквате."Foo" == 'Foo' връща True6 * 9 == 42 връща False<>, но той е остаряла версия на != и не се препоръчва< и > са оператори за сравнение"Perl" < "Python" връща True"Bar" < "Baz" < "Foo" връща True"Bar" < "Baz" and "Baz" < "Foo"<= и >= версии20 < "Foo" връща True.Класическо:
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"
:if hungry: print "We should go get some food"
pass:
if something:
pass
else:
print "Else happened!"
not something. pass има някои смислени приложения при изключения и класове, но за това - по-натамЦялостен пример:
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. Може би в следващата версия :(
[израз1] if [условие] else [израз2]
print "We're connected" if conntected else ":("
Отново, while цикълът в Python е съвсем класически:
while not connected:
print "Trying..."
connected = retry()
print "We're now connected"
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"
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 :("