Βρ

Βρόχοι σε Python

93 ασκήσεις

Σχετικά με την έννοια Βρόχοι

Η Python έχει δύο δομές επανάληψης. Οι βρόχοι while για αόριστη (μη μετρημένη) επανάληψη και οι βρόχοι for για ορισμένη, (μετρημένη) επανάληψη. Οι λέξεις-κλειδιά break, continue και else βοηθούν στην προσαρμογή της συμπεριφοράς των βρόχων. Τα range() και enumerate() βοηθούν στη μέτρηση και στην εύρεση θέσεων μέσα στους βρόχους.

While

Οι while βρόχοι συνεχίζουν να εκτελούνται όσο η loop expression ή η "δοκιμή" αποτιμάται σε True μέσα σε ένα boolean context, και τερματίζουν όταν αποτιμηθεί σε False:

# Lists are considered "truthy" in a boolean context if they
# contain one or more values, and "falsy" if they are empty.

>>> placeholders = ["spam", "ham", "eggs", "green_spam", "green_ham", "green_eggs"]

>>> while placeholders:
...     print(placeholders.pop(0))
...
'spam'
'ham'
'eggs'
'green_spam'
'green_ham'
'green_eggs'

For

Ο βασικός for loop στην Python περιγράφεται καλύτερα ως ένα for each που διατρέχει τις τιμές οποιουδήποτε αντικειμένου iterable, τερματίζοντας όταν δεν επιστρέφονται άλλες τιμές από την κλήση της next() (πετώντας μια StopIteration).

>>> word_list = ["bird", "chicken", "barrel", "bongo"]

>>> for word in word_list:
...    if word.startswith("b"):
...        print(f"{word.title()} starts with a B.")
...    else:
...        print(f"{word.title()} doesn't start with a B.")
...
'Bird starts with a B.'
'Chicken doesn\'t start with a B.'
'Barrel starts with a B.'
'Bongo starts with a B.'

Αντικείμενο ακολουθίας range()

Όταν δεν δίνεται κάποιο συγκεκριμένο iterable, η ειδική ακολουθία range() χρησιμοποιείται ως μετρητής βρόχου. Η range() απαιτεί ένα int στο οποίο θα κάνει stop η ακολουθία, και μπορεί προαιρετικά να δεχτεί τις παραμέτρους start και step. Αν δεν δοθεί αριθμός start, η ακολουθία θα ξεκινήσει από το 0. Τα αντικείμενα range() είναι lazy (οι τιμές παράγονται κατόπιν αιτήματος), υποστηρίζουν όλες τις κοινές πράξεις ακολουθιών και καταλαμβάνουν σταθερή ποσότητα μνήμης, ανεξάρτητα από το μήκος της ακολουθίας που ορίζεται. Έχει ενδιαφέρον ότι η range() δεν είναι iterator και μπορεί να χρησιμοποιηθεί σε πολλά πλαίσια εκτός βρόχων όπου χρειάζεται μια ακολουθία αριθμών.

# Here we use range to produce some numbers, rather than creating a list of them in memory.
# The values will start with 1 and stop *before* 7.

>>> for number in range(1, 7):
...    if number % 2 == 0:
...       print(f"{number} is even.")
...    else:
...       print(f"{number} is odd.")
'1 is odd.'
'2 is even.'
'3 is odd.'
'4 is even.'
'5 is odd.'
'6 is even.'

# range() can also take a *step* parameter.
# Here we use range to produce only the "odd" numbers, starting with 3 and stopping *before* 15.

>>> for number in range(3, 15, 2):
...    if number % 2 == 0:
...       print(f"{number} is even.")
...    else:
...       print(f"{number} is odd.")
...
'3 is odd.'
'5 is odd.'
'7 is odd.'
'9 is odd.'
'11 is odd.'
'13 is odd.'

Τιμές και θέσεις με enumerate()

Αν χρειάζονται και οι τιμές και οι θέσεις, η ενσωματωμένη enumerate(<iterable>) επιστρέφει έναν iterator πάνω από ζεύγη (index, value):

>>> word_list = ["bird", "chicken", "barrel", "apple"]

# *index* and *word* are the loop variables.
# Loop variables can be any valid python name.

>>> for index, word in enumerate(word_list):
...    if word.startswith("b"):
...        print(f"{word.title()} (at index {index}) starts with a B.")
...    else:
...        print(f"{word.title()} (at index {index}) doesn't start with a B.")
...
'Bird (at index 0) starts with a B.'
'Chicken (at index 1) doesn\'t start with a B.'
'Barrel (at index 2) starts with a B.'
'Apple (at index 3) doesn\'t start with a B.'


# The same method can be used as a "lookup" for pairing items between two lists.
# Of course, if the lengths or indexes don't line up, this doesn't work.

>>> word_list = ["cat", "chicken", "barrel", "apple", "spinach"]
>>> category_list = ["mammal", "bird", "thing", "fruit", "vegetable"]

>>> for index, word in enumerate(word_list):
...    print(f"{word.title()} is in category: {category_list[index]}.")
...
'Cat is in category: mammal.'
'Chicken is in category: bird.'
'Barrel is in category: thing.'
'Apple is in category: fruit.'
'Spinach is in category: vegetable.'

Η ίδια μέθοδος μπορεί να χρησιμοποιηθεί ως "αναζήτηση" για το ταίριασμα στοιχείων ανάμεσα σε δύο λίστες. Φυσικά, αν τα μήκη ή οι θέσεις δεν ευθυγραμμίζονται, αυτό δεν δουλεύει.

Η συνάρτηση enumerate(<iterable>) μπορεί επίσης να ρυθμιστεί ώστε να κάνει start τη μέτρηση των θέσεων από διαφορετικό αριθμό:

# Here, the index count will start at 1.
>>> for position, word in enumerate(word_list, start=1):
...    if word.startswith("b"):
...        print(f"{word.title()} (at position {position}) starts with a B.")
...    else:
...        print(f"{word.title()} (at position {position}) doesn't start with a B.")
...
'Bird (at position 1) starts with a B.'
'Chicken (at position 2) doesn\'t start with a B.'
'Barrel (at position 3) starts with a B.'
'Apple (at position 4) doesn\'t start with a B.'

Αλλάζοντας τη συμπεριφορά του βρόχου

Η λέξη-κλειδί continue μπορεί να χρησιμοποιηθεί για να προχωρήσεις στον επόμενο κύκλο επανάληψης:

>>> word_list = ["bird", "chicken", "barrel", "bongo", "sliver", "apple", "bear"]
...
... # This will skip *bird*, at index 0
... for index, word in enumerate(word_list):
...     if index == 0:
...         continue
...     if word.startswith("b"):
...         print(f"{word.title()} (at index {index}) starts with a b.")
...
'Barrel (at index 2) starts with a b.'
'Bongo (at index 3) starts with a b.'
'Bear (at index 6) starts with a b.'

Η λέξη-κλειδί break (όπως σε πολλές γλώσσες που μοιάζουν με τη C) μπορεί να χρησιμοποιηθεί για να σταματήσει η επανάληψη και να "βγεις" από τον πιο εσωτερικό loop που την περιβάλλει:

>>>  word_list = ["bird", "chicken", "barrel", "bongo", "sliver", "apple"]

>>> for index, word in enumerate(word_list):
...    if word.startswith("b"):
...        print(f"{word.title()} (at index {index}) starts with a B.")
...    elif word == "sliver":
...        break
...    else:
...        print(f"{word.title()} doesn't start with a B.")
... print("loop broken.")
...
'Bird (at index 0) starts with a B.'
'Chicken doesn\'t start with a B.'
'Barrel (at index 2) starts with a B.'
'Bongo (at index 3) starts with a B.'
'loop broken.'

Η ρήτρα else του βρόχου είναι μοναδική στην Python και μπορεί να χρησιμοποιηθεί για ενέργειες "ολοκλήρωσης" ή "κατακλείδας" όταν η επανάληψη έχει εξαντληθεί. Οι εντολές που ακολουθούν τη λέξη-κλειδί else δεν εκτελούνται αν η επανάληψη τερματιστεί μέσω break:

>>> word_list = ["bird", "chicken", "barrel", "bongo", "sliver", "apple"]

# Using enumerate to get both an index and a value.

>>> for index, word in enumerate(word_list):
...    word = word.title()
...    if word.startswith("B"):
...        print(f"{word} (at index {index}) starts with a B.")
...
... # This executes once *StopIteration* is raised and 
... # There are no more items to iterate through.
... # Note the indentation, which lines up with the for keyword.
... else:
...    print(f"Found the above b-words, out of {len(word_list)} words in the word list.")
...
'Bird (at index 0) starts with a B.'
'Barrel (at index 2) starts with a B.'
'Bongo (at index 3) starts with a B.'
'Found the above b-words, out of 6 words in the word list.'


# Terminating a loop via *break* will bypass the loop *else* clause

>>> for index, word in enumerate(word_list):
...    word = word.title()
...    if word.startswith("B"):
...       print(f"{word} (at index {index}) starts with a B.")
...    if word.startswith("S"):
...        print("Found an S, stopping iteration.")
...        break

... # This statement does not run, because a *break* was triggered.
... else:
...    print(f"Found the above b-words, out of {len(word_list)} words in the word list.")
...
'Bird (at index 0) starts with a B.'
'Barrel (at index 2) starts with a B.'
'Bongo (at index 3) starts with a B.'
'Found an S, stopping iteration.'
Επεξεργασία μέσω GitHub Ο σύνδεσμος ανοίγει σε νέο παράθυρο ή καρτέλα

Μάθε την έννοια Βρόχοι

Η εξάσκηση είναι κλειδωμένη

Ξεκλείδωσε 6 ακόμη ασκήσεις για να εξασκηθείς στην έννοια Βρόχοι