Позволява изпълняването на малки парчета код, без да се налага да пишете цели програми
>>> 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: {0}".format(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>", line 1, in <module>
NameError: name 'question' is not defined
Основни типове в Python
int
float
, complex
str
bool
1
42
-42
999999
999999999999999999
-999999999999999999
float
— 1. 0.314е1 217Е-2
decimal
fractions
complex
— 0+1j complex(1,2) 3.0+4.0j
+
), изваждане (−
), умножение (*
)/
), целочислено деление (//
), деление с остатък (%
)**
)<<
, >>
, &
, |
, ^
, ~
>>> 6 * 7
42
>>> 10 / 3
3.3333333333333335
>>> 10.0 / 3
3.3333333333333335
>>> 10.0 // 3
3.0
>>> 10 % 3
1
>>> 2 ** 31 -1
2147483647
>>> 1j * 1j
(-1+0j)
str
"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"""
"Не използвайте 6lyokavica!"
r'C:\Program Files\Python'
"Subsequent " 'literals ' r'are ' """concatenated."""
bool
- True
False
True
и False
са други имена на 1
и 0
True + True
връща 2
True
и False
— така кодът се чете по-лесноand
, or
и not
работят точно както очаквате==
и !=
също действат както очаквате."Foo" == 'Foo'
връща True
6 * 9 == 42
връща False
<
и >
са оператори за сравнение"Perl" < "Python"
връща True
"Bar" < "Baz" < "Foo"
връща True
"Bar" < "Baz" and "Baz" < "Foo"
<=
и >=
версии20 < "Foo"
гърми.Класическо:
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]
[условие]? [израз1] : [израз2]
print("We're connected" if connected 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 - {0} times left...".format(retries))
if connected:
print("Connected successfully")
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 - {0} times left...".format(retries))
else:
print("Failed :(")