Deutsch English |
YOU LEARN HERE... |
how you can store any number of values in a list or tuple and how to access these values. |
WHY DO YOU NEED LISTS? |
Instead of storing several values in different variables a, b, c individually, you can use lists or tuples. The values (elements) of a list are enumerated in square brackets, in a tuple in round brackets. For example: List of colors: List with numbers Tuple with x, y coordinates of a point p: You access the individual values with an index. The first element always has index 0, the second index 1 and so on. For example, colors[2] returns the color “yellow” or p[0] the number 10. The difference between lists and tuples is that lists can be changed during program execution, whereas tuples cannot. |
EXAMPLES |
You go through the list with an index i. The first element of the list has index 0. If n is the number of list elements (also known as the length of the list), the index i must run from 0 to n-1. You can determine the length n of the list with the built-in function n = len(colors). Program: from gturtle import * colors = ["red", "blue", "yellow", "green"] n = len(colors) for i in range(n): c = colors[i] setPenColor(c) dot(40) forward(40) There is a second, shorter way of running through the list with a for-loop, where you do not need an index. With the notation for c in colors: you can fetch one element after the other from the colors list. Program: from gturtle import * colors = ["red", "blue", "yellow", "green"] for c in colors: setPenColor(c) dot(40) forward(40)
Program: from gturtle import* house = [(0, 60), (50, 110), (100, 60), (100, 0), (0, 0)] for (x, y) in house: moveTo(x, y)
In your program, you create a new point (x, y) with a mouse click and draw all connecting lines from this point to the existing points. To do this, you must save the existing points in a points list.
Program: from gturtle import * def drawLines(x, y): for (x1, y1) in points: setPos(x, y) moveTo(x1, y1) def addPoint(x, y): setPos(x, y) dot(8) drawLines(x, y) points.append((x, y)) makeTurtle(mousePressed = addPoint) hideTurtle() setPenColor("blue") points = [] print("Click with the mouse to draw points!")
Program: from gturtle import * clear("black") colors = ["green", "yellow","red", "blue", "magenta"] a = 5 while a < 300: for c in colors: setPenColor(c) forward(a) right(70) a = a + 0.8 |
REMEMBER... |
You can store several values in a list and access the individual elements via an index. When enumerating the list elements, use the square brackets. Use li.append(x) to add a new element x to the end of the list li. In addition to lists, Python also provides tuples for storing multiple values. The elements of a tuple are specified in the round brackets. Tuples are often used to save coordinates. |
TO SOLVE BY YOURSELF |
|