Циклы в Python

Введение

Цикл — разновидность управляющей конструкции в высокоуровневых языках программирования, предназначенная для организации многократного исполнения набора инструкций.

Также циклом может называться любая многократно исполняемая последовательность инструкций, организованная любым способом (например, с помощью условного перехода).

Статьи
Цикл for
continue

>>> numbers = [1, 2, 3, 5, 7] >>> squares = (n**2 for n in numbers) >>> squares <generator object <genexpr> at 0x00000159BD890520> >>> >>> tuple(squares) (1, 4, 9, 25, 49) >>> >>> sum(squares) 0 >>> >>> squares = (n**2 for n in numbers) >>> 9 in squares True >>> 9 in squares False >>> >>> >>> >>> counts = {"apples": 2, "oranges": 1} >>> x, y = counts >>> x == ("apples", 2) False >>> x 'apples'

C-style for loop

let numbers = [1, 2, 3, 5, 7]; for (let i = 0; i < numbers.length; i+=1) { print(numbers[i]) }

1 2 3 5 7

В Python таких циклов for нет. По объекту, который является последовательностью можно перемещаться с помощью индексов.

numbers = [1, 2, 3, 5, 7] i = 0 while i < len(numbers): print(numbers[i]) i += 1

1 2 3 5 7

С объектами, которые не являются последовательностями такой способ не сработает.

cities = {"benalmadena", "fuengirola", "malaga", "torremolinos"} i = 0 while i < len(cities): print(cities[i]) i += 1

Traceback (most recent call last): File "C:\Users\AO\set_while_ex.py", line 4, in <module> print(cities[i]) ~~~~~~^^^ TypeError: 'set' object is not subscriptable

def funky_for_loop(iterable, action_to_do): for item in iterable: action_to_do(item)

С помощью цикла while и функций iter() и next() можно создать аналог цикла for не только для последовательностей но для всех итерируемых объектов.

def funky_for_loop(iterable, action_to_do): iterator = iter(iterable) done_looping = False while not done_looping: try: item = next(iterator) except StopIteration: done_looping = True else: action_to_do(item)

Article author: Andrei Olegovich

Похожие статьи
Python
Цикл for in
continue
Collections

Search this site

Subscribe to Telegram channel @aofeed to follow new articles and updates to old ones

Go to channel

@aofeed

Ask a question in the Telegram group

@aofeedchat

Contacts and cooperation:
I recommend our hosting beget.ru
Write to info@urn.su, info@aredel.com if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: