This shows you the differences between two versions of the page.
ic:resurse:python [2020/09/25 16:28] acosmin.maria [References] |
ic:resurse:python [2023/10/02 00:10] (current) razvan.smadu [Python3 Crash Course] |
||
---|---|---|---|
Line 1: | Line 1: | ||
===== Python3 Crash Course ===== | ===== Python3 Crash Course ===== | ||
+ | |||
+ | === Ce este Python? === | ||
+ | |||
+ | Python este un limbaj interpretat, ușor de folosit, în special datorită faptului că nu necesită compilare sau linkare. Interpretorul permite rularea de fișiere care conțin cod scris în Python, dar permite și rularea de cod în modul interactiv. În plus, este un limbaj perfect pentru prototipat idei și testat algoritmi, însă are dezavantajul de a rula mai lent decât limbaje precum C, C++ și Java. | ||
+ | |||
+ | Mediul de dezvoltare poate presupune utilizarea unui editor de text/IDE și al unul terminal, sau folosirea unor medii de dezvoltare bazate pe interfațe web, precum [[https://jupyter.org/index.html|Jupyter Notebooks]], [[https://research.google.com/colaboratory/|Google Colaboratory]] și [[https://www.kaggle.com/|Kaggle]]. | ||
+ | |||
+ | === Instalare Python 3 === | ||
+ | |||
+ | În linux este destul de simplu întrucât multe distribuții vin deja cu Python instalat. Pentru a verifica dacă aveți deja instalat Python pe sistemul vostru, puteți deschide un terminal și rula | ||
+ | <code> | ||
+ | python --version # OR python3 --version | ||
+ | </code> | ||
+ | |||
+ | In cazul în care comanda vă returnează un versiunea de python instalată (ex. Python 3.7.9), atunci nu mai trebui să faceți nimic. | ||
+ | |||
+ | <note> Recomandăm să aveți instalat Python 3, întrucât Python 2 nu mai are [[https://www.python.org/doc/sunset-python-2/|suport oficial]] de la 1 ianuare 2020, iar sintaxa între cele două versiuni diferă. </note> | ||
+ | |||
+ | În cazul în care nu aveți Python 3 instalat, puteți folosi managerul de pachete (ex. apt, yum), [[https://docs.conda.io/en/latest/miniconda.html|conda]], sau puteți descărca direct de pe [[https://www.python.org/downloads/|site-ul oficial]]. | ||
+ | |||
+ | În Windows, puteți descărca de pe [[https://www.microsoft.com/en-us/p/python-39/9p7qfqmjrfp7|Microsoft Store]], puteți folosi [[https://docs.conda.io/en/latest/miniconda.html|conda]], sau puteți descărca direct de pe [[https://www.python.org/downloads/|site-ul oficial]]. | ||
+ | |||
=== Command Line (CLI) === | === Command Line (CLI) === | ||
- | Start REPL (Read Execute Print Repeat) interactive mode and exit: | + | Pornirea modului interactiv REPL (Read Execute Print Repeat) și ieșirea din el: |
<code python> | <code python> | ||
- | shell$ python | + | shell$ python # OR python3 |
>>> | >>> | ||
- | >>> quit() | + | >>> quit() # OR CTRL-D |
shell$ | shell$ | ||
</code> | </code> | ||
- | Execute files: | + | Executarea fișierelor: |
<code python> | <code python> | ||
shell$ python filename.py | shell$ python filename.py | ||
shell$ python filename.py arg1 arg2 arg3 | shell$ python filename.py arg1 arg2 arg3 | ||
+ | shell$ python -i filename.py # start in interactive mode | ||
</code> | </code> | ||
- | ==== Basics ==== | + | === Basics === |
- | Variables: | + | |
+ | Variabile și tipuri de date numerice: | ||
<code python> | <code python> | ||
- | a = 10 | + | a = 10 # int |
- | b = "Ana are mere" | + | b = 10.2 # float |
- | c = [1, 2, 3] | + | c = None # NULL value in Python |
+ | </code> | ||
+ | Stringuri și formatarea strigurilor | ||
+ | <code python> | ||
+ | s1 = "Ana are mere" | ||
+ | s2 = """This is a | ||
+ | multiline string""" | ||
+ | age = 20 | ||
+ | s3 = f"Ana are {age} ani" | ||
</code> | </code> | ||
- | Functions: | + | Funcții: |
<code python> | <code python> | ||
- | def my_function(a | + | def my_function(a, b): |
+ | return a + b | ||
</code> | </code> | ||
- | ==== Input/Output ==== | + | **!Notă:** În Python nu avem acolade (ca în limbajele C-like). În schimb, folosim identarea pentru a defini scopul unei funcții/instrucțiuni. |
- | ==== Data Structure ==== | + | === Input/Output === |
- | Lists: | + | Standard I/O: |
- | <code> | + | <code python> |
- | l1 = [1, 2, 3] | + | input_text = input() # type str |
- | l2 = [10, 'mere', [25, 20], {}, ] | + | print(input_text) |
+ | a = input() # 10 | ||
+ | a = int(a) # convert to int | ||
+ | print(a + 5) # 15 | ||
</code> | </code> | ||
- | ==== Object Oriented Programming ==== | + | Fișiere: |
+ | <code python> | ||
+ | f = open("path/to/file.txt") # default behaviour is 'read text' | ||
+ | data = f.read() # reads the entire file in a string | ||
+ | lines = f.readlines() # reads the lines in a list | ||
+ | f.close() | ||
- | <code> | + | # when using the 'with' statement no need to close the file |
+ | # 'w' - write, 'r' - read, 'a' - append, 'x' - create | ||
+ | # 't' - text, 'b' - binary | ||
+ | with open("result.txt", 'w') as f: # 'write text' | ||
+ | f.write(data) | ||
+ | f.writelines(lines) | ||
+ | </code> | ||
+ | === Operații === | ||
+ | |||
+ | * Aritmetice: +, +=, -, -=, *, *=, /, /= | ||
+ | * Logice: ==, !=, <, <=, >, >= | ||
+ | |||
+ | <code python> | ||
+ | a = 7 // 2 # a = 3 (Integer Division) | ||
+ | b = 7 % 2 # b = 1 (Modulus) | ||
+ | c = 2 ** 3 # c = 8 (Exponent) | ||
+ | d = 1 ^ 0 # d = 1 (XOR operation) | ||
</code> | </code> | ||
+ | === Structuri condiționale și repetitive === | ||
+ | Putem folosi majoritatea cuvintelor cheie (keywords) din C: | ||
- | === Conditions & Loops === | ||
<code python> | <code python> | ||
i = 0 | i = 0 | ||
- | cnt1 = 0 | + | cnt = 0 |
- | while i < 10: | + | while i < 100: |
- | if i%2 == 0: | + | if i == 25: |
+ | continue | ||
+ | if i < 50: | ||
cnt += 1 | cnt += 1 | ||
- | + | if i % 2 == 0: | |
+ | cnt *= 2 | ||
+ | elif i >= 50 and cnt % 2 == 0: | ||
+ | cnt += 3 | ||
+ | else: | ||
+ | cnt -= 1 | ||
+ | if i > 90 or cnt > 200: | ||
+ | break | ||
+ | </code> | ||
+ | |||
+ | **!Notă:** Folosim 'and' și 'or' pentru a combina 2 structuri logice | ||
+ | |||
+ | |||
+ | === Structuri de date === | ||
+ | Liste: | ||
+ | <code python> | ||
+ | l1 = [1, 2, 3] | ||
+ | l1.append(4) # [1, 2, 3, 4] | ||
+ | l1.reverse() # [4, 3, 2, 1] | ||
+ | e1 = l1.pop() # l1 = [4, 3, 2], e1 = 1 | ||
+ | e2 = l1.pop(0) # l1 = [3, 2], e2 = 4 | ||
+ | l1.extend([10, 12, 15]) # l1 = [3, 2, 10, 12, 15] | ||
+ | l2 = l1[:] # copy the entire list into l2 | ||
+ | c1, c2, c3 = l1[:1], l1[1:3], l1[3:] # c1 = [3], c2 = [2, 10], c3 = [12, 15] | ||
+ | c1.insert(0, 2) # c1 = [2, 3] | ||
+ | c1.remove(3) # c1 = [3] | ||
+ | </code> | ||
+ | |||
+ | Dicționare: | ||
+ | <code python> | ||
+ | dictio = {} | ||
+ | dictio["key1"] = 1 | ||
+ | "key1" in dictio # True | ||
+ | "key2" not in dictio # True | ||
+ | del dictio["key1"] | ||
+ | dictio.clear() # deletes all entries in the dictionary | ||
+ | </code> | ||
+ | |||
+ | Tupluri: | ||
+ | <code python> | ||
+ | t = (1, 2, 3) # same as lists, but immutable | ||
+ | </code> | ||
+ | |||
+ | Seturile sunt similare cu dicționarele în termeni de complexitate, dar stocheaza doar cheile. | ||
+ | <code python> | ||
+ | s = {1, 2, 3} | ||
+ | 2 in s # True O(1) time complexity | ||
+ | unique_elements = list(set([1, 1, 2, 2, 3, 3])) # unique_elements = [1, 2, 3] | ||
+ | </code> | ||
+ | |||
+ | === Programare Orientată pe Obiecte === | ||
+ | |||
+ | <code python> | ||
+ | class MyClass: | ||
+ | def __init__(self, arg1, arg2): # constructor | ||
+ | self.arg1 = arg1 # object properties | ||
+ | self.arg2 = arg2 | ||
| | ||
+ | def my_method(self, arg1, arg2): # class method | ||
+ | self.arg1 += arg1 | ||
+ | self.arg2 -= arg2 | ||
+ | return self.arg1 * self.arg2 | ||
+ | | ||
+ | | ||
+ | obj1 = MyClass(1, 2) | ||
+ | result = obj1.my_method(2, 3) | ||
+ | print(result) | ||
</code> | </code> | ||
- | |||
- | fsafsafsa | ||
- | ==== References ==== | + | === Funcții Built-in === |
- | * Official documentation: [[https://www.python.org/|link]] | + | |
- | * Tutorial: [[https://www.tutorialspoint.com/python/index.htm|link]] | + | == range(start, stop, step) == |
- | * Cheatsheet: [[https://www.pythoncheatsheet.org/|link]] | + | <code python> |
- | * Book: [[https://www.pdfdrive.com/python-crash-coursepdf-e33417142.html|link]] | + | for i in range(5): |
- | * Online Course: [[https://www.coursera.org/specializations/python|link]] | + | print(i) # 0 1 2 3 4 |
+ | |||
+ | for i in range(3, 10, 2): | ||
+ | print(i) # 3 5 7 9 | ||
+ | </code> | ||
+ | |||
+ | În Python 2.x, range() prima dată genereaza întreaga lista de numere, iar apoi iterează prin ele. | ||
+ | <code python> | ||
+ | for i in range(5): # equivalent to: for i in [0, 1, 2, 3, 4] | ||
+ | </code> | ||
+ | Alternativa este funcția xrange() care se folosește de un generator pentru a genera numere, la nevoie. Funcția range() din Python 3.x este echivalentul funcției xrange() din Python 2.x. | ||
+ | <code python> | ||
+ | def xrange(start, stop, step): | ||
+ | i = start | ||
+ | while i < stop: | ||
+ | yield i | ||
+ | i += step | ||
+ | |||
+ | iter = xrange(0, 10, 1) | ||
+ | type(iter) # <class 'generator'> | ||
+ | </code> | ||
+ | |||
+ | == enumerate() == | ||
+ | <code python> | ||
+ | for index, value in enumerate([10, 20, 30]): | ||
+ | print(index, value) | ||
+ | |||
+ | for key, value in enumerate({"key1": "val1", "key2": "val2", "key3": "val3"}): | ||
+ | print(key, value) | ||
+ | </code> | ||
+ | |||
+ | == len() == | ||
+ | <code python> | ||
+ | len([1, 2, 3]) # 3 | ||
+ | </code> | ||
+ | |||
+ | Alte [[https://docs.python.org/3/library/functions.html|funcții built-in utile]]: abs(), all(), any(), max(), min(), zip(), type(), sum(), str(), chr(), ord(), sorted(), round(), reversed(), int(), float() | ||
+ | |||
+ | === Comprehensions === | ||
+ | |||
+ | List comprehension: | ||
+ | <code python> | ||
+ | l1 = [2*i if i % 2 == 0 else 3*i for i in range(100)] # [0, 3, 4, 9 ...] | ||
+ | l2 = [f"item{i}" for i in range(100)] # ["item0", "item1", ..., "item99"] | ||
+ | l3 = [0 for i in range(100) if i % 2 == 0] # len(l3) = 50 | ||
+ | </code> | ||
+ | |||
+ | Dictionary comprehension: | ||
+ | <code python> | ||
+ | d1 = {f"key{i}": i*2 for i in range(100)} | ||
+ | </code> | ||
+ | |||
+ | === Biblioteci și Importuri === | ||
+ | <code python> | ||
+ | python -m pip install packagename # Windows | ||
+ | pip install packagename # Linux | ||
+ | </code> | ||
+ | |||
+ | <code python> | ||
+ | from tensorflow.keras.layers import Conv2D | ||
+ | import numpy as np | ||
+ | import random | ||
+ | from mypackage import * | ||
+ | |||
+ | obj1 = Conv2D() | ||
+ | result = np.sum([1, 2, 3]) | ||
+ | r1 = random.random() | ||
+ | </code> | ||
+ | |||
+ | === Type Hints === | ||
+ | |||
+ | Python este un limbaj tipat dinamic. Pentru a ușura întelegerea codului, putem folosi type hints care reprezintă adnotări asupra tipurilor de date. Acestea nu sunt forțate la runtime, fiind responsabilitatea programatorului să se asigure că tipurile nu induc în eroare. Detalii legate de type hints se pot găsi în [[https://docs.python.org/3/library/typing.html|documentație]], [[https://peps.python.org/pep-0484/|PEP 484]] și [[https://peps.python.org/pep-0483/|PEP 483]]. | ||
+ | |||
+ | Exemple: | ||
+ | <code python> | ||
+ | from typing import Dict, List, Sequence, Tuple, TypeVar | ||
+ | |||
+ | my_string: str = "hello world" # A variable storing a string | ||
+ | my_number: int = 10 # A variable storing an integer | ||
+ | |||
+ | # A function returning nothing | ||
+ | def main() -> None: | ||
+ | return # Returns nothing (i.e., None) | ||
+ | |||
+ | # A function that takes some arguments, and returns a tuple | ||
+ | def compute(a: int, b: float, c: List[str]) -> Tuple[int, float]: | ||
+ | return a, b # This is a tuple of `a` and `b` | ||
+ | |||
+ | T = TypeVar('T') # Declare type variable | ||
+ | |||
+ | def first(l: Sequence[T]) -> T: # A generic function | ||
+ | return l[0] | ||
+ | |||
+ | # Type alias | ||
+ | MyCustomType = Dict[str, List[Tuple[int, int]]] | ||
+ | </code> | ||
+ | |||
+ | |||
+ | ==== Referințe ==== | ||
+ | * Documentația oficială: [[https://www.python.org/|here]] | ||
+ | * Tutorial: [[https://www.tutorialspoint.com/python/index.htm|here]] | ||
+ | * Cheatsheet: [[https://www.pythoncheatsheet.org/|here]] | ||
+ | * Book: [[https://www.pdfdrive.com/python-crash-coursepdf-e33417142.html|here]] | ||
+ | * Curs online: [[https://www.coursera.org/specializations/python|here]] | ||