Python 3-zelfstudie - Leer Python in 30 minuten.

Python is een krachtige programmeertaal die ideaal is voor scripting en snelle applicatie-ontwikkeling. Het wordt gebruikt in webontwikkeling (zoals: Django en Bottle), wetenschappelijk en wiskundig computergebruik (Orange, SymPy, NumPy) tot grafische gebruikersinterfaces op de desktop (Pygame, Panda3D).

Deze tutorial laat je kennismaken met de basisconcepten en functies van Python 3. Na het lezen van de tutorial kun je basis Python-programma's lezen en schrijven, en Python zelf grondig verkennen.

Deze tutorial is bedoeld voor mensen die kennis hebben van andere programmeertalen en snel met Python aan de slag willen.

Python voor beginners

Als je een nieuwe programmeur bent, raden we je aan om naar:

  1. Python-programmering - Een uitgebreide gids over wat Python is, hoe u aan de slag kunt in Python, waarom u het zou moeten leren en hoe u het kunt leren.
  2. Python-zelfstudies - Volg de zijbalklinks een voor een.
  3. Python-voorbeelden - Eenvoudige voorbeelden voor beginners om te volgen.

Wat wordt er in deze tutorial behandeld?

  • Voer Python uit op uw computer
  • Introductie (variabelen, operators, I / O, …)
  • Gegevensstructuren (lijst, woordenboek, set, …)
  • Besturingsstroom (if, loop, break, …)
  • Bestand (bestandsverwerking, directory, …)
  • Uitzonderingen (afhandeling, door de gebruiker gedefinieerde uitzondering, …)
  • OOP (Object & Klasse, Overerving, Overbelasting, …)
  • Standaardbibliotheek (ingebouwde functie, lijstmethoden, …)
  • Misc (generatoren, decorateurs, …)

Voer Python uit op uw computer

U hoeft Python niet op uw computer te installeren om deze tutorial te volgen. We raden u echter aan om Python-programma's die in deze zelfstudie zijn opgenomen, op uw eigen computer uit te voeren.

  • Voer Python uit op Windows
  • Voer Python uit op MacOS

Python-introductie

Laten we ons eerste Python-programma schrijven, "Hallo, wereld!". Het is een eenvoudig programma dat Hello World! op het standaard uitvoerapparaat (scherm).

"Hallo Wereld!" Programma

 print("Hello, World!")

Wanneer u het programma uitvoert, is de uitvoer:

 Hallo Wereld!

In dit programma hebben we de ingebouwde print () -functie gebruikt om Hallo wereld! draad.

Variabelen en literalen

Een variabele is een benoemde locatie die wordt gebruikt om gegevens in het geheugen op te slaan. Hier is een voorbeeld:

 a = 5 

Hier is a een variabele. We hebben 5aan variabele a toegewezen

We hoeven het type variabele in Python niet te definiëren. U kunt zoiets als dit doen:

 a = 5 print("a =", 5) a = "High five" print("a =", a)

Aanvankelijk wordt een integerwaarde 5toegewezen aan de variabele a. Vervolgens wordt de string High five toegewezen aan dezelfde variabele.

By the way, 5is een numerieke letterlijke en "High five"is een letterlijke tekenreeks.

Wanneer u het programma uitvoert, is de uitvoer:

 a = 5 a = High five 

Bezoek Python Variables, Constants and Literals voor meer informatie.

Operatoren

Operatoren zijn speciale symbolen die bewerkingen uitvoeren op operanden (variabelen en waarden).

Laten we het in dit deel hebben over rekenkundige en toewijzingsoperatoren.

Rekenkundige operatoren worden gebruikt om wiskundige bewerkingen uit te voeren zoals optellen, aftrekken, vermenigvuldigen enz.

 x = 14 y = 4 # Add two operands print('x + y =', x+y) # Output: x + y = 18 # Subtract right operand from the left print('x - y =', x-y) # Output: x - y = 10 # Multiply two operands print('x * y =', x*y) # Output: x * y = 56 # Divide left operand by the right one print('x / y =', x/y) # Output: x / y = 3.5 # Floor division (quotient) print('x // y =', x//y) # Output: x // y = 3 # Remainder of the division of left operand by the right print('x % y =', x%y) # Output: x % y = 2 # Left operand raised to the power of right (x^y) print('x ** y =', x**y) # Output: x ** y = 38416

Toewijzingsoperatoren worden gebruikt om waarden aan variabelen toe te wijzen. Je hebt het gebruik van =operator al gezien . Laten we wat meer toewijzingsoperatoren proberen.

 x = 5 # x += 5 ----> x = x + 5 x +=5 print(x) # Output: 10 # x /= 5 ----> x = x / 5 x /= 5 print(x) # Output: 2.0

Andere veelgebruikte toewijzingsoperatoren: -=, *=, %=, //=en **=.

Bezoek Python Operators voor meer informatie over alle operators.

Krijg input van de gebruiker

In Python kun je de functie input () gebruiken om input van de gebruiker te krijgen. Bijvoorbeeld:

 inputString = input('Enter a sentence:') print('The inputted string is:', inputString) 

Wanneer u het programma uitvoert, is de uitvoer:

Voer een zin in: Hallo daar. De ingevoerde string is: Hallo daar.

Python-opmerkingen

Er zijn 3 manieren om opmerkingen te maken in Python.

 # Dit is een opmerking 
 "" "Dit is een opmerking met meerdere regels." "" 
 '' 'Dit is ook een opmerking met meerdere regels.' '' 

Ga voor meer informatie over opmerkingen en docstring naar: Python Comments.

Typ Conversie

Het proces waarbij de waarde van het ene gegevenstype (integer, string, float, etc.) naar een ander wordt geconverteerd, wordt typeconversie genoemd. Python heeft twee soorten typeconversie.

Impliciete typeconversie

Impliciete conversie vereist geen tussenkomst van de gebruiker. Bijvoorbeeld:

 num_int = 123 # integer type num_flo = 1.23 # float type num_new = num_int + num_flo print("Value of num_new:",num_new) print("datatype of num_new:",type(num_new))

Wanneer u het programma uitvoert, is de uitvoer:

 Waarde van aantal_nieuw: 124,23 datatype van aantal_nieuw: datatype van aantal_nieuw: 

Hier heeft num_new het gegevenstype float omdat Python altijd een kleiner gegevenstype naar een groter gegevenstype converteert om het verlies van gegevens te voorkomen.

Hier is een voorbeeld waarin de Python-interpreter niet impliciet convert kan typen.

 num_int = 123 # int type num_str = "456" # str type print(num_int+num_str)

Als u het programma uitvoert, krijgt u

 TypeError: niet-ondersteunde operandtype (s) voor +: 'int' en 'str'

Python heeft echter een oplossing voor dit soort situaties die bekend staat als expliciete conversie.

Expliciete conversie

In case of explicit conversion, you convert the datatype of an object to the required data type. We use predefined functions like int(), float(), str() etc. to perform explicit type conversion. For example:

 num_int = 123 # int type num_str = "456" # str type # explicitly converted to int type num_str = int(num_str) print(num_int+num_str)

To lean more, visit Python type conversion.

Python Numeric Types

Python supports integers, floating point numbers and complex numbers. They are defined as int, float and complex class in Python. In addition to that, booleans: True and False are a subtype of integers.

 # Output: print(type(5)) # Output: print(type(5.0)) c = 5 + 3j # Output: print(type(c))

To learn more, visit Python Number Types.

Python Data Structures

Python offers a range of compound datatypes often referred to as sequences. You will learn about those built-in types in this section.

Lists

A list is created by placing all the items (elements) inside a square bracket () separated by commas.

It can have any number of items and they may be of different types (integer, float, string etc.)

 # empty list my_list = () # list of integers my_list = (1, 2, 3) # list with mixed data types my_list = (1, "Hello", 3.4) 

You can also use list() function to create lists.

Here's how you can access elements of a list.

 language = ("French", "German", "English", "Polish") # Accessing first element print(language(0)) # Accessing fourth element print(language(3))

You use the index operator () to access an item in a list. Index starts from 0. So, a list having 10 elements will have index from 0 to 9.

Python also allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the second last item and so on.

Check these resources for more information about Python lists:

  • Python lists (slice, add and remove item etc.)
  • Python list methods
  • Python list comprehension

Tuples

Tuple is similar to a list except you cannot change elements of a tuple once it is defined. Whereas in a list, items can be modified.

Basically, list is mutable whereas tuple is immutable.

 language = ("French", "German", "English", "Polish") print(language)

You can also use tuple() function to create tuples.

You can access elements of a tuple in a similar way like a list.

 language = ("French", "German", "English", "Polish") print(language(1)) #Output: German print(language(3)) #Output: Polish print(language(-1)) # Output: Polish

You cannot delete elements of a tuple, however, you can entirely delete a tuple itself using del operator.

 language = ("French", "German", "English", "Polish") del language # NameError: name 'language' is not defined print(language)

To learn more, visit Python Tuples.

String

A string is a sequence of characters. Here are different ways to create a string.

 # all of the following are equivalent my_string = 'Hello' print(my_string) my_string = "Hello" print(my_string) my_string = '''Hello''' print(my_string) # triple quotes string can extend multiple lines my_string = """Hello, welcome to the world of Python""" print(my_string)

You can access individual characters of a string using indexing (in a similar manner like lists and tuples).

 str = 'programiz' print('str = ', str) print('str(0) = ', str(0)) # Output: p print('str(-1) = ', str(-1)) # Output: z #slicing 2nd to 5th character print('str(1:5) = ', str(1:5)) # Output: rogr #slicing 6th to 2nd last character print('str(5:-2) = ', str(5:-2)) # Output: am

Strings are immutable. You cannot change elements of a string once it is assigned. However, you can assign one string to another. Also, you can delete the string using del operator.

Concatenation is probably the most common string operation. To concatenate strings, you use + operator. Similarly, the * operator can be used to repeat the string for a given number of times.

 str1 = 'Hello ' str2 ='World!' # Output: Hello World! print(str1 + str2) # Hello Hello Hello print(str1 * 3)

Check these resources for more information about Python strings:

  • Python Strings
  • Python String Methods
  • Python String Formatting

Sets

A set is an unordered collection of items where every element is unique (no duplicates).

Here is how you create sets in Python.

 # set of integers my_set = (1, 2, 3) print(my_set) # set of mixed datatypes my_set = (1.0, "Hello", (1, 2, 3)) print(my_set)

You can also use set() function to create sets.

Sets are mutable. You can add, remove and delete elements of a set. However, you cannot replace one item of a set with another as they are unordered and indexing have no meaning.

Let's try commonly used set methods: add(), update() and remove().

 # set of integers my_set = (1, 2, 3) my_set.add(4) print(my_set) # Output: (1, 2, 3, 4) my_set.add(2) print(my_set) # Output: (1, 2, 3, 4) my_set.update((3, 4, 5)) print(my_set) # Output: (1, 2, 3, 4, 5) my_set.remove(4) print(my_set) # Output: (1, 2, 3, 5)

Let's tryout some commonly used set operations:

 A = (1, 2, 3) B = (2, 3, 4, 5) # Equivalent to A.union(B) # Also equivalent to B.union(A) print(A | B) # Output: (1, 2, 3, 4, 5) # Equivalent to A.intersection(B) # Also equivalent to B.intersection(A) print (A & B) # Output: (2, 3) # Set Difference print (A - B) # Output: (1) # Set Symmetric Difference print(A B) # Output: (1, 4, 5)

More Resources:

  • Python Sets
  • Python Set Methods
  • Python Frozen Set

Dictionaries

Dictionary is an unordered collection of items. While other compound data types have only value as an element, a dictionary has a key: value pair. For example:

 # empty dictionary my_dict = () # dictionary with integer keys my_dict = (1: 'apple', 2: 'ball') # dictionary with mixed keys my_dict = ('name': 'John', 1: (2, 4, 3))

You can also use dict() function to create dictionaries.

To access value from a dictionary, you use key. For example:

 person = ('name':'Jack', 'age': 26, 'salary': 4534.2) print(person('age')) # Output: 26

Here's how you can change, add or delete dictionary elements.

 person = ('name':'Jack', 'age': 26) # Changing age to 36 person('age') = 36 print(person) # Output: ('name': 'Jack', 'age': 36) # Adding salary key, value pair person('salary') = 4342.4 print(person) # Output: ('name': 'Jack', 'age': 36, 'salary': 4342.4) # Deleting age del person('age') print(person) # Output: ('name': 'Jack', 'salary': 4342.4) # Deleting entire dictionary del person

More resources:

  • Python Dictionary
  • Python Dictionary Methods
  • Python Dictionary Comprehension

Python range()

range() returns an immutable sequence of numbers between the given start integer to the stop integer.

  print(range(1, 10)) # Output: range(1, 10) 

The output is an iterable and you can convert it to list, tuple, set and so on. For example:

 numbers = range(1, 6) print(list(numbers)) # Output: (1, 2, 3, 4, 5) print(tuple(numbers)) # Output: (1, 2, 3, 4, 5) print(set(numbers)) # Output: (1, 2, 3, 4, 5) # Output: (1: 99, 2: 99, 3: 99, 4: 99, 5: 99) print(dict.fromkeys(numbers, 99))

We have omitted optional step parameter for range() in above examples. When omitted, step defaults to 1. Let's try few examples with step parameter.

 # Equivalent to: numbers = range(1, 6) numbers1 = range(1, 6 , 1) print(list(numbers1)) # Output: (1, 2, 3, 4, 5) numbers2 = range(1, 6, 2) print(list(numbers2)) # Output: (1, 3, 5) numbers3 = range(5, 0, -1) print(list(numbers3)) # Output: (5, 4, 3, 2, 1)

Python Control Flow

if… else Statement

The if… else statement is used if you want perform different action (run different code) on different condition. For example:

 num = -1 if num> 0: print("Positive number") elif num == 0: print("Zero") else: print("Negative number") # Output: Negative number

There can be zero or more elif parts, and the else part is optional.

Most programming languages use () to specify the block of code. Python uses indentation.

A code block starts with indentation and ends with the first unindented line. The amount of indentation is up to you, but it must be consistent throughout that block.

Generally, four whitespace is used for indentation and is preferred over tabs.

Let's try another example:

 if False: print("I am inside the body of if.") print("I am also inside the body of if.") print("I am outside the body of if") # Output: I am outside the body of if.

Before you move on to next section, we recommend you to check comparison operator and logical operator.

Also, check out Python if… else in detail.

while Loop

Like most programming languages, while loop is used to iterate over a block of code as long as the test expression (condition) is true. Here is an example to find the sum of natural numbers:

 n = 100 # initialize sum and counter sum = 0 i = 1 while i <= n: sum = sum + i i = i+1 # update counter print("The sum is", sum) # Output: The sum is 5050

In Python, while loop can have optional else block that is executed if the condition in the while loop evaluates to False. However, if the loop is terminated with break statement, Python interpreter ignores the else block.

To learn more, visit Python while Loop

for Loop

In Python, for loop is used to iterate over a sequence (list, tuple, string) or other iterable objects. Iterating over a sequence is called traversal.

Here's an example to find the sum of all numbers stored in a list.

 numbers = (6, 5, 3, 8, 4, 2) sum = 0 # iterate over the list for val in numbers: sum = sum+val print("The sum is", sum) # Output: The sum is 28

Notice the use of in operator in the above example. The in operator returns True if value/variable is found in the sequence.

In Python, for loop can have optional else block. The else part is executed if the items in the sequence used in for loop exhausts. However, if the loop is terminated with break statement, Python interpreter ignores the else block.

To learn more, visit Python for Loop

break Statement

The break statement terminates the loop containing it. Control of the program flows to the statement immediately after the body of the loop. For example:

 for val in "string": if val == "r": break print(val) print("The end")

When you run the program, the output will be:

 s t The end 

continue Statement

The continue statement is used to skip the rest of the code inside a loop for the current iteration only. Loop does not terminate but continues on with the next iteration. For example:

 for val in "string": if val == "r": continue print(val) print("The end")

When you run the program, the output will be:

 s t i n g The end 

To learn more on break and continue with detail explanation, visit Python break and continue.

pass Statement

Suppose, you have a loop or a function that is not implemented yet, but want to implement it in the future. They cannot have an empty body. The interpreter would complain. So, you use the pass statement to construct a body that does nothing.

 sequence = ('p', 'a', 's', 's') for val in sequence: pass

Python Function

A function is a group of related statements that perform a specific task. You use def keyword to create functions in Python.

 def print_lines(): print("I am line1.") print("I am line2.") 

You have to call the function to run the codes inside it. Here's how:

 def print_lines(): print("I am line1.") print("I am line2.") # function call print_lines()

A function can accept arguments.

 def add_numbers(a, b): sum = a + b print(sum) add_numbers(4, 5) # Output: 9

You can also return value from a function using return statement.

 def add_numbers(a, b): sum = a + b return sum result = add_numbers(4, 5) print(result) # Output: 9

Here are few resources to check:

  • Python Function
  • Python Function Arguments (Default, Keyword, Arbitrary)

Recursion (Recursive function)

A function that calls itself is known as recursive function and this process is called recursion.

Every recursive function must have a base condition that stops the recursion or else the function calls itself infinitely.

 # Recursive function to find the factorial of a number def calc_factorial(x): if x == 1: return 1 else: return (x * calc_factorial(x-1)) num = 6 print("The factorial of", num, "is", calc_factorial(num)) # Output: The factorial of 6 is 720

Visit Python recursion to learn more.

Lambda Function

In Python, you can define functions without a name. These functions are called lambda or anonymous function. To create a lambda function, lambda keyword is used.

 square = lambda x: x ** 2 print(square(5)) # Output: 25

We use lambda functions when we require a nameless function for a short period of time. Lambda functions are used along with built-in functions like filter(), map() etc.

To learn more, visit:

  • Python Lambda Function
  • Python map()
  • Python filter()

Modules

Modules refer to a file containing Python statements and definitions.

A file containing Python code, for e.g.: example.py, is called a module and its module name would be example.

Let us create it and save it as example.py.

 # Python Module example def add(a, b): return a + b 

To use this module, we use import keyword.

 # importing example module import example # accessing the function inside the module using . operator example.add(4, 5.5) 

Python has a ton of standard modules readily available for use. For example:

 import math result = math.log2(5) # return the base-2 logarithm print(result) # Output: 2.321928094887362

You can import specific names from a module without importing the module as a whole. Here is an example.

 from math import pi print("The value of pi is", pi) # Output: The value of pi is 3.141592653589793

More Resources:

  • Python Modules
  • Python Packages

Python File I/O

A file operation takes place in the following order.

  1. Open a file
  2. Read or write (perform operation)
  3. Close the file

How to open a file?

You can use open() function to open a file.

 f = open("test.txt") # open file in current directory f = open("C:/Python33/README.txt") # specifying full path 

We can specify the mode while opening a file.

Mode Description
'r' Open a file for reading. (default)
'w' Open a file for writing. Creates a new file if it does not exist or truncates the file if it exists.
'x' Open a file for exclusive creation. If the file already exists, the operation fails.
'a' Open for appending at the end of the file without truncating it. Creates a new file if it does not exist.
't' Open in text mode. (default)
'b' Open in binary mode.
'+' Open a file for updating (reading and writing)
 f = open("test.txt") # equivalent to 'r' or 'rt' f = open("test.txt",'w') # write in text mode f = open("img.bmp.webp",'r+b') # read and write in binary mode 

How to close a file?

To close a file, you use close() method.

 f = open("test.txt",encoding = 'utf-8') # perform file operations f.close() 

How to write to a file?

In order to write into a file in Python, we need to open it in write 'w', append 'a' or exclusive creation 'x' mode.

 with open("test.txt",'w',encoding = 'utf-8') as f: f.write("my first file") f.write("This file") f.write("contains three lines") 

Here, we have used with statement to open a file. This ensures that the file is closed when the block inside with is exited.

How to read files?

To read a file in Python, you must open the file in reading mode.

There are various methods available for this purpose. We can use the read(size) method to read in size number of data.

 f = open("test.txt",'r',encoding = 'utf-8') f.read(4) # read the first 4 data 

Visit Python File I/O to learn more.

Python Directory

A directory or folder is a collection of files and sub directories. Python has the os module, which provides many useful methods to work with directories and files.

 import os os.getcwd() // present working directory os.chdir('D:\Hello') // Changing current directory to D:Hello os.listdir() // list all sub directories and files in that path os.mkdir('test') // making a new directory test os.rename('test','tasty') // renaming the directory test to tasty os.remove('old.txt') // deleting old.txt file 

Visit Python Directory to learn more.

Python Exception Handling

Errors that occur at runtime are called exceptions. They occur, for example, when a file we try to open does not exist FileNotFoundError, dividing a number by zero ZeroDivisionError etc.

Visit this page to learn about all built-in exceptions in Python.

If exceptions are not handled, an error message is spit out and our program come to a sudden, unexpected halt.

In Python, exceptions can be handled using try statement. When exceptions are caught, it's up to you what operator to perform.

 # import module sys to get the type of exception import sys randomList = ('a', 0, 2) for entry in randomList: try: print("The entry is", entry) r = 1/int(entry) break except: print("Oops!",sys.exc_info()(0),"occurred.") print("Next entry.") print() print("The reciprocal of",entry,"is",r)

When you run the program, the output will be:

 The entry is a Oops! occurred. Next entry. The entry is 0 Oops! occurred. Next entry. The entry is 2 The reciprocal of 2 is 0.5

To learn about catching specific exceptions and finally clause with try statement, visit Python exception handling.

Also, you can create user-defined exceptions in Python. For that, visit Python Custom Exceptions

Python OOP

Everything in Python is an object including integers, floats, functions, classes, and None. Let's not focus on why everything in Python is an object. For that, visit this page. Rather, this section focuses on creating your own classes and objects.

Class and Objects

Object is simply a collection of data (variables) and methods (functions) that act on data. And, class is a blueprint for the object.

How to define a class?

 class MyClass: a = 10 def func(self): print('Hello') 

As soon as you define a class, a new class object is created with the same name. This class object allows us to access the different attributes as well as to instantiate new objects of that class.

 class MyClass: "This is my class" a = 10 def func(self): print('Hello') # Output: 10 print(MyClass.a) # Output: print(MyClass.func) # Output: 'This is my class' print(MyClass.__doc__)

You may have noticed the self parameter in function definition inside the class but, we called the method simply as ob.func() without any arguments. It still worked.

This is because, whenever an object calls its method, the object itself is passed as the first argument. So, ob.func() translates into MyClass.func(ob).

Creating Objects

You can also create objects of the class yourself.

 class MyClass: "This is my class" a = 10 def func(self): print('Hello') obj1 = MyClass() print(obj1.a) # Output: 10 obj2 = MyClass() print(obj1.a + 5) # Output: 15

Python Constructors

In Python, a method with name __init()__ is a constructor. This method is automatically called when an object is instantiated.

 class ComplexNumber: def __init__(self,r = 0,i = 0): # constructor self.real = r self.imag = i def getData(self): print("(0)+(1)j".format(self.real,self.imag)) c1 = ComplexNumber(2,3) # Create a new ComplexNumber object c1.getData() # Output: 2+3j c2 = ComplexNumber() # Create a new ComplexNumber object c2.getData() # Output: 0+0j

Visit Python Class and Object to learn more.

Python Inheritance

Inheritance refers to defining a new class with little or no modification to an existing class. Let's take an example:

 class Mammal: def displayMammalFeatures(self): print('Mammal is a warm-blooded animal.')

Let's derive a new class Dog from this Mammal class.

 class Mammal: def displayMammalFeatures(self): print('Mammal is a warm-blooded animal.') class Dog(Mammal): def displayDogFeatures(self): print('Dog has 4 legs.') d = Dog() d.displayDogFeatures() d.displayMammalFeatures()

Notice that we are able to call method of base class displayMammalFeatures() from the object of derived class d.

To learn more about inheritance and method overriding, visit Python Inheritance.

We also suggest you to check multiple inheritance and operator overloading if you are interested.

Miscellaneous and Advance Topics

Iterators

Iterator in Python is simply an object that can be iterated upon. An object which will return data, one element at a time.

Technically speaking, Python iterator object must implement two special methods, __iter__() and __next__(), collectively called the iterator protocol.

An object is called iterable if we can get an iterator from it. Most of built-in containers in Python like: list, tuple, string etc. are iterables.

The iter() function (which in turn calls the __iter__() method) returns an iterator from them.

 my_list = (4, 7, 0, 3) # get an iterator using iter() my_iter = iter(my_list) print(next(my_iter)) # Output: 4 print(next(my_iter)) # Output: 7

To learn more about infinite iterators and how to create custom iterators, visit: Python Iterators.

Generators

There is a lot of overhead in building an iterator in Python; we have to implement a class with __iter__() and __next__() method, keep track of internal states, raise StopIteration when there was no values to be returned etc.

This is both lengthy and counter intuitive. Generator comes into rescue in such situations.

Python generators are a simple way of creating iterators.

Learn more about Python Generators.

Closures

This technique by which some data gets attached to the code is called closure in Python.

 def print_msg(msg): # outer enclosing function def printer(): # inner function print(msg) return printer # this got changed another = print_msg("Hello") # Output: Hello another()

Here, the print_msg() function is called with the string "Hello" as an argument and the returned function was bound to the name another. On calling another(), the message was still remembered although we had already finished executing the print_msg() function.

The criteria that must be met to create closure in Python are summarized in the following points.

  • We must have a nested function (function inside a function).
  • The nested function must refer to a value defined in the enclosing function.
  • The enclosing function must return the nested function.

Visit Python closures to learn more about closures and when to use them.

Decorators

Python has an interesting feature called decorators to add functionality to an existing code.

Dit wordt ook metaprogrammering genoemd, omdat een deel van het programma probeert een ander deel van het programma tijdens het compileren te wijzigen.

Bezoek Python Decorators voor meer informatie over decorateurs.

Heb ik iets gemist in deze Python-tutorial?

Interessante artikelen...