Python: Keywords

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

or

In a boolean control structure, the keyword 'or' is used if at least one condition must be True for the boolean expression to result to True. if x < y or y < z: print "x"

and

The 'and' keyword in a boolean expressions specifies that conditions on both sides of the keyword must be True in order for the expression to result to True.

as

The 'as' keyword is used to give a module a different alias. import random as rnd print rnd.radint(1,10)

assert

The 'assert' keyword is used for debugging purposes. assert salary > 0 If the assertion fails, the interpreter will complain.

break

The 'break' keyword is used to interrupt the cycle, if needed. import random while (True): val = random.randint(1, 30) print val, if (val == 22): break If the number equals to 22, the cycle is interrupted with the 'break' keyword.

class

The 'class' keyword is used to create new user defined objects. class Random: class definition...

continue

The 'continue' keyword is used to interrupt the current cycle without jumping out of the whole cycle. num = 0 while (num < 1000): num = num + 1 if (num % 2) == 0: continue print num

def

The 'def' keyword is used to create a new user defined function. def newFunction():

del

The 'del' keyword deletes objects.

except

The 'except' keyword clause(s) specify one or more exception handlers. When no exception occurs in the 'try' clause, no exception handler is executed. When an exception occurs in the 'try' suite, a search for an exception handler is started. This search inspects the 'except' clauses in turn until one is found that matches the exception. f = None try: f = open('films', 'r') for i in f: print i, except IOError: print "Error reading file" finally: if f: f.close()

exec

The 'exec' keyword executes Python code dynamically. exec("for i in [1, 2, 3, 4, 5]: print i,")

finally

The 'finally' keywords is used in various 'try' statements. If 'finally' is present, it specifies a 'cleanup' handler. f = None try: f = open('films', 'r') for i in f: print i, except IOError: print "Error reading file" finally: if f: f.close()

for

The 'for' keyword is used to iterate over items of a collection in order that they appear in the container. i = [1, 2, 3] for x in i: print x

from

The 'from' keyword is used for importing a specific variable, class, or a function from a module.

if

The 'if' keyword is used in a control statement to determine which statements are going to be executed. age = 17 if age > 18: print "Driving licence issued" else: print "Driving licence not permitted"

elif

The 'elif' keyword stands for 'else if'. In a boolean control structure, 'elif' defines that if the first test evaluates to False, we continue with the next one. If none of the tests is True, the else statement is executed. name = "Luke" if name == "Jack": print "Hello Jack!" elif name == "John": print "Hello John!" else: print "Hello there!"

else

The 'else' keyword is optionally used in an if-statement. The statement after the 'else' keyword is executed, unless the condition prefaced by 'if' is True. age = 17 if age > 18: print "Driving licence issued" else: print "Driving licence not permitted"

global

The 'global' keyword is used to access variables outside a function. x = 15 def function(): global x x = 45 function() print x >> 45 Normally, assigning to x variable inside a function, we create a new local variable, which is valid only in that function. But if we use the 'global' keyword, we change a variable outside the function definition.

import

The 'import' keyword is used to import other modules into a Python script. import math print math.pi

in

The 'in' keyword points a test from an expression to an object. print 4 in (2, 3, 5, 6) >> False print 4 in (2, 3, 4, 5) >> True The 'in' keyword tests if the number four is in the tuple. The second usage is traversing a tuple in a 'for' loop.

is

The 'is' keyword tests for object identity. Whether we are talking about the same object. Note, that multiple variables may refer to the same object. It answers the question "Do I have two names for the same object?" m is x False

lambda

The 'lambda' keyword creates a new anonymous function. An anonymous function is a function, which is not bound to a specific name. It is also called an inline function. for i in (1, 2, 3, 4, 5): a = lambda x: x * x print a(i) We do not create a new function with a def keyword. Instead we use an inline function on the fly.

not

The 'not' keyword negates a boolean value. grades = ["A", "B"] grade = "G" if grade not in grades: print "unknown grade" This tests whether the grade value is from the list of possible grades.

pass

The 'pass' keyword does nothing. def function(): pass This function is not implemented yet. It will be later. The body of the function must not be empty. So we can use a 'pass' keyword here.

print

The 'print' keyword is use to print numbers and characters to the console. >>print 2 2

raise

The 'raise' keyword and associated statement forces a specified exception to occur. answer = 'y' if (answer != 'yes' or answer != 'no'): raise YesNoException else: print 'Correct value' The YesNoException is raised if answer != 'yes' or 'no'.

return

The 'return' keyword is closely connected with a function definition. 'Return' exits the function and returns a value. def root(x): return x * x

try

The 'try' statement specifies exception handlers and/or cleanup code for a group of statements. while True: try: x = int(raw_input("Enter a number: ")) break except ValueError: print "Not a valid number. Try again..."

while

The 'while' keyword is a basic keyword for controlling the flow of the program. The statements inside the while loop are executed, until the expression evaluates to False.

with

The 'with' keyword is used to wrap the execution of a block with methods defined by a context manager. This allows common 'try...except...finally' usage patterns to be encapsulated for convenient reuse. The 'with' statement is a control-flow structure whose basic structure is: with expression [as variable]: with-block with open('/etc/passwd', 'r') as f: for line in f: print line ... more processing code ... It is used when working with unmanaged resources (like file streams). It creates the resource, performs the code in the block, then it closes the resource.

yield

The 'yield' keyword is used with generators. def gen(): x = 11 yield x print gen().next() >> 11 The 'yield' keyword exits the generator and returns a value.


Ensembles d'études connexes