Python podsetnik¶
Ukratko ćemo se podsetiti na osnovne elemente Python programskog jezika. Za one koji se prvi put sreću sa Python-om preporučujem da prođu kroz predavanja u Osnove programiranja u Python jeziku, ili neki tutorial kao što je W3School Python.
Podaci u Pythonu¶
Varijable¶
Vrijable nisu ništa drugo do rezervisane memorijske lokacije u koje se smeštaju vrednosti. Tim lokacijama se daju imena (imena varijabli). Varijablama se dodeljuje vrednost naredbama za pridruživanje, kao u sledećem primeru:
v = 8 + 2*(100 - 6)
Pravila za davanje imena varijablama:
- Moraju početi sa slovom ili donjom crtom (_), ne mogu počinjati cifrom
- Mogu sadržati sam alfa-numeričke karaktere i donju crtu (A-z, 0-9, and _ )
- Razlikuju mala i velika slova (Case-sensitive)
Osnovni tipovi podataka¶
1, 23, 3493 # int - dekadni brojevi
0o1, 0o27, 0o6645 # oct - oktalni brojevi
0x1, 0x17, 0xDA5 # hex - heksadecimalni brojevi
0b1011, 0b10101010 # bin - binary brojevi
1.2, 0.08, 2.7e-8, 0.5e10 # float - decimalni brojevi
4.5 + 7.2j, 0.5e3+0.3e-2j # complex - kompleksni brojevi
True, False # bool - Bulovske vrednosti
'abcd', "abcd", """abcd""" # str - stringovi
b'\xd8\xe1\xb7\xeb\xa8\xe5' # bytes - niz bajtova
None # specijana vrednost
Operatorori¶
+, -, *, /, //, % # Aritmetičke operacija
==, >,<, <>, !=,>=, <, <= # Operacije poređenja
<<, >>, &, |, ~, ^ # Operacije sa bitovima:
not, and, or # Logičke operacija
in, not in, del # Dodatne operacije
Bibliotečke funkcije¶
Built-in funkcije:
abs, all, any, ascii, bin, bool, breakpoint, bytearray, bytes, callable, chr,
classmethod, compile, complex, copyright, credits, delattr, dict, dir, divmod,
enumerate, eval, exec, exit, filter, float, format, frozenset, getattr, globals,
hasattr, hash, help, hex, id, input, int, isinstance, issubclass, iter, len,
license, list, locals, map, max, memoryview, min, next, object, oct, open, ord,
pow, print, property, quit, range, repr, reversed, round, set, setattr, slice,
sorted, staticmethod, str, sum, super, tuple, type, vars, zip
String metode:
capitalize, casefold, center, count, encode, endswith,expandtabs, find, format,
format_map, index, isalnum, isalpha, isdecimal, isdigit, isidentifier, islower,
isnumeric, isprintable, isspace, istitle, isupper, join, ljust, lower, lstrip,
maketrans, partition, replace, rfind, rindex, rjust, rpartition, rsplit, rstrip,
split, splitlines, startswith, strip, swapcase, title, translate, upper, zfill
Modul math:
acos, acosh, asin, asinh, atan, atan2, atanh, ceil, copysign, cos, cosh, degrees,
e, erf, erfc, exp, expm1, fabs, factorial, floor, fmod, frexp, fsum, gamma, hypot,
isinf, isnan, ldexp, lgamma, log, log10, log1p, modf, pi, pow, radians, sin, sinh
Strukture podataka¶
Liste¶
[1, 2, 3, 4, ...] - mutable
len, in, indexing, slicing, +, * # Operacije
append, clear, copy, count, extend, index, insert, pop, remove, reverse, sort #Metode
Tuplovi¶
(1, 2, 3,...) - imutable
len, in, indexing, slicing, +, * # Operacije
index, count # Metode
Rečnici (dictionary)¶
{key1: data1, key2: data2, ...} # Mutable
len, in, index # Operacije
clear, copy, get, items, keys, pop, update,values #Metode
Skupovi¶
{a, b, c, d, ... } # Mutable
|, &, -, ^ # Operacije
add, clear, copy, difference, discard, intersection, # Metode
issuperset, isdisjoint, issubset, pop, remove,
symetric_difference, union, update
Kontrolne strukture¶
Pridruživanje (assignment)¶
variable_name = expression
v1,v2,...,vn = e1,e2,...,en
x, y, z = y, z, x
x=y=z=e
Iteracija (petlja, loop)¶
for element in sequence :
statement(s)
while test_expression :
statement(s)
else, finally
pass, break, continue
Selekcija (if naredba)¶
if test_expression :
statement(s)
elif test_expression :
statement(s)
...
elif test_expression :
statement(s)
else :
statement(s)
Definisanje funkcije¶
def function_name(parameters):
""" Doc string """
statement(s)
return (yield) value
Definisanje klase¶
class class_name:
def __init__(self,parameters):
statement(s)
def method_name(self,parameters):
statement(s)
Izuzeci (Exceptions)¶
try:
statement(s)
except:
statement(s)
finally:
statement(s)
raise Exception('Error message')
Potvrde (Assertions)¶
assert condition
assert condition, error_message
Ulaz/Izlaz (input/print)¶
input variable_name = input(poruka)
print print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
Fajlovi (files)¶
open file = open(filename, mode) # mode: r, w, a, r+, b, t
read file.read(), file.readline(number_of_lines), file.readlines()
write file.write(“Hello World”)
close file.close()
with open(filename, mode) as file:
statement(s)
Modules¶
import module_name
from module_name import method_name as new_module_name
module_name.method_name(arguments)
Primer Python programa¶
Sledeći primer Python programa pokazuje razne načine korišćenja nezavisnih funkcija i metoda kao delova klase. Proučite primer, uočite i analizirajte sve specifičnosti definisanja i korišćenja metoda iz klase Zbir.
import math # importovanje modula
# Definisanje funkcija zbir
def zbir(a,b):
return a + b
# Definisanje klase Zbir
class Zbir():
def __init__(self,a=0,b=0):
self.a = a
self.b = b
self.rezultat = 0
def zbir(self): # metod zbir
self.rezultat = self.a + self.b
return self.rezultat
def sum(self,a,b): # metod sum
return a + b
@staticmethod # dekorator
def plus(a,b): # static metod plus
return a + b
# Glavni program (main)
a = 10
b = 90
z = a + b # bez poziva funkcije ili metode
print(a + b)
z = zbir(a,b) # poziv funkcije
print(z,math.sqrt(z))
objekat_zbir = Zbir(a,b) # kreiranje jednog objekta iz klase Zbir
z = objekat_zbir.zbir() # pozivanje metode zbir()
print(z,math.sqrt(z))
z = objekat_zbir.sum(20,5) # pozivanje metode sum()
print(z)
z = Zbir.plus(3,6) # pozivanje statičke metode plus()
print(z)