Λίστα λέξεων-κλειδιών στον προγραμματισμό Python

Αυτό το σεμινάριο παρέχει σύντομες πληροφορίες για όλες τις λέξεις-κλειδιά που χρησιμοποιούνται στο Python.

Οι λέξεις-κλειδιά είναι οι δεσμευμένες λέξεις στο Python. Δεν μπορούμε να χρησιμοποιήσουμε μια λέξη-κλειδί ως όνομα μεταβλητής, όνομα λειτουργίας ή οποιοδήποτε άλλο αναγνωριστικό.

Ακολουθεί μια λίστα με όλες τις λέξεις-κλειδιά στον προγραμματισμό Python

Λέξεις-κλειδιά στη γλώσσα προγραμματισμού Python
Ψευδής αναμένω αλλού εισαγωγή πέρασμα
Κανένας Διακοπή εκτός σε υψώνω
Αληθής τάξη τελικά είναι ΕΠΙΣΤΡΟΦΗ
και να συνεχίσει Για λάμδα δοκιμάστε
όπως και ορισμός από μη τοπικό ενώ
διεκδικώ δελ παγκόσμια δεν με
ασύγχρονος elif αν ή απόδοση παραγωγής

Οι παραπάνω λέξεις-κλειδιά μπορεί να τροποποιηθούν σε διαφορετικές εκδόσεις του Python. Κάποια επιπλέον ενδέχεται να προστεθούν ή κάποια να αφαιρεθούν. Μπορείτε πάντα να λάβετε τη λίστα των λέξεων-κλειδιών στην τρέχουσα έκδοση πληκτρολογώντας τα ακόλουθα στην ερώτηση.

  >>> import keyword >>> print(keyword.kwlist) ('False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield') 

Περιγραφή λέξεων-κλειδιών στο Python με παραδείγματα

Σωστό Λάθος

Trueκαι Falseείναι τιμές αλήθειας στο Python. Είναι τα αποτελέσματα των συγκρίσεων ή των λογικών (Boolean) λειτουργιών στο Python. Για παράδειγμα:

  >>> 1 == 1 True >>> 5> 3 True >>> True or False True >>> 10 >> 3> 7 False >>> True and False False 

Εδώ μπορούμε να δούμε ότι οι τρεις πρώτες δηλώσεις είναι αληθείς, έτσι ο διερμηνέας επιστρέφει Trueκαι επιστρέφει Falseγια τις υπόλοιπες τρεις δηλώσεις. Trueκαι Falseστο python είναι ίδιο με 1και 0. Αυτό μπορεί να δικαιολογηθεί με το ακόλουθο παράδειγμα:

 >>> True == 1 True >>> False == 0 True >>> True + True 2 

Κανένας

None είναι μια ειδική σταθερά στο Python που αντιπροσωπεύει την απουσία τιμής ή μηδενικής τιμής.

Είναι ένα αντικείμενο του δικού του τύπου δεδομένων, το NoneType. Δεν μπορούμε να δημιουργήσουμε πολλά Noneαντικείμενα αλλά μπορούμε να τα αντιστοιχίσουμε σε μεταβλητές. Αυτές οι μεταβλητές θα είναι ίσες μεταξύ τους.

Πρέπει να προσέξουμε που Noneδεν συνεπάγεται False, 0ή καμία κενή λίστα, λεξικό, συμβολοσειρά κ.λπ. Για παράδειγμα:

 >>> None == 0 False >>> None == () False >>> None == False False >>> x = None >>> y = None >>> x == y True 

Οι άκυρες λειτουργίες που δεν επιστρέφουν τίποτα θα επιστρέψουν ένα Noneαντικείμενο αυτόματα. Noneεπιστρέφεται επίσης από συναρτήσεις στις οποίες η ροή προγράμματος δεν αντιμετωπίζει δήλωση επιστροφής. Για παράδειγμα:

  def a_void_function(): a = 1 b = 2 c = a + b x = a_void_function() print(x) 

Παραγωγή

 Κανένας 

Αυτό το πρόγραμμα έχει μια συνάρτηση που δεν επιστρέφει μια τιμή, αν και κάνει κάποιες λειτουργίες μέσα. Έτσι, όταν εκτυπώνουμε x, παίρνουμε το Noneοποίο επιστρέφεται αυτόματα (σιωπηρά). Ομοίως, εδώ είναι ένα άλλο παράδειγμα:

 def improper_return_function(a): if (a % 2) == 0: return True x = improper_return_function(3) print(x) 

Παραγωγή

 Κανένας 

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

Εάν δώσουμε στη συνάρτηση έναν μονό αριθμό, Noneεπιστρέφεται σιωπηρά.

και, ή όχι

and, or, notΕίναι οι λογικοί τελεστές στην Python. andθα έχει ως αποτέλεσμα Trueμόνο εάν και οι δύο τελεστές True. Ο πίνακας αλήθειας για andδίνεται παρακάτω:

and Πίνακας αλήθειας για
ΕΝΑ σι Α και Β
Αληθής Αληθής Αληθής
Αληθής Ψευδής Ψευδής
Ψευδής Αληθής Ψευδής
Ψευδής Ψευδής Ψευδής

orθα οδηγήσει σε Trueεάν κάποιος από τους τελεστές είναι True. Ο πίνακας αλήθειας για orδίνεται παρακάτω:

or Πίνακας αλήθειας για
ΕΝΑ σι Α ή Β
Αληθής Αληθής Αληθής
Αληθής Ψευδής Αληθής
Ψευδής Αληθής Αληθής
Ψευδής Ψευδής Ψευδής

notο τελεστής χρησιμοποιείται για να αντιστρέψει την τιμή αλήθειας. Ο πίνακας αλήθειας για notδίνεται παρακάτω:

not Πίνακας αλήθειας για
ΕΝΑ δεν είναι
Αληθής Ψευδής
Ψευδής Αληθής

Κάποιο παράδειγμα της χρήσης τους δίνεται παρακάτω

 >>> True and False False >>> True or False True >>> not False True 

όπως και

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

Όπως για παράδειγμα, η Python έχει μια τυπική μονάδα που ονομάζεται math. Ας υποθέσουμε ότι θέλουμε να υπολογίσουμε τι cosine pi χρησιμοποιεί ένα ψευδώνυμο. Μπορούμε να το κάνουμε ως εξής χρησιμοποιώντας as:

 >>> import math as myAlias >>>myAlias.cos(myAlias.pi) -1.0 

Εδώ εισαγάγαμε τη mathμονάδα δίνοντάς της το όνομα myAlias. Τώρα μπορούμε να αναφερθούμε στην mathενότητα με αυτό το όνομα. Χρησιμοποιώντας αυτό το όνομα υπολογίσαμε cos (pi) και πήρα -1.0ως απάντηση.

διεκδικώ

assert χρησιμοποιείται για σκοπούς εντοπισμού σφαλμάτων.

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

Εάν η κατάσταση είναι αληθινή, δεν συμβαίνει τίποτα. Αν όμως η κατάσταση είναι ψευδής, AssertionErrorαυξάνεται. Για παράδειγμα:

 >>> a = 4 >>> assert a >> assert a> 5 Traceback (most recent call last): File "", line 301, in runcode File "", line 1, in AssertionError 

Για την καλύτερη κατανόησή μας, μπορούμε επίσης να παρέχουμε ένα μήνυμα προς εκτύπωση με το AssertionError.

 >>> a = 4 >>> assert a> 5, "The value of a is too small" Traceback (most recent call last): File "", line 301, in runcode File "", line 1, in AssertionError: The value of a is too small 

Σε αυτό το σημείο μπορούμε να σημειώσουμε ότι,

 assert condition, message 

είναι ισοδύναμο με,

 if not condition: raise AssertionError(message)

async, περίμενε

Η asyncκαι awaitλέξεις-κλειδιά που παρέχονται από την asyncioβιβλιοθήκη της Python. Χρησιμοποιούνται για τη σύνταξη ταυτόχρονου κώδικα στο Python. Για παράδειγμα,

 import asyncio async def main(): print('Hello') await asyncio.sleep(1) print('world')

Για να εκτελέσουμε το πρόγραμμα, χρησιμοποιούμε

 asyncio.run(main())

Στο παραπάνω πρόγραμμα, η asyncλέξη-κλειδί καθορίζει ότι η συνάρτηση θα εκτελεστεί ασύγχρονα.

Εδώ, εκτυπώνεται το πρώτο Hello. Η awaitλέξη-κλειδί κάνει το πρόγραμμα να περιμένει 1 δευτερόλεπτο. Και τότε ο κόσμος τυπώνεται.

διάλειμμα, συνέχεια

breakκαι continueχρησιμοποιούνται μέσα forκαι whileβρόχους για να αλλάξουν την κανονική συμπεριφορά τους.

break will end the smallest loop it is in and control flows to the statement immediately below the loop. continue causes to end the current iteration of the loop, but not the whole loop.

This can be illustrated with the following two examples:

 for i in range(1,11): if i == 5: break print(i) 

Output

 1 2 3 4 

Here, the for loop intends to print numbers from 1 to 10. But the if condition is met when i is equal to 5 and we break from the loop. Thus, only the range 1 to 4 is printed.

 for i in range(1,11): if i == 5: continue print(i) 

Output

 1 2 3 4 6 7 8 9 10 

Here we use continue for the same program. So, when the condition is met, that iteration is skipped. But we do not exit the loop. Hence, all the values except 5 are printed out.

Learn more about Python break and continue statement.

class

class is used to define a new user-defined class in Python.

Class is a collection of related attributes and methods that try to represent a real-world situation. This idea of putting data and functions together in a class is central to the concept of object-oriented programming (OOP).

Classes can be defined anywhere in a program. But it is a good practice to define a single class in a module. Following is a sample usage:

 class ExampleClass: def function1(parameters):… def function2(parameters):… 

Learn more about Python Objects and Class.

def

def is used to define a user-defined function.

Function is a block of related statements, which together does some specific task. It helps us organize code into manageable chunks and also to do some repetitive task.

The usage of def is shown below:

 def function_name(parameters):… 

Learn more about Python functions.

del

del is used to delete the reference to an object. Everything is object in Python. We can delete a variable reference using del

 >>> a = b = 5 >>> del a >>> a Traceback (most recent call last): File "", line 301, in runcode File "", line 1, in NameError: name 'a' is not defined >>> b 5 

Here we can see that the reference of the variable a was deleted. So, it is no longer defined. But b still exists.

del is also used to delete items from a list or a dictionary:

  >>> a = ('x','y','z') >>> del a(1) >>> a ('x', 'z') 

if, else, elif

if, else, elif are used for conditional branching or decision making.

When we want to test some condition and execute a block only if the condition is true, then we use if and elif. elif is short for else if. else is the block which is executed if the condition is false. This will be clear with the following example:

 def if_example(a): if a == 1: print('One') elif a == 2: print('Two') else: print('Something else') if_example(2) if_example(4) if_example(1) 

Output

 Two Something else One 

Here, the function checks the input number and prints the result if it is 1 or 2. Any input other than this will cause the else part of the code to execute.

Learn more about Python if and if… else Statement.

except, raise, try

except, raise, try are used with exceptions in Python.

Exceptions are basically errors that suggests something went wrong while executing our program. IOError, ValueError, ZeroDivisionError, ImportError, NameError, TypeError etc. are few examples of exception in Python. try… except blocks are used to catch exceptions in Python.

We can raise an exception explicitly with the raise keyword. Following is an example:

 def reciprocal(num): try: r = 1/num except: print('Exception caught') return return r print(reciprocal(10)) print(reciprocal(0)) 

Output

 0.1 Exception caught None 

Here, the function reciprocal() returns the reciprocal of the input number.

When we enter 10, we get the normal output of 0.1. But when we input 0, a ZeroDivisionError is raised automatically.

This is caught by our try… except block and we return None. We could have also raised the ZeroDivisionError explicitly by checking the input and handled it elsewhere as follows:

 if num == 0: raise ZeroDivisionError('cannot divide') 

finally

finally is used with try… except block to close up resources or file streams.

Using finally ensures that the block of code inside it gets executed even if there is an unhandled exception. For example:

 try: Try-block except exception1: Exception1-block except exception2: Exception2-block else: Else-block finally: Finally-block 

Here if there is an exception in the Try-block, it is handled in the except or else block. But no matter in what order the execution flows, we can rest assured that the Finally-block is executed even if there is an error. This is useful in cleaning up the resources.

Learn more about exception handling in Python programming.

for

for is used for looping. Generally we use for when we know the number of times we want to loop.

In Python we can use it with any type of sequences like a list or a string. Here is an example in which for is used to traverse through a list of names:

 names = ('John','Monica','Steven','Robin') for i in names: print('Hello '+i) 

Output

 Hello John Hello Monica Hello Steven Hello Robin 

Learn more about Python for loop.

from, import

import keyword is used to import modules into the current namespace. from… import is used to import specific attributes or functions into the current namespace. For example:

 import math 

will import the math module. Now we can use the cos() function inside it as math.cos(). But if we wanted to import just the cos() function, this can done using from as

 from math import cos 

now we can use the function simply as cos(), no need to write math.cos().

Learn more on Python modules and import statement.

global

global is used to declare that a variable inside the function is global (outside the function).

If we need to read the value of a global variable, it is not necessary to define it as global. This is understood.

If we need to modify the value of a global variable inside a function, then we must declare it with global. Otherwise, a local variable with that name is created.

Following example will help us clarify this.

 globvar = 10 def read1(): print(globvar) def write1(): global globvar globvar = 5 def write2(): globvar = 15 read1() write1() read1() write2() read1() 

Output

 10 5 5 

Here, the read1() function is just reading the value of globvar. So, we do not need to declare it as global. But the write1() function is modifying the value, so we need to declare the variable as global.

We can see in our output that the modification did take place (10 is changed to 5). The write2() also tries to modify this value. But we have not declared it as global.

Hence, a new local variable globvar is created which is not visible outside this function. Although we modify this local variable to 15, the global variable remains unchanged. This is clearly visible in our output.

in

in is used to test if a sequence (list, tuple, string etc.) contains a value. It returns True if the value is present, else it returns False. For example:

 >>> a = (1, 2, 3, 4, 5) >>> 5 in a True >>> 10 in a False 

The secondary use of in is to traverse through a sequence in a for loop.

 for i in 'hello': print(i) 

Output

 h e l l o 

is

is is used in Python for testing object identity. While the == operator is used to test if two variables are equal or not, is is used to test if the two variables refer to the same object.

It returns True if the objects are identical and False if not.

 >>> True is True True >>> False is False True >>> None is None True 

We know that there is only one instance of True, False and None in Python, so they are identical.

 >>> () == () True >>> () is () False >>> () == () True >>> () is () False 

An empty list or dictionary is equal to another empty one. But they are not identical objects as they are located separately in memory. This is because list and dictionary are mutable (value can be changed).

 >>> '' == '' True >>> '' is '' True >>> () == () True >>> () is () True 

Unlike list and dictionary, string and tuple are immutable (value cannot be altered once defined). Hence, two equal string or tuple are identical as well. They refer to the same memory location.

lambda

lambda is used to create an anonymous function (function with no name). It is an inline function that does not contain a return statement. It consists of an expression that is evaluated and returned. For example:

 a = lambda x: x*2 for i in range(1,6): print(a(i)) 

Output

 2 4 6 8 10 

Here, we have created an inline function that doubles the value, using the lambda statement. We used this to double the values in a list containing 1 to 5.

Learn more about Python lamda function.

nonlocal

The use of nonlocal keyword is very much similar to the global keyword. nonlocal is used to declare that a variable inside a nested function (function inside a function) is not local to it, meaning it lies in the outer inclosing function. If we need to modify the value of a non-local variable inside a nested function, then we must declare it with nonlocal. Otherwise a local variable with that name is created inside the nested function. Following example will help us clarify this.

 def outer_function(): a = 5 def inner_function(): nonlocal a a = 10 print("Inner function: ",a) inner_function() print("Outer function: ",a) outer_function() 

Output

 Inner function: 10 Outer function: 10 

Here, the inner_function() is nested within the outer_function.

The variable a is in the outer_function(). So, if we want to modify it in the inner_function(), we must declare it as nonlocal. Notice that a is not a global variable.

Hence, we see from the output that the variable was successfully modified inside the nested inner_function(). The result of not using the nonlocal keyword is as follows:

 def outer_function(): a = 5 def inner_function(): a = 10 print("Inner function: ",a) inner_function() print("Outer function: ",a) outer_function() 

Output

 Inner function: 10 Outer function: 5 

Here, we do not declare that the variable a inside the nested function is nonlocal. Hence, a new local variable with the same name is created, but the non-local a is not modified as seen in our output.

pass

pass is a null statement in Python. Nothing happens when it is executed. It is used as a placeholder.

Suppose we have a function that is not implemented yet, but we want to implement it in the future. Simply writing,

 def function(args): 

in the middle of a program will give us IndentationError. Instead of this, we construct a blank body with the pass statement.

 def function(args): pass 

We can do the same thing in an empty class as well.

 class example: pass 

return

return statement is used inside a function to exit it and return a value.

If we do not return a value explicitly, None is returned automatically. This is verified with the following example.

 def func_return(): a = 10 return a def no_return(): a = 10 print(func_return()) print(no_return()) 

Output

 10 None 

while

while is used for looping in Python.

The statements inside a while loop continue to execute until the condition for the while loop evaluates to False or a break statement is encountered. Following program illustrates this.

 i = 5 while(i): print(i) i = i - 1 

Output

 5 4 3 2 1 

Note that 0 is equal to False.

Learn more about Python while loop.

with

with statement is used to wrap the execution of a block of code within methods defined by the context manager.

Context manager is a class that implements __enter__ and __exit__ methods. Use of with statement ensures that the __exit__ method is called at the end of the nested block. This concept is similar to the use of try… finally block. Here, is an example.

 with open('example.txt', 'w') as my_file: my_file.write('Hello world!') 

This example writes the text Hello world! to the file example.txt. File objects have __enter__ and __exit__ method defined within them, so they act as their own context manager.

First the __enter__ method is called, then the code within with statement is executed and finally the __exit__ method is called. __exit__ method is called even if there is an error. It basically closes the file stream.

yield

yieldχρησιμοποιείται μέσα σε μια συνάρτηση όπως μια returnδήλωση. Αλλά yieldεπιστρέφει μια γεννήτρια.

Το Generator είναι ένα επαναληπτικό που δημιουργεί ένα στοιχείο τη φορά. Μια μεγάλη λίστα τιμών θα καταλάβει πολλή μνήμη. Οι γεννήτριες είναι χρήσιμες σε αυτήν την περίπτωση καθώς δημιουργεί μόνο μία τιμή τη φορά αντί να αποθηκεύει όλες τις τιμές στη μνήμη. Για παράδειγμα,

 >>> g = (2**x for x in range(100)) 

θα δημιουργήσει μια γεννήτρια g η οποία παράγει δυνάμεις από 2 έως και τον αριθμό δύο που αυξάνεται στην ισχύ 99. Μπορούμε να δημιουργήσουμε τους αριθμούς χρησιμοποιώντας τη next()λειτουργία όπως φαίνεται παρακάτω.

 >>> next(g) 1 >>> next(g) 2 >>> next(g) 4 >>> next(g) 8 >>> next(g) 16 

Και ούτω καθεξής… Αυτός ο τύπος γεννήτριας επιστρέφεται από τη yieldδήλωση μιας συνάρτησης. Εδώ είναι ένα παράδειγμα.

 def generator(): for i in range(6): yield i*i g = generator() for i in g: print(i) 

Παραγωγή

 0 1 4 9 16 25 

Εδώ, η συνάρτηση generator()επιστρέφει μια γεννήτρια που δημιουργεί τετράγωνο αριθμών από 0 έως 5. Αυτό εκτυπώνεται στο forβρόχο.

ενδιαφέροντα άρθρα...