# 1. Introducere¶

Limbajul de programare Python a fost lansat de catre Guido van Rossum, in anul 1991. Python este un limbaj de programare de nivel inalt, codul scris in acest limbaj rulând pe oricare sistem de operare.
Limbajul de programare Python are urmatoarele caracteristici:

- limbaj interpretat: codul este rulat pe un interpretor;
- sintaxa simpla, recomandat incepatorilor in programare;
- dispune de un ecosistem foarte dezvoltat: exista o comunitate numeroasa de programatori care dezvolta module Python (librarii Python) dedicate implementarii software a aplicatiilor dintr-o gama foarte variata de domenii: inteligenta artificiala (machine learning), calcul numeric, robotica, comunicatii, prelucrare semnale, modelare sisteme, etc.
- este gratuit; se poate descarca de pe pagina web oficiala a limajului www.python.org.
  Codul scris in limbaj Python este rulat pe un interpretor de program, prin parcurgerea urmatorilor pasi:

1. Interpretorul de program citeste codul sursa (source code) scris in limbajul Python si verifica linie cu linie corectitudinea sintaxei utilizate. In cazul in care interpretorul depisteaza o eroare de sintaxa (syntax error), isi intrerupe executia si lanseaza un mesaj de eroare.
2. Daca nu sunt depisate erori de sintaxa in codul sursa, interpretorul face conversia (translateaza) codul sursa intr-o forma echivalenta, de nivel inferior, denumit byte code ( source code -interpretor-> byte code)
3. Varianta byte code a codului sursa este trimisa catre o componenta software denumita masina virtuala Python (Python virtual machine (PVM)), care executa codul sursa. Daca la executia byte code-ului sunt depistate erori, denumite erori de executie (runtime error), masina virtuala Python isi intrerupe executia si un mesaj de eroare este lansat.

Acest curs utilizeaza platforma software Anaconda, care se poate descarca gratuit si instala de la adresa https://www.anaconda.com/distribution/. Toate prezentarile si exemplele de cod Python sunt rulate in aplicatia Jupyter Notebook, una din componentele platformei Anaconda.

Aplicatia Jupyter Notebook utilizeaza varianta IPython (interactive interface to Python) a interpretorului Python, lansata in anul 2001 de catre Fernando Perez. Aplicatia Jupyter Notebook furnizeaza o interfata grafica interactiva, care permite combinarea intr-o singura aplicatie, denumita document notebook (pe scurt, notebook), componente utilizate la executia unui cod software scris in diverse limbaje de programare (Python, Julia, R), editor de text, afisare grafice, imagini, JavaScript widgets, rulare de filme, etc. Jupyter Notebook reprezinta o aplicatie web de tip server-client, care permite editarea si rularea continutului documentelor notebook prin intermediul unui browser web.

Pentru rularea codurilor sursa incluse intr-un notebook, este necesar ca aplicatia Jupyter Notebook sa fie conectata la un nucleu de executie, denumit kernel. Acest lucru se realizeaza automat, la lansarea aplicatiei Jupyter notebook, din meniul Anaconda Navigator al platformei software Anaconda. La lansarea aplicatiei, se lanseaza implicit un server web local (de exemplu, http://localhost:8888/, dar adresa depinde de computerul utilizat la rularea platformei software), care devine vizibil in browser-ul web setat ca implicit in sistemul de operare.

In [1]:

    # Introducere in Jupyter Notebook
    from IPython.display import YouTubeVideo
    YouTubeVideo('HW29067qVWk', width=400, height=300)

Out[1]:

## Comenzi magice (Magic Commands) specifice interpretorului IPython¶

Comenzile magice (Magic Commands) sunt specifice interpretorului IPython (nu fac parte din sintaxa limbajului Python), destinate rezolvarii unor probleme uzuale, frecvente in analiza datelor. Aceste comenzi sunt prefixate de caracterul `%`, sau `%%` si sunt de 2 tipuri:

- comenzi linie line magics, sunt prefixate de caracterul `%` si au efect in linia in care sunt plasate,
- comenzi celula cell magics,sunt prefixate de caracterul `%%` si au efect in celula in care sunt plasate Exemple:
- `%magic` = afiseaza o descriere generala a functiilor magice furnizate
- `%lsmagic` = afiseaza o lista a functiilor magice furnizate
- `%pwd` = afiseaza calea directorului de lucru curent
- `%matplotlib inline` = permite afisarea graficelor
- `%%HTML` = permite afisarea paginilor web
- `%%timeit` = permite afisarea timpului necesar executie codului sursa din celula in care este utilizata.

In [2]:

    # Exemplul 1: obtinerea informatiilor despre directorul curent de lucru
    %pwd

Out[2]:

    'W:\\PRJ\\JUPYTER_PYTHON\\Python'

# 2. Comentarea liniilor de cod in Python (Python Comments)¶

Limbajul Python pune la dispozitia programatorului 2 solutii pentru introducerea comentariilor, in functie de tipul lor:

- comentariu pe o singura linie de cod
- comentariu pe mai multe linii de cod

Comentariul pe 1 singura linie de cod se introduce plasand caracterul `#` in comentariului respectiv. Comentariul se poate introduce sau pe o linie care nu contine cod Python, sau in linie cu codul Python, daca se introduce la finalul acesteia.

In [3]:

    # Acesta este un comentariu pe 1 singura linie

Comentariul pe mai multe linii de cod se introduce intre 2 siruri de caractere `"""` - acesta varianta este utilizata pentru delimitarea unui segment de text, referit sub denumirea de docstring.

In [4]:

    """
    Acesta este un docstring.
    Se recomanda utilizarea acestui tip de comentariu la inceputul unui fisier, pentru documentare sa,
    sau pentru documentarea "functiilor", respectiv a "claselor" Python.
    """

Out[4]:

    '\nAcesta este un docstring.\nSe recomanda utilizarea acestui tip de comentariu la inceputul unui fisier, pentru documentare sa, \nsau pentru documentarea "functiilor", respectiv a "claselor" Python. \n'

# 3. Obtinerea informatiilor despre componenta software interogata¶

Limbajul de programare Python pune la dispozitia programatorului functia predefinita `help`, care returneaza informatii despre "componenta software" furnizata ca argument.

- Sintaxa:

    help(argument)

In [5]:

    # Exemplul 2: utilizarea functiei help
    help(int)

    Help on class int in module builtins:

    class int(object)
     |  int([x]) -> integer
     |  int(x, base=10) -> integer
     |
     |  Convert a number or string to an integer, or return 0 if no arguments
     |  are given.  If x is a number, return x.__int__().  For floating point
     |  numbers, this truncates towards zero.
     |
     |  If x is not a number or if base is given, then x must be a string,
     |  bytes, or bytearray instance representing an integer literal in the
     |  given base.  The literal can be preceded by '+' or '-' and be surrounded
     |  by whitespace.  The base defaults to 10.  Valid bases are 0 and 2-36.
     |  Base 0 means to interpret the base from the string as an integer literal.
     |  >>> int('0b100', base=0)
     |  4
     |
     |  Methods defined here:
     |
     |  __abs__(self, /)
     |      abs(self)
     |
     |  __add__(self, value, /)
     |      Return self+value.
     |
     |  __and__(self, value, /)
     |      Return self&value.
     |
     |  __bool__(self, /)
     |      self != 0
     |
     |  __ceil__(...)
     |      Ceiling of an Integral returns itself.
     |
     |  __divmod__(self, value, /)
     |      Return divmod(self, value).
     |
     |  __eq__(self, value, /)
     |      Return self==value.
     |
     |  __float__(self, /)
     |      float(self)
     |
     |  __floor__(...)
     |      Flooring an Integral returns itself.
     |
     |  __floordiv__(self, value, /)
     |      Return self//value.
     |
     |  __format__(self, format_spec, /)
     |      Default object formatter.
     |
     |  __ge__(self, value, /)
     |      Return self>=value.
     |
     |  __getattribute__(self, name, /)
     |      Return getattr(self, name).
     |
     |  __getnewargs__(self, /)
     |
     |  __gt__(self, value, /)
     |      Return self>value.
     |
     |  __hash__(self, /)
     |      Return hash(self).
     |
     |  __index__(self, /)
     |      Return self converted to an integer, if self is suitable for use as an index into a list.
     |
     |  __int__(self, /)
     |      int(self)
     |
     |  __invert__(self, /)
     |      ~self
     |
     |  __le__(self, value, /)
     |      Return self<=value.
     |
     |  __lshift__(self, value, /)
     |      Return self<<value.
     |
     |  __lt__(self, value, /)
     |      Return self<value.
     |
     |  __mod__(self, value, /)
     |      Return self%value.
     |
     |  __mul__(self, value, /)
     |      Return self*value.
     |
     |  __ne__(self, value, /)
     |      Return self!=value.
     |
     |  __neg__(self, /)
     |      -self
     |
     |  __or__(self, value, /)
     |      Return self|value.
     |
     |  __pos__(self, /)
     |      +self
     |
     |  __pow__(self, value, mod=None, /)
     |      Return pow(self, value, mod).
     |
     |  __radd__(self, value, /)
     |      Return value+self.
     |
     |  __rand__(self, value, /)
     |      Return value&self.
     |
     |  __rdivmod__(self, value, /)
     |      Return divmod(value, self).
     |
     |  __repr__(self, /)
     |      Return repr(self).
     |
     |  __rfloordiv__(self, value, /)
     |      Return value//self.
     |
     |  __rlshift__(self, value, /)
     |      Return value<<self.
     |
     |  __rmod__(self, value, /)
     |      Return value%self.
     |
     |  __rmul__(self, value, /)
     |      Return value*self.
     |
     |  __ror__(self, value, /)
     |      Return value|self.
     |
     |  __round__(...)
     |      Rounding an Integral returns itself.
     |      Rounding with an ndigits argument also returns an integer.
     |
     |  __rpow__(self, value, mod=None, /)
     |      Return pow(value, self, mod).
     |
     |  __rrshift__(self, value, /)
     |      Return value>>self.
     |
     |  __rshift__(self, value, /)
     |      Return self>>value.
     |
     |  __rsub__(self, value, /)
     |      Return value-self.
     |
     |  __rtruediv__(self, value, /)
     |      Return value/self.
     |
     |  __rxor__(self, value, /)
     |      Return value^self.
     |
     |  __sizeof__(self, /)
     |      Returns size in memory, in bytes.
     |
     |  __str__(self, /)
     |      Return str(self).
     |
     |  __sub__(self, value, /)
     |      Return self-value.
     |
     |  __truediv__(self, value, /)
     |      Return self/value.
     |
     |  __trunc__(...)
     |      Truncating an Integral returns itself.
     |
     |  __xor__(self, value, /)
     |      Return self^value.
     |
     |  bit_length(self, /)
     |      Number of bits necessary to represent self in binary.
     |
     |      >>> bin(37)
     |      '0b100101'
     |      >>> (37).bit_length()
     |      6
     |
     |  conjugate(...)
     |      Returns self, the complex conjugate of any int.
     |
     |  to_bytes(self, /, length, byteorder, *, signed=False)
     |      Return an array of bytes representing an integer.
     |
     |      length
     |        Length of bytes object to use.  An OverflowError is raised if the
     |        integer is not representable with the given number of bytes.
     |      byteorder
     |        The byte order used to represent the integer.  If byteorder is 'big',
     |        the most significant byte is at the beginning of the byte array.  If
     |        byteorder is 'little', the most significant byte is at the end of the
     |        byte array.  To request the native byte order of the host system, use
     |        `sys.byteorder' as the byte order value.
     |      signed
     |        Determines whether two's complement is used to represent the integer.
     |        If signed is False and a negative integer is given, an OverflowError
     |        is raised.
     |
     |  ----------------------------------------------------------------------
     |  Class methods defined here:
     |
     |  from_bytes(bytes, byteorder, *, signed=False) from builtins.type
     |      Return the integer represented by the given array of bytes.
     |
     |      bytes
     |        Holds the array of bytes to convert.  The argument must either
     |        support the buffer protocol or be an iterable object producing bytes.
     |        Bytes and bytearray are examples of built-in objects that support the
     |        buffer protocol.
     |      byteorder
     |        The byte order used to represent the integer.  If byteorder is 'big',
     |        the most significant byte is at the beginning of the byte array.  If
     |        byteorder is 'little', the most significant byte is at the end of the
     |        byte array.  To request the native byte order of the host system, use
     |        `sys.byteorder' as the byte order value.
     |      signed
     |        Indicates whether two's complement is used to represent the integer.
     |
     |  ----------------------------------------------------------------------
     |  Static methods defined here:
     |
     |  __new__(*args, **kwargs) from builtins.type
     |      Create and return a new object.  See help(type) for accurate signature.
     |
     |  ----------------------------------------------------------------------
     |  Data descriptors defined here:
     |
     |  denominator
     |      the denominator of a rational number in lowest terms
     |
     |  imag
     |      the imaginary part of a complex number
     |
     |  numerator
     |      the numerator of a rational number in lowest terms
     |
     |  real
     |      the real part of a complex number

Aplicatia Jupyter Notebook furnizeaza utilizatorului 2 variante prin care acesta poate obtine informatii despre componenta software interogata, respectiv despre codul sursa al acesteia, daca este valabil:

- se pot obtine informatii despre componenta sw. interogata, daca dupa acesta se pune caracterul `?`:
- daca este scris in limbaj Python, se poate obtine codul sursa al componentei sw. interogate, daca dupa aceasta se pune sirul de caractere `??`:

In [6]:

    # Exemplul 3: returnarea unor informatii prin utilizarea caracterului "?"
    len?

    Help on built-in function len in module builtins:

    len(obj, /)
        Return the number of items in a container.

In cazul utilizarii obiectelor Python, aplicatia Jupyter Notebook furnizeaza programatorului functia `tab completion`, care determina afisarea unor informatii despre metodele clasei care defineste tipul obiectului considerat. Aceasta functie implica utilizarea operatorului punct (dot operator) dupa obiectul interogat si apasarea tastei Tab.

    obiect.(se apasa Tab)

In [7]:

    # Exemplul 4: utilizarea functiei "tab completion" pentru obiectele Python
    str.

    Help on class str in module builtins:

    class str(object)
     |  str(object='') -> str
     |  str(bytes_or_buffer[, encoding[, errors]]) -> str
     |
     |  Create a new string object from the given object. If encoding or
     |  errors is specified, then the object must expose a data buffer
     |  that will be decoded using the given encoding and error handler.
     |  Otherwise, returns the result of object.__str__() (if defined)
     |  or repr(object).
     |  encoding defaults to sys.getdefaultencoding().
     |  errors defaults to 'strict'.
     |
     |  Methods defined here:
     |
     |  __add__(self, value, /)
     |      Return self+value.
     |
     |  __contains__(self, key, /)
     |      Return key in self.
     |
     |  __eq__(self, value, /)
     |      Return self==value.
     |
     |  __format__(self, format_spec, /)
     |      Return a formatted version of the string as described by format_spec.
     |
     |  __ge__(self, value, /)
     |      Return self>=value.
     |
     |  __getattribute__(self, name, /)
     |      Return getattr(self, name).
     |
     |  __getitem__(self, key, /)
     |      Return self[key].
     |
     |  __getnewargs__(...)
     |
     |  __gt__(self, value, /)
     |      Return self>value.
     |
     |  __hash__(self, /)
     |      Return hash(self).
     |
     |  __iter__(self, /)
     |      Implement iter(self).
     |
     |  __le__(self, value, /)
     |      Return self<=value.
     |
     |  __len__(self, /)
     |      Return len(self).
     |
     |  __lt__(self, value, /)
     |      Return self<value.
     |
     |  __mod__(self, value, /)
     |      Return self%value.
     |
     |  __mul__(self, value, /)
     |      Return self*value.
     |
     |  __ne__(self, value, /)
     |      Return self!=value.
     |
     |  __repr__(self, /)
     |      Return repr(self).
     |
     |  __rmod__(self, value, /)
     |      Return value%self.
     |
     |  __rmul__(self, value, /)
     |      Return value*self.
     |
     |  __sizeof__(self, /)
     |      Return the size of the string in memory, in bytes.
     |
     |  __str__(self, /)
     |      Return str(self).
     |
     |  capitalize(self, /)
     |      Return a capitalized version of the string.
     |
     |      More specifically, make the first character have upper case and the rest lower
     |      case.
     |
     |  casefold(self, /)
     |      Return a version of the string suitable for caseless comparisons.
     |
     |  center(self, width, fillchar=' ', /)
     |      Return a centered string of length width.
     |
     |      Padding is done using the specified fill character (default is a space).
     |
     |  count(...)
     |      S.count(sub[, start[, end]]) -> int
     |
     |      Return the number of non-overlapping occurrences of substring sub in
     |      string S[start:end].  Optional arguments start and end are
     |      interpreted as in slice notation.
     |
     |  encode(self, /, encoding='utf-8', errors='strict')
     |      Encode the string using the codec registered for encoding.
     |
     |      encoding
     |        The encoding in which to encode the string.
     |      errors
     |        The error handling scheme to use for encoding errors.
     |        The default is 'strict' meaning that encoding errors raise a
     |        UnicodeEncodeError.  Other possible values are 'ignore', 'replace' and
     |        'xmlcharrefreplace' as well as any other name registered with
     |        codecs.register_error that can handle UnicodeEncodeErrors.
     |
     |  endswith(...)
     |      S.endswith(suffix[, start[, end]]) -> bool
     |
     |      Return True if S ends with the specified suffix, False otherwise.
     |      With optional start, test S beginning at that position.
     |      With optional end, stop comparing S at that position.
     |      suffix can also be a tuple of strings to try.
     |
     |  expandtabs(self, /, tabsize=8)
     |      Return a copy where all tab characters are expanded using spaces.
     |
     |      If tabsize is not given, a tab size of 8 characters is assumed.
     |
     |  find(...)
     |      S.find(sub[, start[, end]]) -> int
     |
     |      Return the lowest index in S where substring sub is found,
     |      such that sub is contained within S[start:end].  Optional
     |      arguments start and end are interpreted as in slice notation.
     |
     |      Return -1 on failure.
     |
     |  format(...)
     |      S.format(*args, **kwargs) -> str
     |
     |      Return a formatted version of S, using substitutions from args and kwargs.
     |      The substitutions are identified by braces ('{' and '}').
     |
     |  format_map(...)
     |      S.format_map(mapping) -> str
     |
     |      Return a formatted version of S, using substitutions from mapping.
     |      The substitutions are identified by braces ('{' and '}').
     |
     |  index(...)
     |      S.index(sub[, start[, end]]) -> int
     |
     |      Return the lowest index in S where substring sub is found,
     |      such that sub is contained within S[start:end].  Optional
     |      arguments start and end are interpreted as in slice notation.
     |
     |      Raises ValueError when the substring is not found.
     |
     |  isalnum(self, /)
     |      Return True if the string is an alpha-numeric string, False otherwise.
     |
     |      A string is alpha-numeric if all characters in the string are alpha-numeric and
     |      there is at least one character in the string.
     |
     |  isalpha(self, /)
     |      Return True if the string is an alphabetic string, False otherwise.
     |
     |      A string is alphabetic if all characters in the string are alphabetic and there
     |      is at least one character in the string.
     |
     |  isascii(self, /)
     |      Return True if all characters in the string are ASCII, False otherwise.
     |
     |      ASCII characters have code points in the range U+0000-U+007F.
     |      Empty string is ASCII too.
     |
     |  isdecimal(self, /)
     |      Return True if the string is a decimal string, False otherwise.
     |
     |      A string is a decimal string if all characters in the string are decimal and
     |      there is at least one character in the string.
     |
     |  isdigit(self, /)
     |      Return True if the string is a digit string, False otherwise.
     |
     |      A string is a digit string if all characters in the string are digits and there
     |      is at least one character in the string.
     |
     |  isidentifier(self, /)
     |      Return True if the string is a valid Python identifier, False otherwise.
     |
     |      Use keyword.iskeyword() to test for reserved identifiers such as "def" and
     |      "class".
     |
     |  islower(self, /)
     |      Return True if the string is a lowercase string, False otherwise.
     |
     |      A string is lowercase if all cased characters in the string are lowercase and
     |      there is at least one cased character in the string.
     |
     |  isnumeric(self, /)
     |      Return True if the string is a numeric string, False otherwise.
     |
     |      A string is numeric if all characters in the string are numeric and there is at
     |      least one character in the string.
     |
     |  isprintable(self, /)
     |      Return True if the string is printable, False otherwise.
     |
     |      A string is printable if all of its characters are considered printable in
     |      repr() or if it is empty.
     |
     |  isspace(self, /)
     |      Return True if the string is a whitespace string, False otherwise.
     |
     |      A string is whitespace if all characters in the string are whitespace and there
     |      is at least one character in the string.
     |
     |  istitle(self, /)
     |      Return True if the string is a title-cased string, False otherwise.
     |
     |      In a title-cased string, upper- and title-case characters may only
     |      follow uncased characters and lowercase characters only cased ones.
     |
     |  isupper(self, /)
     |      Return True if the string is an uppercase string, False otherwise.
     |
     |      A string is uppercase if all cased characters in the string are uppercase and
     |      there is at least one cased character in the string.
     |
     |  join(self, iterable, /)
     |      Concatenate any number of strings.
     |
     |      The string whose method is called is inserted in between each given string.
     |      The result is returned as a new string.
     |
     |      Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
     |
     |  ljust(self, width, fillchar=' ', /)
     |      Return a left-justified string of length width.
     |
     |      Padding is done using the specified fill character (default is a space).
     |
     |  lower(self, /)
     |      Return a copy of the string converted to lowercase.
     |
     |  lstrip(self, chars=None, /)
     |      Return a copy of the string with leading whitespace removed.
     |
     |      If chars is given and not None, remove characters in chars instead.
     |
     |  partition(self, sep, /)
     |      Partition the string into three parts using the given separator.
     |
     |      This will search for the separator in the string.  If the separator is found,
     |      returns a 3-tuple containing the part before the separator, the separator
     |      itself, and the part after it.
     |
     |      If the separator is not found, returns a 3-tuple containing the original string
     |      and two empty strings.
     |
     |  replace(self, old, new, count=-1, /)
     |      Return a copy with all occurrences of substring old replaced by new.
     |
     |        count
     |          Maximum number of occurrences to replace.
     |          -1 (the default value) means replace all occurrences.
     |
     |      If the optional argument count is given, only the first count occurrences are
     |      replaced.
     |
     |  rfind(...)
     |      S.rfind(sub[, start[, end]]) -> int
     |
     |      Return the highest index in S where substring sub is found,
     |      such that sub is contained within S[start:end].  Optional
     |      arguments start and end are interpreted as in slice notation.
     |
     |      Return -1 on failure.
     |
     |  rindex(...)
     |      S.rindex(sub[, start[, end]]) -> int
     |
     |      Return the highest index in S where substring sub is found,
     |      such that sub is contained within S[start:end].  Optional
     |      arguments start and end are interpreted as in slice notation.
     |
     |      Raises ValueError when the substring is not found.
     |
     |  rjust(self, width, fillchar=' ', /)
     |      Return a right-justified string of length width.
     |
     |      Padding is done using the specified fill character (default is a space).
     |
     |  rpartition(self, sep, /)
     |      Partition the string into three parts using the given separator.
     |
     |      This will search for the separator in the string, starting at the end. If
     |      the separator is found, returns a 3-tuple containing the part before the
     |      separator, the separator itself, and the part after it.
     |
     |      If the separator is not found, returns a 3-tuple containing two empty strings
     |      and the original string.
     |
     |  rsplit(self, /, sep=None, maxsplit=-1)
     |      Return a list of the words in the string, using sep as the delimiter string.
     |
     |        sep
     |          The delimiter according which to split the string.
     |          None (the default value) means split according to any whitespace,
     |          and discard empty strings from the result.
     |        maxsplit
     |          Maximum number of splits to do.
     |          -1 (the default value) means no limit.
     |
     |      Splits are done starting at the end of the string and working to the front.
     |
     |  rstrip(self, chars=None, /)
     |      Return a copy of the string with trailing whitespace removed.
     |
     |      If chars is given and not None, remove characters in chars instead.
     |
     |  split(self, /, sep=None, maxsplit=-1)
     |      Return a list of the words in the string, using sep as the delimiter string.
     |
     |      sep
     |        The delimiter according which to split the string.
     |        None (the default value) means split according to any whitespace,
     |        and discard empty strings from the result.
     |      maxsplit
     |        Maximum number of splits to do.
     |        -1 (the default value) means no limit.
     |
     |  splitlines(self, /, keepends=False)
     |      Return a list of the lines in the string, breaking at line boundaries.
     |
     |      Line breaks are not included in the resulting list unless keepends is given and
     |      true.
     |
     |  startswith(...)
     |      S.startswith(prefix[, start[, end]]) -> bool
     |
     |      Return True if S starts with the specified prefix, False otherwise.
     |      With optional start, test S beginning at that position.
     |      With optional end, stop comparing S at that position.
     |      prefix can also be a tuple of strings to try.
     |
     |  strip(self, chars=None, /)
     |      Return a copy of the string with leading and trailing whitespace removed.
     |
     |      If chars is given and not None, remove characters in chars instead.
     |
     |  swapcase(self, /)
     |      Convert uppercase characters to lowercase and lowercase characters to uppercase.
     |
     |  title(self, /)
     |      Return a version of the string where each word is titlecased.
     |
     |      More specifically, words start with uppercased characters and all remaining
     |      cased characters have lower case.
     |
     |  translate(self, table, /)
     |      Replace each character in the string using the given translation table.
     |
     |        table
     |          Translation table, which must be a mapping of Unicode ordinals to
     |          Unicode ordinals, strings, or None.
     |
     |      The table must implement lookup/indexing via __getitem__, for instance a
     |      dictionary or list.  If this operation raises LookupError, the character is
     |      left untouched.  Characters mapped to None are deleted.
     |
     |  upper(self, /)
     |      Return a copy of the string converted to uppercase.
     |
     |  zfill(self, width, /)
     |      Pad a numeric string with zeros on the left, to fill a field of the given width.
     |
     |      The string is never truncated.
     |
     |  ----------------------------------------------------------------------
     |  Static methods defined here:
     |
     |  __new__(*args, **kwargs) from builtins.type
     |      Create and return a new object.  See help(type) for accurate signature.
     |
     |  maketrans(x, y=None, z=None, /)
     |      Return a translation table usable for str.translate().
     |
     |      If there is only one argument, it must be a dictionary mapping Unicode
     |      ordinals (integers) or characters to Unicode ordinals, strings or None.
     |      Character keys will be then converted to ordinals.
     |      If there are two arguments, they must be strings of equal length, and
     |      in the resulting dictionary, each character in x will be mapped to the
     |      character at the same position in y. If there is a third argument, it
     |      must be a string, whose characters will be mapped to None in the result.

In cazul utilizarii functiilor, sau a metodelor claselor Python, aplicatia Jupyter Notebook furnizeaza programatorului functia `tab completion`, care determina afisarea unor informatii despre functiile, sau metodele interogate - se afiseaza docstring-ul functiei/metodei interogate. Aceasta functie implica scrierea denumirii functiei, sau a metodei interogate si apasarea combinatiei de taste Shift + Tab, sau Shift + 2xTab, sau Shift + 3 x Tab; fiecare varianta extinde continutul informatiilor afisate.

    obiect.metoda(se apasa Shift + Tab)

In [8]:

    # Exemplul 5: utilizarea functiei tab completion pentru functiile / metodele Python
    'hello'.replace

Out[8]:

    <function str.replace(old, new, count=-1, /)>

# 4. Tipuri de erori¶

## Erori de sintaxa (syntax errors)¶

Sunt erori generate de nerespectarea regulilor de sintaxa care alcatuiesc limbajul Python. Aceste erori sunt identificate de catre interpretor, la analizarea codului sursa.

## Erori de executie (run-time errors)¶

Sunt erori generate de logica programului, in conditiile in care sintaxa codului este corecta. Aceste erori sunt identificate de catre interpretor, la executia codului sursa si se numesc exceptii sau erori de executie runt-time errors.

Atunci cand este depistata o eroare de catre interpretorul Python, acesta furnizeaza o serie de informatii care ajuta programatorul sa depaneze eroarea. Daca eroarea depistata este de executie, interpretorul Python ajuta si la localizarea erorii respective. Localizarea erorii de executie este realizata pe baza unei inregistrari, denumita traceback, care urmareste operatiile efectuate la executia programului.

In [9]:

    # Exemplul 6: exemplu de eroare de sintaxa
    message = "Hello Python!"
    print message

      File "<ipython-input-9-0c605f81c6a4>", line 3
        print message
                    ^
    SyntaxError: Missing parentheses in call to 'print'. Did you mean print(message)?

In [10]:

    # Exemplul 7: exemplu de eroare de executie
    message = "Hello Python!"
    print (message)
    x = 1/0
    print(x)

    Hello Python!

    ---------------------------------------------------------------------------
    ZeroDivisionError                         Traceback (most recent call last)
    <ipython-input-10-5674fa76223b> in <module>
          2 message = "Hello Python!"
          3 print (message)
    ----> 4 x = 1/0
          5 print(x)

    ZeroDivisionError: division by zero