-
[Python tutorial] 13. Control flow, Loop, Iterator코딩/Python 2022. 12. 21. 17:15728x90
While Loops
i = 1 while i < 6: print(i) i += 1
break
i = 1 while i < 6: print(i) if i == 3: break i += 1
continue
i = 0 while i < 6: i += 1 if i == 3: continue print(i)
else
i = 1 while i < 6: print(i) i += 1 else: print("i is no longer less than 6")
For Loop
fruits = ["apple", "banana", "cherry"] for x in fruits: print(x)
Looping Through a String
for x in "banana": print(x)
break
fruits = ["apple", "banana", "cherry"] for x in fruits: print(x) if x == "banana": break
fruits = ["apple", "banana", "cherry"] for x in fruits: if x == "banana": break print(x)
continue
fruits = ["apple", "banana", "cherry"] for x in fruits: if x == "banana": continue print(x)
range()
for x in range(6): print(x)
for x in range(2, 6): print(x)
for x in range(2, 30, 3): # increment 3 print(x)
2
5
8
11
14
17
20
23
26
29Iteration with range() & len()
a = ['a', 'b', 'c'] for i in range(len(a)): print(i, a[i])
enumerate()
for i, v in enumerate(['tic', 'tac', 'toe']): print(i, v)
Else in For Loop
for x in range(6): print(x) else: print("Finally finished!")
0
1
2
3
4
5
Finally finished!for x in range(6): if x == 3: break print(x) else: print("Finally finished!")
0
1
2Nested Loops
adj = ["red", "big", "tasty"] fruits = ["apple", "banana", "cherry"] for x in adj: for y in fruits: print(x, y)
red apple
red banana
red cherry
big apple
big banana
big cherry
tasty apple
tasty banana
tasty cherrypass
for x in [0, 1, 2]: pass
match - case
def http_error(status): match status: case 400: return "Bad request" case 404: return "Not found" case 418: return "I'm a teapot" case _: # wildcard return "Something's wrong with the internet"
case 401 | 403 | 404: # or return "Not allowed"
# point is an (x, y) tuple match point: case (0, 0): print("Origin") case (0, y): print(f"Y={y}") case (x, 0): print(f"X={x}") case (x, y): print(f"X={x}, Y={y}") case _: raise ValueError("Not a point")
Iterators
- 셀 수 있는 값을 포함하는 개체
- 반복할 수 있는 개체
__iter__()
및__next__()
메서드로 구성된 반복자 프로토콜을 구현하는 객체
interator & iterable
- iterable: list, tuple, dictionary, set & string
__inter__()
메서드를 가진 객체
iter() & next()
# tuple mytuple = ("apple", "banana", "cherry") myit = iter(mytuple) print(next(myit)) print(next(myit)) print(next(myit))
# string mystr = "banana" myit = iter(mystr) print(next(myit)) print(next(myit)) print(next(myit)) print(next(myit)) print(next(myit)) print(next(myit))
Looping Through an Iterator: for...
mytuple = ("apple", "banana", "cherry") for x in mytuple: print(x)
mystr = "banana" for x in mystr: print(x)
Create an Iterator
- 객체/클래스를 이터레이터로 생성하려면
__iter__()
및__next__()
메서드를 객체에 구현 __iter__()
항상 반복자 객체 자체를 반환해야 함__next__()
메서드로 작업을 수행하고 시퀀스의 다음 항목을 반환
class MyNumbers: def __iter__(self): self.a = 1 return self def __next__(self): x = self.a self.a += 1 return x myclass = MyNumbers() myiter = iter(myclass) print(next(myiter)) # 1 print(next(myiter)) # 2 print(next(myiter)) # 3 print(next(myiter)) # 4 print(next(myiter)) # 5
StopIteration
- 반복이 영원히 계속되는 것 방지 위해 StopIteration 문을 사용
__next__()
메서드에서 반복이 지정된 횟수만큼 수행되면 오류를 발생시키는 종료 조건을 추가
class MyNumbers: def __iter__(self): self.a = 1 return self def __next__(self): if self.a <= 20: x = self.a self.a += 1 return x else: raise StopIteration myclass = MyNumbers() myiter = iter(myclass) for x in myiter: print(x)
728x90'코딩 > Python' 카테고리의 다른 글
[Python tutorial] 15. Lambda (0) 2022.12.21 [Python tutorial] 14. Functions (0) 2022.12.21 [Python tutorial] 12. Control flow, If...else (0) 2022.12.21 [Python tutorial] 11. Operators (0) 2022.12.21 [Python tutorial] 10. Data type - Dictionary (0) 2022.12.21