>>> word = "Ni!" >>> knights = "We Are The Knights Who Say" >>> print(knights, word) We Are The Knights Who Say Ni! >>> 2 * 2 4
whoami.py
:name = "Guido" print("Hello, I'm Python and", name, "created me!")
python whoami.py
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
int
(1
, -99
, 111111111111111111111111111111
)float
, complex
(2.71828
, 217e-2
, 3.0+4.0j
, complex(1,2)
)str
bool
+
), изваждане (−
), умножение (*
)/
), целочислено деление (//
), деление с остатък (%
)**
)<<
, >>
, &
, |
, ^
, ~
str
Unicode
„spam and eggs“, 'larodi'
\\ \' \" \a \b \f \n \r \t \v
>>> food = 'spam' >>> taste = "yum"
>>> "spam" == 'spam' True
>>> 'I can\'t taste your ' + food + ', can I?' >>> "Yes, you can't"
bool
— True
False
and
, or
и not
работят точно както очаквате==
и !=
също действат както очаквате.6 * 9 == 42
връща False
<
и >
са оператори за сравнение„Perl“ < „Python“
връща True<=
и >=
версии20 < 'Foo'
гърми с TypeError
:
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!")
connected = False while not connected: print("Trying...") connected = retry() print("We're now connected")
for n in range(12, 22): if 2 * 7 == n: print("Middle brother") else: print("Sad unicorn")
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)
["Lancelot", ["Ni!", 8, []], "Pidgeon"]
>>> actor = "Eric Idle" >>> sketch = "Spam" >>> stuff = [actor, 42, sketch] >>> print(stuff) ['Eric Idle', 42, 'Spam']
len(списък)
>>> len(["Foo", "Bar", "Baz", "Qux"]) 4
+
>>> [1, 2] + [3, 4] [1, 2, 3, 4]
in
>>> "Spam" in ["Eggs", "Bacon", "Spam"] True
not in
>>> "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 ⟨нещо-за-обхождане⟩: ⟨блок код⟩
in
е част от синтаксиса, не проверка за притежание⟨нещо-за-обхождане⟩
може да е както литерал — [1, 2, 3]
така и име, например knights
break
излиза от цикълаcontinue
прекъсва текущата итерация и продължава изпълнението на цикъла от следващия елемент>>> numbers = [1, 2, 3, 5, 7, 11, 13] >>> answer = 0 >>> >>> for n in numbers: answer += n >>> print(answer) 42
Ние нали ви казахме, че става лесно?
python
операторът =
дава ново име на съществуващ обект.>>> 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“