fun lupu ni Python. Sintasi, akojọ aṣetunṣe, isinmi, tẹsiwaju ati awọn ẹya miiran

Цikl for python i ọmọ while – statements software ede, ara: iteration operators, letIng repeat code nọmba ti a fun aago.

Цикл For — сintaxis

As already explained, cinclude for in Python is an iterator based onй fun ọmọ kọọkanidanimo. is he iṣe by tuple elements и atokọ, fokabulari awọn bọtini ati ki o miiran iterable objects.

A loop in Python begins with the for keyword, followed by an arbitrary variable name that stores the value of the next object in the given sequence. The general syntax for for…in in python looks like this:

for  in :        else:      

irinše “sequences” ti wa ni akojọ ọkan lẹhin miiran cycle variable. Tabi dipo, variable points to iru elements. For everybody ninu wpn “action” is performed.

A simple for loop in Python with a specific example:

>>> languages = ["C", "C++", "Perl", "Python"]  >>> for x in languages:  ...     print(x)  ...  C  C++  Perl  Python  >>>

The else block is specialth. If a olupin isẹыṣiṣẹ с Perl familiarы with him, ti for those who interact с C and C++ — this is an innovation. Semantically it awọn iṣẹ тbakanna lakoko lupu.

Only executed when the loop is not “stopped” by the break statement. That is, it is executed only after all elements have passed through the specified sequence.

Break operator in python – break

If the program has a for loop pataki da gbigbiawọn break statement, he pipeo lọati eto Sisan yio ilodilati wa lai ti fi si ibere from else.

Fe e je gbogbo igba break phrases in pythonuyutsya with conditional statements.

edibles = ["chops", "dumplings","eggs","nuts"] for food in edibles: if food == "dumplings": print("I don't eat dumplings!") break print("Great, delicious " + food) else: print("It's good that there were no dumplings!") print("Dinner is over.")

If you run this code, you get the following result:

Great, delicious chops. I don't eat dumplings! Dinner is over.

We remove “dumplings” from the existing list of data and get:

Excellent, delicious chops Excellent, delicious eggs Excellent, delicious nuts Good thing there were no dumplings! Dinner is over.

python skip operator – continue

Let’s say that the user’s antipathy to such products is not so great as to completely abandon their consumption. As a result, the loop continues with the operator continue. The following script uses the statement continue, to continue iterating through the list on “dumpling contact”.

edibles = ["chops", "dumplings","eggs","nuts"] for food in edibles: if food == "dumplings": print("I don't eat dumplings!") continue print("Great, delicious " + food) # this could be code for enjoying food :-) else: print("I hate dumplings!") print("Dinner is over.")

Ilẹ isalẹ:

Great, delicious chops. I don't eat dumplings! Great, delicious eggs Great, delicious nuts I hate dumplings! Dinner is over.

Iterating over lists with the range() function

If you want to access the indexes of a list, it’s not clear how to use a for loop for this purpose. It is possible to access all elements, but the element’s index will remain inaccessible. However, there is a method for accessing both the element’s index and the element itself. For this purpose, the function is used range() combined with the length function len():

fibonacci = [0,1,1,2,3,5,8,13,21]  for i in range(len(fibonacci)):      print(i,fibonacci[i])

Gba:

0 0 1 1 2 1 3 2 4 3 5 5 6 8 7 13 8 21

Attention! When applied len() к list or tuple, the corresponding number of elements of the given sequence is obtained.

Difficulties of iterating over lists

When iterating over a list, it is recommended to avoid list dynamics in the loop body. For clarity, we can offer the following option:

colors = ["red"] for i in colors: if i == "red": colors += ["black"] if i == "black": colors += ["white"] print(colours)

What happens when applying print(colours)?

['red', 'black', 'white']

To avoid this, it is recommended to interact with the copy using slices, as in the example below:

colors = ["red"] for i in colors[:]: if i == "red": colors += ["black"] if i == "black": colors += ["white"] print(colours )

esi:

['Red Black']

The list has been changed colours, but this action did not affect the loop. The data that needed to be iterated remained unchanged during the execution of the loop.

Enumerate in python 3

Enumerate is a built-in Python function. Most beginners, as well as some experienced programmers, are not aware of its existence. It allows you to automatically count iterations of the loop. For example:

for counter, value in enumerate(some_list):     print(counter, value)

iṣẹ enumerate also takes an optional argument (the value of the origin, taken by default for 0). Which makes it even more efficient.

my_list = ['apple', 'banana', 'cherry', 'peach'] for c, value in enumerate(my_list, 1): print(c, value) # Result: # 1 apple # 2 banana # 3 cherry # 4 peach

Fi a Reply