- Python
- Types
- Operators
- Conditions
- Cycles
- Functions
- Exceptions
- Posible exceptions
- Use
try-exceptconstruction to handle exception - You can write keyword
passto do nothing - You can except only defined exceptions
- You can defined several except blocks
- You can except several exception_names
SyntaxErrorandIndentationErrorFinally- Raise your exceptions
- To
raiseexception withoutexcept - To see exception in
try-exceptconstruction - To create your own exception
AssertionError
- Work with files
- Modules
- String formatting
- Additional funcs
foo = True
bar = Falsefoo = 'text'
# return string
str(0) # '0'# return int
int('0') # 4# return float
float('0') # 0.0Just none ( False )
Functions without return type returns 'None'
def foo():
print('foo body')
bar = foo()
print(bar) # Nonefoo = [0, 1, 2, 3, [4, 5, 6]]
print(foo[4][0]) # 4foo = [1, 2, 3]
print(foo * 2) # [1, 2, 3, 1, 2, 3]
print(foo + [4, 5, 6]) # [1, 2, 3, 4, 5, 6]foo = 'Hello'
print(foo[4]) # ofoo = ['John', 'Mike', 'Alex']
if 'Alex' in foo:
print('Alex in list')
if 'Samuel' not in foo:
print('Samuel is not in list')foo = []
foo.append('Hello')
foo.append(0)
foo.append([1, 2, 3])
print(foo) # ['Hello', 0, [1, 2, 3]]foo = [1, 2, 3, 4, 5]
print('count: ' + str(len(foo))) # count: 5foo.remove(5)
print('count: ' + str(len(foo))) # count: 4foo.insert(0, 6)
print('count: ' + str(len(foo))) # count: 5
print(foo) # [6, 1, 2, 3, 4]print('max: ' + str(max(foo))) # max: 6
print('min: ' + str(min(foo))) # min: 1foo = [1, 1, 0, 2, 0, 2, 2, 0, 3, 4, 6, 0, 6, 7, 8, 0, 9, 9, 0, 0]
print('count: ' + str(foo.count(0))) # count: 7foo = [1, 2, 3, 4, 5]
foo.reverse()
print(foo) # [5, 4, 3, 2, 1]array = list(range(10)) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
array = list(range(50, 60)) # [50, 51, 52, 53, 54, 55, 56, 57, 58, 59]
array = list(range(0, 10, 2)) # [0, 2, 4, 6, 8]foo = [1, 2, 3, 4, 5]
foo[-2] # 4foo = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
foo[<start_index>:<end_index>:<step>]
foo[<start_index>:]
foo[:<end_index>]
foo[::<step>]foo = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
bar = foo[2:5] # [3, 4, 5]foo = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
bar = foo[:5] # [1, 2, 3, 4, 5]foo = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
bar = foo[5:] # [6, 7, 8, 9, 0]foo = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
bar = foo[::2] # [1, 3, 5, 7, 9]foo = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
bar = foo[-4:-1] # [7, 8, 9]foo = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
bar = foo[::-1] # [0, 9, 8, 7, 6, 5, 4, 3, 2, 1]Syntax:
{
simple_type: any_type
}
simple_type: Int, Float, String
any_type: ...Example:
foo = {
'key_1': 'value_1',
'key_2': 'value_2'
}value = foo['key_1']
print(value) # value_1if <key> in <dict>:
do stuff<dict>.get('key')
return 'None' if key not exist<dict>.get('key', '<return_value>')
<return_value> - will return if key not exist# Tuple - immutable list
foo = (1, 2, 3)
foo[0]# You can define tuple without `(`, `)`
foo = 1, 2, 3
foo[0]foo = 0
del foo
print(foo) # 'foo' is note defined+= -= *= /= %=== != > < >= <=Case of letters does not affect the weight.
string_1 = 'Test' # 64, 20 + 5 + 19 + 20
string_2 = 'Tesa' # 45, 20 + 5 + 19 + 1
print(string_1 > string_2) # Trueif else elif
and orif <condition>:
do stuffif <condition>:
do stuff
else:
do other stuffif <condition>:
do stuff
elif <condition>:
do other stuffif <condition_1> and <condition_2>:
do stuffif <condition_1> or <condition_2>:
do stuffif <condition_1> and (<condition_2> or <condition_3>):
do stuff# not
if not <condition>:
do stuffSyntax:
while <condition>:
# do stuffExample:
foo = 0
while foo < 10:
print('Current foo: ' + str(foo))
foo += 1array = [1, 2, 3, 4, 5]
for value in array:
# do stufffor _ in range(10):
# do stuff, will called 10 timesfor value in range(10):
print(value) # 0123456789 one value on each callwhile <condition_1>:
# do stuff
if <condition_2>:
breakwhile True:
print('Current foo: ' + str(foo))
foo += 1
if foo == 101:
breakwhile <condition_1>:
# do stuff
if <condition_2>:
continue
# do stuffSyntax:
def <fuction_name>(<arg_name_1>, <arg_name_...>):
# do stuff, can use arg_name_1, arg_name_...
# can return somethingExample:
def max(x, y):
if x > y:
return x
else:
return ySyntax:
<function_name>(<parameter_value_1, parameter_value_...>)Example:
max(5, 10)def function_name():
''' Function description '''
# do stufffunction_name.__doc__ # Function descriptiondef function():
print('Called function')
var_func = function
var_func() # Called functiondef print_hello(name):
print('Hello ' + name + '!')
def read_name():
return ':::' + input('Enter your name: ') + ':::'
print_hello(read_name())def print_hello(name):
print('Hello ' + name() + '!')
def read_name():
return ':::' + input('Enter your name: ') + ':::'
print_hello(read_name)- ImportError - wrong import
- IndexError - index out of range
- NameError - variable is not defined
- SyntaxError - syntax
- TypeError - invalid argument type
- ValueError - invalid argument value
- ZeroDivisionError - division by zero
- AssertionError - assert
try:
do stuff
except:
do stufftry:
pass
except:
passtry:
do stuff
except <exception_name>:
do stufftry:
do stuff
except <exception_name>:
do stuff
except <exception_name>:
do stufftry:
do stuff
except (<exception_name>, <exception_name>):
do stuffTo catch these exceptions, you must use the eval function
try:
eval('do stuff')
except SyntaxError:
Here 'SyntaxError' exception
except IndentationError:
Here 'IndentationError' exceptionFinally stuff will be always executed
try:
do stuff
except <exception_name>:
do stuff
finally:
do stuffYou can except yours exceptions by keyword raise
try:
if True:
raise <error>
except <error>:
do stuffDon't use the 'try-except' construction
raise <error>('description')Just make raise in except block
try:
stuff with exception
except:
some stuff
raiseclass MyOwnExceptionError(Exception):
some stuff
raise MyOwnExceptionError
or
raise MyOwnExceptionError('description')assert <condition>, 'assert description'
assert text != ''Syntax:
open('<file_path>', '<read_mode>')- r - read
- w - write
- a - append
- b - binary
file = open('files.txt', 'r')
print(file.read())file.close()file_len = len(file.read())1 symbol = 1 byte in UTF-8
Syntax:
file.read(<bytes>)Example:
file.read(2) # will read 2 bytes from beginfile.read(2) # will read 2 bytes from begin
file.read(2) # will read 2 bytes from previous stop placeIf in the next step you user .read func without argument will read all remaining content.
file.read(2) # will read 2 bytes from begin
file.read() # will read all remaining contentUse method readlines()
strings = file.readlines()If file does not exist, it will be create If file exist, it will be delete and create again All content will be deleted
Syntax:
file.write('<file_content>')Syntax:
<file>.write('<content>')
file.write('some text')All media content needs binary mode Binary mode work not only with media content You can work with .txt or any files in binary mode
Syntax:
open('<file>', <mode>)
<mode> = rb, wb, abExample:
open('file_name.png', 'rb')You don't need to close file
with open('<file_name>', 'r') as f:
f.read()
f.read() # ValueError exceptionSTL - Standart library Three types of module
- Your modules
- Import modules
- Modules integrated to python (random, math, os, json, sys)
PyPi - modules by other peoples
To install packages use pip3 console utility
Syntax:
import <module name>Example:
import random
random.randint(0, 100) # random number 0 - 100
import math
math.sqrt(25)import <module_name> as my_module_name
import math as m
m.sqrt(25)from <module_name> import <object_name>, <object_name>
from random import randint
from math import sqrt, pi
randint(0, 100) # random number 0 - 100
sqrt(25)from <module_name> import *
* - means allfrom <module_name> import <object_name> as my_object_name
from math import sqrt as my_sqrt
my_sqrt(25)To use module methods, just write method name
randint(0, 100) # random number 0 - 100
sqrt(25)- %s - string
- %d - int
- %f - float
foo = '<string_value>'
bar = <int_value>
baz = '%s, %d' % (foo, bar) # 'string_value, int_value'foo = '<string_value>'
bar = <int_value>
baz = '{}, {}'.format(foo, bar) # 'string_value, int_value'foo = '<string_value>'
bar = <int_value>
baz = '{0}, {1}, {0}'.format(foo, bar) # 'string_value, int_value, string_value'foo = '<string_value>'
bar = <int_value>
baz = '{foo_index}, {bar_index}'.format(foo_index = foo, bar_index = bar) # 'string_value, int_value'foo = {
'bar': 'bar_value',
'baz': 'baz_value'
}
res = '{foo[bar]}, {foo[baz]}'.format(foo = foo) # bar_value, baz_value- ^ - center
- < - right filling
-
- left filling
foo = 'FOO'
'{0:_^11}'.format(foo) # ____FOO____
'{0:_<11}'.format(foo) # FOO________
'{0:_>11}'.format(foo) # ________FOO# Auto filling with alignment
import string
def correct_lenth(str, attr):
return len(str) + (attr * 2)
def random_letters():
letters = string.ascii_letters
output = []
for index in range(len(letters)):
output.append(letters[:index])
return output
for letter in random_letters():
lenth = correct_lenth(letter, 5)
output = '{0:*^{lenth}}'.format(letter, lenth)
print(output)foo = ['one', 'two', 'three]
bar = ', '.join(foo) # one, two, threefoo = '<string_value>'
bar = foo.replace('<string_value>', '<replacement_value>') # replacement_value