Когато не сте сигурни, просто пробвайте.
$ python
>>> 5 + 10
15
>>> a = 5
>>> b = a + 10
>>> print(b)
15
>>> a * 2
10
>>> a ** 2
25
>>> "hello" + ', ' + "world"
"hello, world"
В интерактивната конзола, help() показва документацията на всяка функция, клас или тип.
>>> help(str)
>>> help(5)
>>> help(SomeClass)
>>> help(some_function)
my_var = 'spam'.upper()
print(my_var) # SPAM
>>> "hello".upper()
"HELLO"
>>> len("абвгдеж")
7
>>> "hello"[1]
"e"
>>> help(str)
>>> type(5.5)
<class 'float'>
>>> type(type)
<class 'type'>
>>> type(type(type(type)))
<class 'type'>
а = 5
type(a) # <class 'int'>
a = 'test'
type(a) # <class 'str'>
my_list = []
my_list = list()
my_list = []
my_list.append('word')
my_list.append(5)
my_list.append(False)
my_list[1] == 5
my_other_list = ['foo', 'bar', 'quux']
len(my_other_list) # 3
del my_other_list[1]
print(my_other_list) # ['foo', 'quux']
'foo' in my_other_list # True
False in my_list # True
ages = {'Кай': 1, 'Бобо': 2}
ages['Йоан'] = 25
ages['Алек'] = 25
ages['Кирил'] = 22
ages['Николай'] = 27
print(ages['Кирил']) # 22
'Николай' in ages # True
ages.get('Георги') # None
ages.get('Георги', 'няма такъв') # няма такъв
>>> args = (9.8, 3.14, 2.71)
>>> args[2]
2.71
>>> args[1] = 22/7
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> unique_numbers = {2,3,5,6}
>>> unique_numbers
{2, 3, 5, 6}
>>> unique_numbers.add(5)
>>> unique_numbers
{2, 3, 5, 6}
>>> unique_numbers.remove(5)
>>> unique_numbers
{2, 3, 6}
>>> my_list = [5,1,6,6,2,3,5,5]
>>> set(my_list)
{1, 2, 3, 5, 6}
a = 5
a += 2 # 7
a = [1,2,3]
a.append(4)
if a == 5:
print("a is five")
elif a == 3 and not b == 2:
print("a is three, b is not two")
else:
print("a is something else")
Булеви тестове:
a = True
if a:
print("a is True")
if not a:
print("a is not True")
тестове за принадлежност:
my_list = [1, 2, 3, 4]
if 1 in my_list:
print('1 is in my list')
if 5 not in my_list:
print('5 is not in my list')
while a > 5:
a -= 1
print("a is %d" % a)
primes = [3,5,7,11]
for e in primes:
print(e ** 2) # prints 9 25 49 121
people = {'bob': 25, 'john': 22, 'mitt': 56}
for name, age in people:
print("{} is {} years old".format(name, age))
# bob is 25 years old
# john is 22 years old
# ...
for i in range(0, 20):
print(i)
# 0 1 2 3 4 5 6 .. 19
for i in range(0, 20, 3):
print(i)
# 0 3 6 9 12 15 18
Няма.
def say_hello(name, from):
return "Hello, {}! -- {}".format(name, from)
def multiply(a, b=2):
return a * b
multiply(5) # 10
multiply(5, 10) # 50
def is_pythagorean(a=2, b=3, c=4):
return a * a + b * b == c * c
is_pythagorean(b=5) # a = 2, c = 4
is_pythagorean(1, c=3) # a = 1, b = 3
def varfunc(some_arg, *args, **kwargs):
#...
varfunc('hello', 1,2,3, name='Bob', age=12)
# some_arg == 'hello'
# args = (1,2,3)
# kwargs = {'name': 'Bob', 'age': 12}