Skip to content

Latest commit

 

History

History
1024 lines (770 loc) · 16.8 KB

File metadata and controls

1024 lines (770 loc) · 16.8 KB

Python

Types

Boolean

foo = True
bar = False

String

foo = 'text'

# return string
str(0) # '0'

Int

# return int
int('0') # 4

Float

# return float
float('0') # 0.0

None (NULL)

Just none ( False )

Functions without return type returns 'None'

def foo():
  print('foo body')
bar = foo()
print(bar) # None

Lists

foo = [0, 1, 2, 3, [4, 5, 6]]
print(foo[4][0]) # 4
foo = [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]) # o

Keywords if in and if not in

foo = ['John', 'Mike', 'Alex']
if 'Alex' in foo:
  print('Alex in list')

if 'Samuel' not in foo:
  print('Samuel is not in list')

append

foo = []
foo.append('Hello')
foo.append(0)
foo.append([1, 2, 3])
print(foo) # ['Hello', 0, [1, 2, 3]]

len

foo = [1, 2, 3, 4, 5]
print('count: ' + str(len(foo))) # count: 5

remove

foo.remove(5)
print('count: ' + str(len(foo))) # count: 4

insert

foo.insert(0, 6)
print('count: ' + str(len(foo))) # count: 5
print(foo) # [6, 1, 2, 3, 4]

max, min

print('max: ' + str(max(foo))) # max: 6
print('min: ' + str(min(foo))) # min: 1

count

foo = [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: 7

reverse

foo = [1, 2, 3, 4, 5]
foo.reverse()
print(foo) # [5, 4, 3, 2, 1]

list, range

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]

Negative index

foo = [1, 2, 3, 4, 5]
foo[-2] # 4

List indexing (Chunk)

foo = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
foo[<start_index>:<end_index>:<step>]
foo[<start_index>:]
foo[:<end_index>]
foo[::<step>]
Get chunk
foo = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
bar = foo[2:5] # [3, 4, 5]
Get chunk to some index
foo = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
bar = foo[:5] # [1, 2, 3, 4, 5]
Get chunk from some index
foo = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
bar = foo[5:] # [6, 7, 8, 9, 0]
Get chunk with step
foo = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
bar = foo[::2] # [1, 3, 5, 7, 9]
Get chunk with negative indexes
foo = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
bar = foo[-4:-1] # [7, 8, 9]
Get chunk with negative step (reverse step)
foo = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
bar = foo[::-1] # [0, 9, 8, 7, 6, 5, 4, 3, 2, 1]

Dictionary

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_1

Check if key in dictionary

if <key> in <dict>:
  do stuff

Keyword get

<dict>.get('key')
return 'None' if key not exist
<dict>.get('key', '<return_value>')
<return_value> - will return if key not exist

Tuple

# Tuple - immutable list
foo = (1, 2, 3)
foo[0]
# You can define tuple without `(`, `)`
foo = 1, 2, 3
foo[0]

Operators

Delete variable

foo = 0
del foo
print(foo) # 'foo' is note defined

In-place operators

+= -= *= /= %=

Comparison

== != > < >= <=

Lexicographic comparison

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) # True

Conditions

if else elif
and or
if <condition>:
  do stuff
if <condition>:
  do stuff
else:
  do other stuff
if <condition>:
  do stuff
elif <condition>:
  do other stuff
if <condition_1> and <condition_2>:
  do stuff
if <condition_1> or <condition_2>:
  do stuff
if <condition_1> and (<condition_2> or <condition_3>):
  do stuff
# not
if not <condition>:
  do stuff

Cycles

Cycle while

Syntax:

while <condition>:
  # do stuff

Example:

foo = 0
while foo < 10:
  print('Current foo: ' + str(foo))
  foo += 1

Cycle for-in

array = [1, 2, 3, 4, 5]
for value in array:
  # do stuff
for _ in range(10):
  # do stuff, will called 10 times
for value in range(10):
  print(value) # 0123456789 one value on each call

Keyword break

while <condition_1>:
  # do stuff
if <condition_2>:
  break
while True:
  print('Current foo: ' + str(foo))
  foo += 1

  if foo == 101:
    break

Keyword continue

while <condition_1>:
  # do stuff
  if <condition_2>:
    continue
  # do stuff

Functions

Define function

Syntax:

def <fuction_name>(<arg_name_1>, <arg_name_...>):
  # do stuff, can use arg_name_1, arg_name_...
  # can return something

Example:

def max(x, y):
  if x > y:
    return x
  else:
    return y

Call function

Syntax:

<function_name>(<parameter_value_1, parameter_value_...>)

Example:

max(5, 10)

Docstrings

def function_name():
  ''' Function description '''
  # do stuff

Print function docstring

function_name.__doc__ # Function description

Save function to variable

def function():
  print('Called function')

var_func = function
var_func() # Called function

Send result of function as argument

def print_hello(name):
  print('Hello ' + name + '!')

def read_name():
  return ':::' + input('Enter your name: ') + ':::'

print_hello(read_name())

Send function as argument

def print_hello(name):
  print('Hello ' + name() + '!')

def read_name():
  return ':::' + input('Enter your name: ') + ':::'

print_hello(read_name)

Exceptions

Posible exceptions

  • 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

Use try-except construction to handle exception

try:
  do stuff
except:
  do stuff

You can write keyword pass to do nothing

try:
  pass
except:
  pass

You can except only defined exceptions

try:
  do stuff
except <exception_name>:
  do stuff

You can defined several except blocks

try:
  do stuff
except <exception_name>:
  do stuff
except <exception_name>:
  do stuff

You can except several exception_names

try:
  do stuff
except (<exception_name>, <exception_name>):
  do stuff

SyntaxError and IndentationError

To catch these exceptions, you must use the eval function

try:
  eval('do stuff')
except SyntaxError:
  Here 'SyntaxError' exception
except IndentationError:
  Here 'IndentationError' exception

Finally

Finally stuff will be always executed

try:
  do stuff
except <exception_name>:
  do stuff
finally:
  do stuff

Raise your exceptions

You can except yours exceptions by keyword raise

try:
  if True:
      raise <error>
except <error>:
  do stuff

To raise exception without except

Don't use the 'try-except' construction

raise <error>('description')

To see exception in try-except construction

Just make raise in except block

try:
  stuff with exception
except:
  some stuff
  raise

To create your own exception

class MyOwnExceptionError(Exception):
  some stuff
raise MyOwnExceptionError
or
raise MyOwnExceptionError('description')

AssertionError

assert <condition>, 'assert description'
assert text != ''

Work with files

Syntax:

open('<file_path>', '<read_mode>')

Modes

  • r - read
  • w - write
  • a - append
  • b - binary

Read

file = open('files.txt', 'r')
print(file.read())
After open file, you need to close it
file.close()
To read length
file_len = len(file.read())
To read not full content

1 symbol = 1 byte in UTF-8

Syntax:

file.read(<bytes>)

Example:

file.read(2) # will read 2 bytes from begin
Offset, if you continue read file
file.read(2) # will read 2 bytes from begin
file.read(2) # will read 2 bytes from previous stop place

If 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 content
To read line to line

Use method readlines()

strings = file.readlines()

Write

If file does not exist, it will be create If file exist, it will be delete and create again All content will be deleted

To write content to file

Syntax:

file.write('<file_content>')

Append

Syntax:

<file>.write('<content>')
file.write('some text')

Binary

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, ab

Example:

open('file_name.png', 'rb')

Keyword with

You don't need to close file

with open('<file_name>', 'r') as f:
    f.read()
f.read() # ValueError  exception

Modules

STL - 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 as

import <module_name> as my_module_name
import math as m
m.sqrt(25)

from module import

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 all

from module import as

from <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)

String formatting

  • %s - string
  • %d - int
  • %f - float

Keyword %

foo = '<string_value>'
bar = <int_value>
baz = '%s, %d' % (foo, bar) # 'string_value, int_value'

.format()

foo = '<string_value>'
bar = <int_value>
baz = '{}, {}'.format(foo, bar) # 'string_value, int_value'

.format() with indexes

foo = '<string_value>'
bar = <int_value>
baz = '{0}, {1}, {0}'.format(foo, bar) # 'string_value, int_value, string_value'

.format() with name indexes/arguments

foo = '<string_value>'
bar = <int_value>
baz = '{foo_index}, {bar_index}'.format(foo_index = foo, bar_index = bar) # 'string_value, int_value'

.format() with name from dictionary

foo = {
    'bar': 'bar_value',
    'baz': 'baz_value'
}
res = '{foo[bar]}, {foo[baz]}'.format(foo = foo) # bar_value, baz_value

.format() with auto filling

  • ^ - 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)

Additional funcs

join

foo = ['one', 'two', 'three]
bar = ', '.join(foo) # one, two, three

replace

foo = '<string_value>'
bar = foo.replace('<string_value>', '<replacement_value>') # replacement_value

startswith

endswith

lower

upper

split

min

max

abs

sum