Διαδρομές
/
Python
Python
/
Ύλη
/
Τα βασικά
Τα

Τα βασικά σε Python

113 ασκήσεις

Σχετικά με την έννοια Τα βασικά

Η Python είναι μια δυναμικά και ισχυρά τυποποιημένη γλώσσα προγραμματισμού. Χρησιμοποιεί και duck typing και βαθμιαία τυποποίηση, μέσω υποδείξεων τύπων. Υποστηρίζονται και τα τρία στυλ προγραμματισμού, ο προστακτικός, ο δηλωτικός (π.χ. ο συναρτησιακός) και ο αντικειμενοστρεφής, αλλά εσωτερικά τα πάντα στην Python είναι αντικείμενα.

Η Python δίνει μεγάλη έμφαση στην αναγνωσιμότητα του κώδικα και (όπως και η Haskell) χρησιμοποιεί σημαντικές εσοχές για να δηλώσει ορισμούς συναρτήσεων, μεθόδων και κλάσεων.

Η Python δημιουργήθηκε από τον Guido van Rossum και κυκλοφόρησε για πρώτη φορά το 1991. Το Python Software Foundation διαχειρίζεται και κατευθύνει πόρους για την ανάπτυξη της Python και της CPython και δέχεται προτάσεις για αλλαγές στη γλώσσα από μέλη της κοινότητας μέσω των προτάσεων βελτίωσης της Python, ή PEPs.

Η πλήρης τεκμηρίωση για την τρέχουσα έκδοση βρίσκεται στο docs.python.org.


Αυτή η πρώτη έννοια παρουσιάζει 4 βασικά χαρακτηριστικά της γλώσσας Python:

  1. Ανάθεση ονόματος (μεταβλητές και σταθερές),
  2. Συναρτήσεις (η λέξη-κλειδί def και η λέξη-κλειδί return),
  3. Σχόλια, και
  4. Docstrings.
Note

Γενικά, το περιεχόμενο, τα tests και τα εργαλεία ανάλυσης για το track Python ακολουθούν τις συμβάσεις στυλ που περιγράφονται στα PEP 8 και PEP 257 για το στυλ κώδικα Python, με την επιπλέον (ισχυρή) σύσταση να μην υπάρχουν ονόματα μεταβλητών με ένα μόνο γράμμα.

Το zen of Python (PEP 20) και το What is Pythonic? παραθέτουν επιπλέον φιλοσοφίες.

Στο track Python, οι μεταβλητές γράφονται πάντα σε snake_case και οι σταθερές σε SCREAMING_SNAKE_CASE

Ανάθεση ονόματος (Μεταβλητές και σταθερές)

Στην Python, δεν χρησιμοποιούνται λέξεις-κλειδιά για τη δημιουργία μεταβλητών ή σταθερών. Αντ' αυτού, οι προγραμματιστές μπορούν να δεσμεύσουν ονόματα (που ονομάζονται και μεταβλητές) σε οποιονδήποτε τύπο αντικειμένου χρησιμοποιώντας τον τελεστή ανάθεσης =: <name> = <value>. Ένα όνομα μπορεί να ανατεθεί ξανά (ή να δεσμευτεί ξανά) σε διαφορετικές τιμές (διαφορετικούς τύπους αντικειμένων) κατά τη διάρκεια της ζωής του.

Για παράδειγμα, η my_first_variable μπορεί να ανατεθεί ξανά πολλές φορές χρησιμοποιώντας το =, και μπορεί να αναφέρεται σε διαφορετικούς τύπους αντικειμένων σε κάθε επανανάθεση:

>>> my_first_variable = 1  # my_first_variable bound to an integer object of value one.
>>> my_first_variable = 2  # my_first_variable re-assigned to integer value 2.

>>> print(type(my_first_variable))
<class 'int'>

>>> print(my_first_variable)
2

>>> my_first_variable = "Now, I'm a string." # <--You may re-bind a name to a different object type and value.
>>> print(type(my_first_variable))
<class 'str'>

>>> my_first_variable = 'You can call me "str".' # <--Strings can be declared using single or double quote marks.
>>> print(my_first_variable)
You can call me "str".

>>> import collections
>>> my_first_variable = collections.Counter([1,1,2,3,3,3,4,5,6,7]) # <--Now my_first_variable has been re-bound to a Counter object.
>>> print(type(my_first_variable))
<class 'collections.Counter'>

>>> print(my_first_variable)
Counter({3: 3, 1: 2, 2: 1, 4: 1, 5: 1, 6: 1, 7: 1})

Σταθερές

Οι σταθερές είναι ονόματα που προορίζονται να ανατεθούν μόνο μία φορά σε ένα πρόγραμμα. Πρέπει να ορίζονται σε επίπεδο άρθρωματος (αρχείου) και είναι συνήθως ορατές σε όλες τις συναρτήσεις και τις κλάσεις του προγράμματος. Η χρήση του SCREAMING_SNAKE_CASE δηλώνει ότι το όνομα δεν πρέπει να ανατεθεί ξανά ούτε να μεταβληθεί η τιμή του.

# All caps signal that this is intended as a constant.
MY_FIRST_CONSTANT = 16

# Re-assignment will be allowed by the compiler & interpreter,
# but this is VERY strongly discouraged.
# Please don't do this, it could create problems in your program!
MY_FIRST_CONSTANT = "Some other value"

Συναρτήσεις

Στην Python, οι μονάδες λειτουργικότητας ενσωματώνονται σε συναρτήσεις, οι οποίες είναι και οι ίδιες αντικείμενα (είναι χελώνες μέχρι κάτω).

Οι συναρτήσεις μπορούν να εκτελεστούν μόνες τους, να περαστούν ως ορίσματα σε άλλες συναρτήσεις, να εμφωλευτούν ή να δεσμευτούν σε μια κλάση. Όταν οι συναρτήσεις δεσμεύονται σε ένα όνομα κλάσης, αναφέρονται ως μέθοδοι. Σχετικές συναρτήσεις και κλάσεις (μαζί με τις μεθόδους τους) μπορούν να ομαδοποιηθούν στο ίδιο αρχείο ή άρθρωμα και να εισαχθούν εν μέρει ή ολόκληρες για χρήση σε άλλα προγράμματα.

Η λέξη-κλειδί def ξεκινά έναν ορισμό συνάρτησης. Κάθε συνάρτηση μπορεί να έχει μηδέν ή περισσότερες τυπικές παραμέτρους μέσα σε παρενθέσεις (), που ακολουθούνται από άνω κάτω τελεία :. Οι εντολές για το σώμα της συνάρτησης ξεκινούν στην επόμενη γραμμή μετά το def και πρέπει να έχουν εσοχή σε μπλοκ:

# The body of a function is indented by 2 spaces & prints the sum of the numbers.
def add_two_numbers(number_one, number_two):
  total = number_one + number_two
  print(total)  

>>> add_two_numbers(3, 4)
7


# Inconsistent indentation in your code blocks will raise an error.
>>> def add_three_numbers_misformatted(number_one, number_two, number_three):
...     result = number_one + number_two + number_three   # This was indented by 4 spaces.
...    print(result)     # <--This was only indented by 3 spaces.
...
...
  File "<stdin>", line 3
    print(result)
    ^
IndentationError: unindent does not match any outer indentation level

Οι συναρτήσεις επιστρέφουν ρητά μια τιμή ή ένα αντικείμενο μέσω της λέξης-κλειδιού return:

# Function definition on first line, explicit return used on final line.
def add_two_numbers(number_one, number_two):
  return number_one + number_two   


# Calling the function in the Python shell returns the sum of the numbers.
>>> add_two_numbers(3, 4)
7

# Assigning the function call to a variable and printing 
# the variable will also return the value.
>>> sum_with_return = add_two_numbers(5, 6)
>>> print(sum_with_return)
11

Οι συναρτήσεις που δεν έχουν ρητή έκφραση μετά το return επιστρέφουν σιωπηρά το αντικείμενο None. Οι λεπτομέρειες του None θα καλυφθούν σε επόμενη έννοια. Για τους σκοπούς αυτής της άσκησης και της εξήγησης, το None είναι ένα σύμβολο θέσης που αντιπροσωπεύει το τίποτα, ή το null:


# This function will return `None`
def square_a_number(number):
    square = number * number
    return # <-- note that this return is not followed by an expression

# Calling the function in the Python shell appears 
# to not return anything at all.
>>> square_a_number(2)
>>>


# Using print() with the function call shows that 
# the function is actually returning the **None** object.
>>> print(square_a_number(2))
None

Οι συναρτήσεις που παραλείπουν το return επιστρέφουν επίσης σιωπηρά το αντικείμενο None. Αυτό σημαίνει ότι αν δεν χρησιμοποιήσεις το return σε μια συνάρτηση, η Python θα επιστρέψει το αντικείμενο None για εσένα.


# This function omits a return keyword altogether
def add_two_numbers(number_one, number_two):
  result = number_one + number_two

>>> add_two_numbers(5, 7)
>>> print(add_two_numbers(5, 7))
None

# Assigning the function call to a variable and printing 
# the variable will also show None.
>>> sum_without_return = add_two_numbers(5, 6)
>>> print(sum_without_return)
None

Κλήση συναρτήσεων

Οι συναρτήσεις καλούνται χρησιμοποιώντας το όνομά τους ακολουθούμενο από (). Η σημειογραφία με τελεία (.) χρησιμοποιείται για την κλήση συναρτήσεων που έχουν οριστεί μέσα σε μια κλάση ή ένα άρθρωμα.

>>> def raise_to_power(number, power):
...     return number ** power
...

>>> raise_to_power(3,3) # Invoking the function with the arguments 3 and 3.
27


# A mis-match between the number of parameters and the number of arguments will raise an error.
>>> raise_to_power(4,)
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: raise_to_power() missing 1 required positional argument: 'power'


# Calling methods or functions in classes and modules.
>>> start_text = "my silly sentence for examples."
>>> str.upper(start_text)  # <--Calling the upper() method from the built-in str class on start_text.
'MY SILLY SENTENCE FOR EXAMPLES.'

# Because a string is an instance of the str class, methods can also be called on them "directly".
>>> start_text = "my silly sentence for examples."
>>> start_text.upper()  # <--Calling the upper() method on start_text directly.
'MY SILLY SENTENCE FOR EXAMPLES.'

# Alternatively, we can skip the variable assignment (although this gets messy quick).
>>> "my silly sentence for examples.".upper()
'MY SILLY SENTENCE FOR EXAMPLES.'


# Importing the math module
>>> import math
>>> math.pow(2,4)  # <--Calling the pow() function from the math module.
16.0

Σχόλια

Τα σχόλια στην Python ξεκινούν με ένα # που δεν είναι μέρος μιας συμβολοσειράς και τελειώνουν στο τέλος της γραμμής. Σε αντίθεση με πολλές άλλες γλώσσες προγραμματισμού, η Python δεν υποστηρίζει σημάδια σχολίων πολλαπλών γραμμών. Κάθε γραμμή ενός μπλοκ σχολίων πρέπει να ξεκινά με τον χαρακτήρα #.

Τα σχόλια αγνοούνται από τον διερμηνευτή:

# This is a single line comment.

x = "foo"  # This is an in-line comment.

# This is a multi-line
# comment block over multiple lines --
# these should be used sparingly.

Docstrings

Η πρώτη εντολή του σώματος μιας συνάρτησης μπορεί προαιρετικά να είναι ένα docstring, το οποίο συνοψίζει με συντομία τον σκοπό της συνάρτησης ή του αντικειμένου. Τα docstrings δηλώνονται με τριπλά διπλά εισαγωγικά (""") σε εσοχή στο ίδιο επίπεδο με το μπλοκ κώδικα:

# An example from PEP257 of a multi-line docstring
# reformatted to use Google style non-type hinted docstrings.
# Some additional details can be found in the Sphinx documentation:
# https://www.sphinx-doc.org/en/master/usage/extensions/napoleon.html#getting-started

def complex(real=0.0, imag=0.0):
    """Form a complex number.

    Keyword Arguments:
        real (float): The real part of the number (default 0.0)
        imag (float): The imaginary part of the number (default 0.0)
        
    """

    if imag == 0.0 and real == 0.0:
        return complex_zero

Τα docstrings διαβάζονται από αυτοματοποιημένα εργαλεία τεκμηρίωσης και επιστρέφονται καλώντας το ειδικό χαρακτηριστικό .__doc__ στο όνομα της συνάρτησης, της μεθόδου ή της κλάσης. Συνιστώνται για προγράμματα οποιουδήποτε μεγέθους όπου χρειάζεται τεκμηρίωση, και οι συμβάσεις τους περιγράφονται στο PEP257.

Τα docstrings μπορούν επίσης να λειτουργήσουν ως ελαφριά unit tests, τα οποία μπορούν να διαβαστούν και να εκτελεστούν από το PyTest ή εισάγοντας το άρθρωμα doctest. Τα tests και το doctest θα καλυφθούν σε επόμενη έννοια.

# An example on a user-defined function using a Google style docstring. 
>>> def raise_to_power(number, power):
    """Raise a number to an arbitrary power.

    Parameters:
        number (int): The base number.
        power (int): The power to raise the base number to.
    
    Returns:
        int: The number raised to the specified power.
    
    Takes a number and raises it to the specified power, returning the result.

    """

    return number ** power
...

# Calling the .__doc__ attribute of the function and printing the result.
>>> print(raise_to_power.__doc__)
Raise a number to an arbitrary power.

Parameters:
    number (int): The base number.
    power (int): The power to raise the base number to.

Returns:
    int: The number raised to the specified power.

Takes a number and raises it to the specified power, returning the result.

...

# Printing the __doc__ attribute of the built-in type: str.
>>> print(str.__doc__)
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 'utf-8'.
errors defaults to 'strict'.
Επεξεργασία μέσω GitHub Ο σύνδεσμος ανοίγει σε νέο παράθυρο ή καρτέλα

Μάθε την έννοια Τα βασικά