🐍 Python · built-ins & keywordsdetalii completecomplete details

📦 Funcții built-in📦 Built-in functions
print()
Afisează valori în consolă. Poate primi mai multe argumente, separate prin spațiu. Parametri: sep, end, file.Displays values to the console. Can take multiple arguments, separated by a space. Parameters: sep, end, file.
print("Salut", 42, sep=" → ")print("Hello", 42, sep=" → ")
input()
Citește un șir de la utilizator (întrerupe execuția). Returnează str. Opțional, afișează un mesaj înainte.Reads a string from the user (pauses execution). Returns str. Optionally shows a prompt message first.
nume = input("Nume: ")name = input("Name: ")
type()
Returnează tipul obiectului (clasa). Util pentru debug sau verificări dinamice.Returns the object's type (class). Useful for debugging or dynamic checks.
type(3.14) # <class 'float'>
len()
Returnează lungimea (numărul de elemente) unui obiect container (șir, listă, tuplu, set, dict etc.).Returns the length (number of elements) of a container object (string, list, tuple, set, dict, etc.).
len([1,2,3]) # 3
int()
Convertește un număr sau un șir într-un întreg (baza 10 implicit). Poate primi și bază (2, 8, 16).Converts a number or string into an integer (base 10 by default). Can also take a base (2, 8, 16).
int("101", 2) # 5
float()
Convertește un număr sau șir în virgulă mobilă. Returnează float.Converts a number or string into a floating point number. Returns float.
float("3.14") # 3.14
str()
Convertește un obiect într-un șir de caractere (reprezentare lizibilă).Converts an object into a string (readable representation).
str(123) # "123"
bool()
Convertește valoarea într-un boolean (True sau False). Reguli: 0, None, "" → False.Converts a value into a boolean (True or False). Rules: 0, None, "" → False.
bool([]) # False
True bool
Valoare booleană adevărată (singleton). Egal cu 1, dar de tip bool.True boolean value (singleton). Equal to 1, but of type bool.
if True: print("da")if True: print("yes")
False bool
Valoare booleană falsă (singleton). Egal cu 0, dar de tip bool.False boolean value (singleton). Equal to 0, but of type bool.
if not False: ...
None NoneType
Reprezintă „nimic”, absența unei valori. Folosit pentru inițializare sau returnare implicită.Represents “nothing”, the absence of a value. Used for initialization or an implicit return.
x = None
➕ Operatori aritmetici & comparație➕ Arithmetic & comparison operators
+
Adunare (numeric) sau concatenare (șiruri, liste).Addition (numeric) or concatenation (strings, lists).
3 + 5 # 8
-
Scădere (numeric).Subtraction (numeric).
10 - 3 # 7
*
Înmulțire (numeric) sau repetare (șiruri, liste).Multiplication (numeric) or repetition (strings, lists).
3 * 4 # 12
/
Împărțire reală (returnează float).True division (returns float).
7 / 2 # 3.5
//
Împărțire întreagă (floor division). Returnează int sau float dacă operanzii sunt float.Floor division (integer division). Returns int, or float if the operands are floats.
7 // 2 # 3
%
Restul împărțirii (modulo).Division remainder (modulo).
7 % 3 # 1
**
Exponentiere (putere).Exponentiation (power).
2 ** 3 # 8
==
Egalitate (valori). Compară conținutul obiectelor.Equality (values). Compares the contents of objects.
[1,2] == [1,2] # True
!=
Inegalitate.Inequality.
3 != 4 # True
>
Mai mare decât.Greater than.
5 > 3 # True
<
Mai mic decât.Less than.
3 < 5 # True
>=
Mai mare sau egal.Greater than or equal to.
5 >= 5 # True
<=
Mai mic sau egal.Less than or equal to.
3 <= 3 # True
🔗 Operatori logici & apartenență🔗 Logical & membership operators
and
Și logic: True dacă ambele operanzi sunt True.Logical AND: True if both operands are True.
True and False # False
or
Sau logic: True dacă cel puțin un operand este True.Logical OR: True if at least one operand is True.
True or False # True
not
Neagă valoarea booleană.Negates a boolean value.
not True # False
in
Verifică apartenența unui element într-un container (șir, listă, set, dict chei).Checks whether an element belongs to a container (string, list, set, dict keys).
"a" in "abc" # True
is
Compară identitatea obiectelor (dacă sunt aceeași instanță). Nu confunda cu ==.Compares object identity (whether they are the same instance). Don't confuse with ==.
x is y # True dacă același obiect
📋 Structuri de date (built-in)📋 Data structures (built-in)
list()
Creează o listă (ordonată, mutabilă). Poate converti un iterabil.Creates a list (ordered, mutable). Can convert an iterable.
list("abc") # ['a','b','c']
tuple()
Creează un tuplu (ordonat, imutabil).Creates a tuple (ordered, immutable).
tuple([1,2]) # (1,2)
set()
Creează un set (neordonat, fără duplicate, mutabil).Creates a set (unordered, no duplicates, mutable).
set([1,1,2]) # {1,2}
dict()
Creează un dicționar (cheie-valoare). Poate primi perechi sau keyword args.Creates a dictionary (key-value). Can take pairs or keyword args.
dict(a=1, b=2) # {'a':1, 'b':2}
🧩 Metode specifice pentru listă🧩 List-specific methods
append()
Adaugă un element la sfârșitul listei. Modifică lista in-place.Adds an element to the end of the list. Modifies the list in place.
lst.append(4)
insert()
Inserează un element la un index dat.Inserts an element at a given index.
lst.insert(1, "x")
remove()
Elimină prima apariție a valorii specificate. Aruncă ValueError dacă nu există.Removes the first occurrence of the specified value. Raises ValueError if not found.
lst.remove(2)
pop()
Elimină și returnează elementul de la index (implicit ultimul).Removes and returns the element at the given index (last by default).
lst.pop(0)
clear()
Elimină toate elementele din listă.Removes all elements from the list.
lst.clear()
sort()
Sortează lista in-place (crescător). Parametri: key, reverse.Sorts the list in place (ascending). Parameters: key, reverse.
lst.sort(reverse=True)
reverse()
Inversează ordinea elementelor in-place.Reverses the order of the elements in place.
lst.reverse()
copy()
Returnează o copie superficială a listei.Returns a shallow copy of the list.
lst2 = lst.copy()
index()
Returnează indexul primei apariții a valorii. Aruncă ValueError.Returns the index of the first occurrence of the value. Raises ValueError.
lst.index(3)
count()
Returnează de câte ori apare valoarea în listă.Returns how many times the value appears in the list.
lst.count(2)
extend()
Adaugă elementele unui iterabil la sfârșitul listei.Adds the elements of an iterable to the end of the list.
lst.extend([5,6])
⚙️ Instrucțiuni de control (if, for, while etc.)⚙️ Control statements (if, for, while, etc.)
if
Execută un bloc dacă condiția este True.Executes a block if the condition is True.
if x > 0: print("pozitiv")if x > 0: print("positive")
elif
Alternativă la if (else-if). Se poate folosi de mai multe ori.Alternative to if (else-if). Can be used multiple times.
elif x == 0: ...
else
Bloc executat când condițiile anterioare sunt False.Block executed when the previous conditions are False.
else: print("negativ")else: print("negative")
for
Iterează peste un iterabil (listă, șir, range etc.).Iterates over an iterable (list, string, range, etc.).
for i in range(3): print(i)
while
Execută un bloc cât timp condiția este True.Executes a block while the condition is True.
while x < 5: x += 1
break
Iese imediat din bucla curentă (for sau while).Immediately exits the current loop (for or while).
if i==3: break
continue
Sare la următoarea iterație a buclei.Skips to the next iteration of the loop.
if i%2==0: continue
pass
Instrucțiune nulă; nu face nimic. Folosit ca placeholder.Null statement; does nothing. Used as a placeholder.
def f(): pass
🧠 Funcții utile: range, enumerate, zip🧠 Useful functions: range, enumerate, zip
range()
Generează o secvență de numere (imutabilă). Folosită des în bucle for.Generates a sequence of numbers (immutable). Often used in for loops.
range(2, 10, 2) # 2,4,6,8
enumerate()
Returnează perechi (index, element) pentru un iterabil.Returns (index, element) pairs for an iterable.
for i, v in enumerate(['a','b']):
zip()
Agregă elemente din mai multe iterabile în tupluri.Aggregates elements from multiple iterables into tuples.
list(zip([1,2], ['a','b'])) # [(1,'a'),(2,'b')]
🧩 Definire funcții & OOP🧩 Function definitions & OOP
def
Definește o funcție.Defines a function.
def salut(): print("hi")def greet(): print("hi")
return
Returnează o valoare dintr-o funcție. Fără returnNone.Returns a value from a function. Without return → None.
return x * 2
lambda
Funcție anonimă (expresie) cu un singur statement. Returnează implicit.Anonymous function (expression) with a single statement. Returns implicitly.
lambda x: x**2
class
Definește o clasă (blueprint pentru obiecte).Defines a class (a blueprint for objects).
class Dog: pass
self
Referință către instanța curentă într-o metodă de clasă.Reference to the current instance inside a class method.
def metoda(self): pass
__init__
Constructorul clasei, apelat la crearea instanței.The class constructor, called when an instance is created.
def __init__(self, nume):
super()
Referință către clasa părinte. Folosit pentru a apela metodele părintelui.Reference to the parent class. Used to call the parent's methods.
super().__init__()
@property
Decorator; definește o proprietate (acces ca atribut, dar cu logică).Decorator; defines a property (accessed like an attribute, but with logic).
@property def age(self):
⚠️ Gestionare excepții⚠️ Exception handling
try
Bloc care poate genera excepții.Block that may raise exceptions.
try: x = int("abc")
except
Prinde și gestionează o excepție specifică sau generică.Catches and handles a specific or generic exception.
except ValueError: print("eroare")except ValueError: print("error")
finally
Bloc executat întotdeauna (după try/except), indiferent de excepție.Block that always executes (after try/except), regardless of the exception.
finally: print("curățenie")finally: print("cleanup")
raise
Aruncă (lansează) o excepție în mod explicit.Explicitly raises an exception.
raise TypeError("mesaj")
assert
Verifică o condiție; dacă e False, aruncă AssertionError.Checks a condition; if False, raises AssertionError.
assert x > 0, "x trebuie pozitiv"assert x > 0, "x must be positive"
📦 Import & alias📦 Import & alias
import
Importă un modul întreg.Imports an entire module.
import math
from
Importă părți dintr-un modul (funcții, clase, constante).Imports parts of a module (functions, classes, constants).
from math import pi
as
Creează un alias (pseudonim) pentru un modul sau obiect importat.Creates an alias (nickname) for an imported module or object.
import numpy as np
📊 Funcții matematice / aggregate📊 Math / aggregate functions
sum()
Sumează elementele unui iterabil (numeric). Poate primi un start.Sums the elements of an iterable (numeric). Can take a start value.
sum([1,2,3]) # 6
min()
Returnează cel mai mic element dintr-un iterabil sau dintre argumente.Returns the smallest element from an iterable or among the arguments.
min(3,1,4) # 1
max()
Returnează cel mai mare element dintr-un iterabil sau dintre argumente.Returns the largest element from an iterable or among the arguments.
max([5,2,8]) # 8
abs()
Valoarea absolută a unui număr.The absolute value of a number.
abs(-5) # 5
round()
Rotunjește un float la un anumit număr de zecimale (implicit 0).Rounds a float to a given number of decimals (0 by default).
round(3.1415, 2) # 3.14
sorted()
Returnează o listă sortată dintr-un iterabil (nu modifică originalul).Returns a sorted list from an iterable (does not modify the original).
sorted([3,1,2]) # [1,2,3]
reversed()
Returnează un iterator invers pentru un iterabil.Returns a reverse iterator for an iterable.
list(reversed([1,2,3])) # [3,2,1]
any()
Returnează True dacă cel puțin un element al iterabilului este True.Returns True if at least one element of the iterable is True.
any([0, False, 5]) # True
all()
Returnează True dacă toate elementele iterabilului sunt True.Returns True if all elements of the iterable are True.
all([1, 2, 3]) # True
map()
Aplică o funcție fiecărui element dintr-un iterabil; returnează iterator.Applies a function to each element of an iterable; returns an iterator.
list(map(str, [1,2])) # ['1','2']
filter()
Filtrează elementele unui iterabil conform unei funcții predicate.Filters the elements of an iterable according to a predicate function.
list(filter(lambda x: x>2, [1,3,5])) # [3,5]