You are on page 1of 22

Python zhrnutie

Úvod
Python je populárny programovací jazyk, vytvoril ho Guido van Rossum a bol vydaný v roku
1991.
Používa sa na:
-serveri na vytváranie webových aplikácií
-spolu so softvérom na vytváranie pracovných postupov
-pripojenie k databázovým systémom. Dokáže tiež čítať a upravovať súbory
-spracovanie veľkých dát a vykonávanie komplexnej matematiky
-rýchle prototypovanie alebo na vývoj softvéru pripraveného na výrobu
Najnovšia hlavná verzia Pythonu je Python 3.
Syntax Pythonu v porovnaní s inými programovacími jazykmi
Python používa na dokončenie príkazu nové riadky, na rozdiel od iných programovacích
jazykov, ktoré často používajú bodkočiarky alebo zátvorky.
Python sa pri definovaní rozsahu spolieha na odsadenie pomocou medzier; ako je rozsah
slučiek, funkcií a tried. Iné programovacie jazyky na tento účel často používajú zložené
zátvorky.

Komentáre:
- na vysvetlenie kódu Python
- na zlepšenie čitateľnosti kódu
-na zabránenie spusteniu pri testovaní kódu
- začínajú znakom # a Python ich bude ignorovať:
#This is a comment

Premenné (Variables):
Premenné slúžia na uchovávanie hodnôt.
*Python nemá žiadny príkaz na deklarovanie premennej (deklarácia- v iných jazykoch, iba
vytvorenie premennej bez pridelenia hodnoty).
Premenná sa vytvorí v momente, keď jej prvýkrát priradíte hodnotu (definícia premennej-
keď premennej priradíme hodnotu).

Dátové typy:
int – integer - celé čísla, x = 20
float – desatinné čísla, x = 20.5
str – string – textový reťazec, x = "Hello World"
bool – boolean – hodnota True alebo False x = True
list – viacero položiek v jednej premennej x = ["apple", "banana", "cherry"]

Funkcie na pretypovanie - casting


int() – funkcia, ktorá pretypuje string alebo float na integer
float() – funckia, ktorá pretypuje na float
str() – funkcia, ktorá pretypuje na string

Zistenie dátového typu premennej:


type()
Python vám umožňuje priradiť hodnoty viacerým premenným v jednom riadku:

A rovnakú hodnotu môžete priradiť viacerým premenným v jednom riadku:

Globálne premenné:
Premenné, ktoré sú vytvorené mimo funkcie sú známe ako globálne premenné.
Globálne premenné môže používať každý, vo funkciách aj mimo nich.

Ak vo funkcii vytvoríte premennú s rovnakým názvom, táto premenná bude lokálna a možno
ju použiť iba vo funkcii. Globálna premenná s rovnakým názvom zostane ako bola s
pôvodnou hodnotou:

Stringy podrobnejšie:
Vieme pristúpiť k jednotlivým písmenám stringu, pomocou indexu
Prvé písmeno má index 0

Viacriadkový string:

”Rezanie stringov” -slicing strings:

Ak chcete vrátiť časť reťazca, zadajte počiatočný index a koncový index oddelené
dvojbodkou.
Negatívne indexovanie:

Úprava stringov

upper()- vráti string veľkými písmenami


lower()- vráti string malými písmenami
strip()- odstráni všetky medzery zo začiatku alebo konca
replace()- nahradí string iným stringom
spilt()- rozdelí reťazec na podreťazce, na základe inštancie separátora (zadáme znak na
základe ktorého bude rozdeľovať)

príklady použitia:
a = "Hello, World!"
print(a.upper())

a = "Hello, World!"
print(a.lower())

a = " Hello, World! "


print(a.strip()) # returns "Hello, World!"

a = "Hello, World!"
print(a.replace("H", "J")) # returns "Jello, World!"
a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']

Spájanie reťazcov(stringov):
a = "Hello"
b = "World"
c = a + " " + b
print(c)

Funkcia format:
-vieme pomocou nej vložiť čísla do stringu

age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))

quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))

quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))

Escape characters („escape znaky“)


Ak chceme do reťazca vložiť znaky, ktoré sú nepovolené, použijeme znak escape.
Znak escape je spätná lomka \, za ktorou nasleduje znak, ktorý chceme vložiť.

Príkladom nepovoleného znaku je dvojitá úvodzovka vo vnútri reťazca, ktorý je obklopený


dvojitými úvodzovkami:

txt = "We are the so-called \"Vikings\" from the north."


print(txt)
#returns We are the so-called "Vikings" from the north.

\‘ – single quote
\” – double quote
\n – new line
\\ - backslash
\t – tab
Prehľad string metód:
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
center() Returns a centered string
count() Returns the number of times a specified
value occurs in a string
encode() Returns an encoded version of the string
endswith() Returns true if the string ends with the
specified value
expandtabs() Sets the tab size of the string
find() Searches the string for a specified value and
returns the position of where it was found
format() Formats specified values in a string
format_map() Formats specified values in a string
index() Searches the string for a specified value and
returns the position of where it was found
isalnum() Returns True if all characters in the string
are alphanumeric
isalpha() Returns True if all characters in the string
are in the alphabet
isascii() Returns True if all characters in the string
are ascii characters
isdecimal() Returns True if all characters in the string
are decimals
isdigit() Returns True if all characters in the string
are digits
isidentifier() Returns True if the string is an identifier
islower() Returns True if all characters in the string
are lower case
isnumeric() Returns True if all characters in the string
are numeric
isprintable() Returns True if all characters in the string
are printable
isspace() Returns True if all characters in the string
are whitespaces
istitle() Returns True if the string follows the rules
of a title
isupper() Returns True if all characters in the string
are upper case
join() Joins the elements of an iterable to the end
of the string
ljust() Returns a left justified version of the string
lower() Converts a string into lower case
lstrip() Returns a left trim version of the string
maketrans() Returns a translation table to be used in
translations
partition() Returns a tuple where the string is parted
into three parts
replace() Returns a string where a specified value is
replaced with a specified value
rfind() Searches the string for a specified value and
returns the last position of where it was
found
rindex() Searches the string for a specified value and
returns the last position of where it was
found
rjust() Returns a right justified version of the string
rpartition() Returns a tuple where the string is parted
into three parts
rsplit() Splits the string at the specified separator,
and returns a list
rstrip() Returns a right trim version of the string
split() Splits the string at the specified separator,
and returns a list
splitlines() Splits the string at line breaks and returns a
list
startswith() Returns true if the string starts with the
specified value
strip() Returns a trimmed version of the string
swapcase() Swaps cases, lower case becomes upper
case and vice versa
title() Converts the first character of each word to
upper case
translate() Returns a translated string
upper() Converts a string into upper case
zfill() Fills the string with a specified number of 0
values at the beginning

Boolean:
Keď porovnávame dve hodnoty, výraz sa vyhodnotí a Python vráti boolovskú odpoveď:
print(10 > 9) #returns True
print(10 == 9) #returns False
print(10 < 9) #returns False

bool() - umožňuje vyhodnotiť akúkoľvek hodnotu a vráti hodnotu True alebo False
print(bool("Hello")) #returns True
print(bool(15)) #returns True
Takmer každá hodnota je vyhodnotená ako True, ak má nejaký obsah.
-Každý reťazec má hodnotu True, okrem prázdnych reťazcov.
-Každé číslo je pravda, okrem 0.
-Každý zoznam, n-tica, množina a slovník sú pravdivé, okrem prázdnych.
Python operátori
Aritmetické:
-používajú sa s číselnými hodnotami na vykonávanie bežných matematických operácií:
Priradenia:
Operátory priradenia sa používajú na priradenie hodnôt premenným:

Porovnávania:
Logické:

Identitné:

Členstva:
Podmienky IF....ELSE

Používa matematické podmienky, a vyhodnocuje ich. Ak podmienku vyhodnotí ako


pravdivú, vykoná sa príkaz vo vetve if, ak ako nepravdivú, vykoná sa vetva else.

a = 33
b = 200
if b > a:
print("b is greater than a")
else:
print("a is greater than b")

Python sa tu spolieha na odsadenie, preto si musíme dávať pozor aby príkazy za dvojbodkami
boli odsadené

ELIF
Kľúčové slovo elif je spôsob, akým Python hovorí „ak predchádzajúce podmienky neboli
pravdivé, skúste túto podmienku“.

a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")

PASS
if príkazy nemôžu byť prázdne, ale ak z nejakého dôvodu máte príkaz if bez obsahu, vložte
príkaz pass, aby ste sa vyhli chybe.

a = 33
b = 200

if b > a:
pass

While Loops
Cyklus ktorý, vykonáva sa kým je podmienka vyhodnotená ako pravdivá.

i = 1
while i < 6:
print(i)
i += 1
BREAK
Pomocou príkazu break môžeme zastaviť cyklus, aj keď je podmienka while pravdivá:

i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1

CONTINUE
Pomocou príkazu continue môžeme zastaviť aktuálnu iteráciu a pokračovať nasledujúcou

i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)

pri cykle while vieme použiť aj vetvu else, ktorá sa vykoná až keď už podmienka nebude
pravdivá

i = 1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")

For Loops
Cyklus for sa používa na iteráciu cez sekvenciu (to je buď zoznam, n-tica, slovník, množina
alebo reťazec).
Pomocou cyklu for môžeme vykonať množinu príkazov, raz pre každú položku v zozname,
n-ticu, množinu atď

fruits = ["apple", "banana", "cherry"]


for x in fruits:
print(x)

for x in range(6):
print(x)

for x in adj:
for y in fruits:
print(x, y)
Funkcie

Funkciu vytvoríme pomocou kľúčového slova def


def my_function():
print("Hello from a function")

funkcu zavoláme pomocu jej názvu, ktorý budú nasledovať zátvorky

def my_function():
print("Hello from a function")

my_function()

Passing arguments
Informácie môžu byť odovzdané do funkcií ako argumenty.
Argumenty sú uvedené za názvom funkcie v zátvorkách. Môžete pridať toľko argumentov,
koľko chcete, oddeľte ich čiarkou.

Nasledujúci príklad obsahuje funkciu s jedným argumentom (fname). Pri volaní funkcie
odovzdávame krstné meno, ktoré sa používa vo vnútri funkcie na vytlačenie celého mena:

def my_function(fname):
print(fname + " Refsnes")

my_function("Emil")
my_function("Tobias")
my_function("Linus")

* Pojmy parameter a argument možno použiť na rovnakú vec: informácie, ktoré sa prenášajú
do funkcie

def my_function(fname, lname):


print(fname + " " + lname)

my_function("Emil", "Refsnes")

def my_function(*kids):
print("The youngest child is " + kids[2])

my_function("Emil", "Tobias", "Linus")


Vstup od používateľa
Zapíšeme do premennej pomocu funkcie input()

username = input("Enter username:")


print("Username is: " + username)

*často vzniká potreba pretypovať vstup od používateľa, keďže vstup je stále dátového typu
string, ak teda potrebujeme pracovať s číslami, musíme vstup pretypovať pomocou funkcie
int()

username = int(input("Enter username:"))


print("Username is: " + username)

*funkcia format
Umožňuje nám formátovať určitú časť stringu, tak, že do kučervých zátvoriek dosadí
parameter funkcie format

price = 49
txt = "The price is {} dollars"
print(txt.format(price))

Vieme pomocou nej aj špecifikovať ako konvertovať dosadzovanú hodnotu, napr. Integer na
float s 2 desatinnými miestami

txt = "The price is {:.2f} dollars"

vieme pri nej používať aj indexy

age = 36
name = "John"
txt = "His name is {1}. {1} is {0} years old."
print(txt.format(age, name))

Práca s textovými súbormi


Pomocou funkcie open(), vieme otvoriť súbor, funkcia má dva parametre a to cestu k súboru
a mód ktorý určuje práva k súboru

"r" - Read - Default value. Opens a file for reading, error if the file does not exist
"a" - Append - Opens a file for appending, creates the file if it does not exist
"w" - Write - Opens a file for writing, creates the file if it does not exist
"x" - Create - Creates the specified file, returns an error if the file exists

Ak práva nešpecifikujeme, máme automaticky na čítanie – r

f = open("demofile.txt", "r")
Metóda read()
Ak nepoužijeme parameter vráti celý text, ale ak áno tak ním určíme počet znakov

f = open("demofile.txt", "r")
print(f.read(5))

Metóda readline()
Prečíta jeden riadok zo súboru
f = open("demofile.txt", "r")
print(f.readline())

Read two lines of the file:

f = open("demofile.txt", "r")
print(f.readline())
print(f.readline())

Loop through the file line by line:

f = open("demofile.txt", "r")
for x in f:
print(x)

Metóda close()
Po práci so súborom ho musíme zatvoriť pomocou funkcie close()

f = open("demofile.txt", "r")
print(f.readline())
f.close()

Zápis do súboru
Potrebujeme na to aj práva na zápis určené pri metóde open()

Zapisujeme pomocou funkcie write()

f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()

#open and read the file after the appending:


f = open("demofile2.txt", "r")
print(f.read())

nový súbor vytvárame rovnako ako otvárame už existujúci, len ak


neexistuje, tak sa vytvorí
Data collections: Lists, Tuples, Sets, Dictionaries
List
list1 = ["apple", "banana", "cherry"]
list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]
list1 = ["abc", 34, True, 40, "male"]

Položky zoznamu sú usporiadané, meniteľné a umožňujú duplicitné hodnoty.


Položky zoznamu sú indexované, prvá položka má index [0], druhá položka má index [1] atď.

Pomocou funkcie len() zistíme počet položiek listu.


thislist = ["apple", "banana", "cherry"]
print(len(thislist))

Access List Items


thislist = ["apple", "banana", "cherry"]
print(thislist[1])

thislist = ["apple", "banana", "cherry"]


print(thislist[-1])

thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])

thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[:4])

thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:])

Change List Items


thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist)

thislist = ["apple", "banana", "cherry"]


thislist[1:2] = ["blackcurrant", "watermelon"]
print(thislist)

Change the second and third value by replacing it with one value:
thislist = ["apple", "banana", "cherry"]
thislist[1:3] = ["watermelon"]
print(thislist)

Add List Items


Pomocou funkcie append() na koniec listu
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)

pomocou funkcie insert() na daný index


thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
print(thislist)

na pridanie ineho listu na koniec listu funkcia extend()


thislist = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
thislist.extend(tropical)
print(thislist)

Remove List Items

Pomocou funkcie remove() *keď je viac rovnakých položiek, odstráni iba


prvý jej výskyt
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
pomocou funkcie pop() odstránime poslednú položku listu alebo položku
na indexe špecifikovanom ako parameter pop(1)
thislist = ["apple", "banana", "cherry"]
thislist.pop()
print(thislist)
thislist = ["apple", "banana", "cherry"]
thislist.pop(1)
print(thislist)
špecifický index vieme tiež odstrániť pomocou kľúčoveho slova del
thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist)
metóda clear() vyprázdni celý list
thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist)

Loop Through a List


thislist = ["apple", "banana", "cherry"]
for x in thislist:
print(x)

thislist = ["apple", "banana", "cherry"]


for i in range(len(thislist)):
print(thislist[i])

thislist = ["apple", "banana", "cherry"]


i = 0
while i < len(thislist):
print(thislist[i])
i = i + 1

Sort List Alphanumerically


thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort()
print(thislist)

thislist = [100, 50, 65, 82, 23]


thislist.sort()
print(thislist)

thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]


thislist.sort(reverse = True)
print(thislist)

thislist = [100, 50, 65, 82, 23]


thislist.sort(reverse = True)
print(thislist)

Copy a List
Zoznam nemôžeme skopírovať jednoducho zadaním list2 = list1, pretože: list2 bude iba
odkazom na list1 a zmeny vykonané v list1 sa automaticky vykonajú aj v list2

Preto potrebujeme použiť metódu copy() alebo metódu list()


thislist = ["apple", "banana", "cherry"]
mylist = thislist.copy()
print(mylist)

thislist = ["apple", "banana", "cherry"]


mylist = list(thislist)
print(mylist)

Join Two Lists


Použitím operátora +

list1 = ["a", "b", "c"]


list2 = [1, 2, 3]

list3 = list1 + list2


print(list3)

alebo pomocou metódy append() či extend()

list1 = ["a", "b" , "c"]


list2 = [1, 2, 3]

for x in list2:
list1.append(x)

print(list1)

list1 = ["a", "b" , "c"]


list2 = [1, 2, 3]

list1.extend(list2)
print(list1)

Metódy pre list:

append() Adds an element at the end of the list

clear() Removes all the elements from the list

copy() Returns a copy of the list

count() Returns the number of elements with the specified


value

extend() Add the elements of a list (or any iterable), to the


end of the current list

index() Returns the index of the first element with the


specified value

insert() Adds an element at the specified position

pop() Removes the element at the specified position

remove() Removes the item with the specified value

reverse() Reverses the order of the list

sort() Sorts the list

Tuple
-je kolekcia dát, ktorá je usporiadaná(má indexy) a nemenná. Umožňuje duplicitu členov
tuple1 = ("apple", "banana", "cherry")

tuple2 = (1, 5, 7, 9, 3)

tuple3 = (True, False, False)

tuple1 = ("abc", 34, True, 40, "male")

Set
-je kolekcia dát, ktorá je neusporiadaná, nemeniteľná* a neindexovaná, nepovoľuje

duplicitné hodnoty(duplicitné budú ignorované)

set1 = {"apple", "banana", "cherry"}

set2 = {1, 5, 7, 9, 3}

set3 = {True, False, False}

set1 = {"abc", 34, True, 40, "male"}


Dictionary

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

-kolekcia dát, ktorá je usporiadaná, meniteľná, a nepovoľuje duplicitné hodnoty, zapisujú sa


do kučeravých zátvoriek a obsahujú kľúče a hodnoty k daným kľúčom

Položky slovníka sú prezentované v pároch kľúč:hodnota a možno na ne odkazovať pomocou


názvu kľúča

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])

thisdict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}

pridanie nového páru kľúč:hodnota

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)

zmena hodnoty k danému kľúču

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018
alebo pomocou update()

thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

thisdict.update({"year": 2020})

Odstránenie položky:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)

funkcia popitem() odstráni poslednú pridanú položku


thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.popitem()
print(thisdict)
Výpis položiek:
Výpis kľúčov:
for x in thisdict:
print(x)
alebo
for x in thisdict.keys():
print(x)
Výpis hodnôt:
for x in thisdict:
print(thisdict[x])
alebo
for x in thisdict.values():
print(x)
Výpis kľúča a hodnoty:
for x, y in thisdict.items():
print(x, y)
Kopírovanie slovníkov:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = thisdict.copy()
print(mydict)

You might also like