[Python] for statement

2023. 7. 30. 22:31·Programming
728x90
728x90

for statement는 loop를 위한 control structure의 대표격이다.

더보기

https://ds31x.tistory.com/427

 

[Programming] Control Flow 와 Control Structure

Abstraction(추상화)을 통한 이해프로그래밍 언어에서 Abstraction은 복잡한 세부 사항을 숨기고 핵심 개념만 드러내는 프로그래밍의 기본 원칙임. Control Flow와 Control Structure는 프로그램의 Execution Path

ds31x.tistory.com


Python에서는 iterable 객체 (주로 collection type의 객체들)이
가지고 있는 item들을 iterate(순회)하는 용도로 사용된다.

 

프로그래밍을 배울 때, 구구단 출력과 같은 고전적인 예를 통해 배우고, 정말 기본 중의 기본으로 활용된다.
단, NumPy등을 익히게 되면서 loop가 아닌 matrix 를 이용한 처리 (쉽게 생각하면 많은 memory를 이용하여 반복을 덜하는 방식이라고 할 수 있음)가 보다 효율적이기 때문에 정말 필요한 경우 아니면 쓰지 말라고 애기를 하게 되지만...

더보기

2023.06.07 - [Programming] - [Python] Iterable and Iterator, plus Generator

 

[Python] Iterable and Iterator, plus Generator

Iterable and Iterator, and GeneratorIterable for 문에서 in 뒤에 위치하여 iterate (반복, 순회)가 가능한 object를 가르킴.__iter__() 라는 special method를 구현하고 있으며, 이를 통해 자신에 대한 iterator object를 반환

dsaint31.tistory.com


 

for statement는 정말 기본 중의 기본이다.

(반복을 얼마나 효율적으로 하느냐가 성능을 결정하기 때문에...)


기본 사용법

https://datagy.io/python-for-loop/

 

for loop_variable in iterable_obj:
    for_block # loop body 또는 loop block으로 불림.

for statement의 사용법은 다음과 같음.

  • keyword for 로 시작함.
  • 이후 loop variables가 놓인다. loop variables는 매 iteration에서 뒤에 놓인 iterable 객체의 item들이 할당됨.
  • 이후 keyword in 이 놓임. (in 이전이 loop variables이고 이후가 iterable객체들이 놓임.)
  • 이후 iterate가 이루어질 iterable 객체가 놓임 (복수 개를 사용시 zip으로 묶어주면 됨.).
  • 이후 : 가 놓임 (for statement는 compound statement로 : 이후 다음 라인들은 for statement의 반복될 code block임.

code block은
for statement가 시작하는 첫번째 line 보다 한단계 더 indentation 이루어짐.
이후 indent level이 감소하면 해당 code block이 종료함.

 

https://ds31x.tistory.com/493

 

Compound Statement란?

Compound Statment란?Compound Statement is a statement that uses a colon :to sperate a header (head) from its body (=suite라고도 불림),which consists of eithera single simple statement on the same line oran indented code block of one or more statement

ds31x.tistory.com


 

list와 함께 사용하기

l = [0,1,2,3,4,5]
for c in l:
  print(c)
  print('\n')
  • list l의 item들이 순서대로 loop variable c에 할당되고,
  • loop block이 수행되고
  • 이후 다시 loop variable c에 다음 item이 할당되고
  • 또 loop block이 수행되고
  • 위 과정이 l의 마지막 item까지 반복됨.

결과는 다음과 같음.

0

1

2

3

4

5

str과 함께 사용하기.

string도 sequence type이기 때문에 다음과 같이 동작가능함.

s = 'abce1234ABC'
for c in s:
  if c.isdigit():
    print(c)
  • 숫자에 해당하는 character c만이 출력이 됨.

결과는 다음과 같음.

1
2
3
4

range 객체와 함께 사용하기 *

C에서처럼 시작과 끝 index에 해당하는 숫자를 이용하는 경우는 range 객체를 사용하는게 효율적이다.

range() 내장함수(built-in function)를 사용하여 range 객체를 생성함(개인적으로 생성자라고 보지만 내장함수라고 해도 틀린건 아님)

더보기

2023.06.07 - [Programming] - [Python] range and enumerate

 

[Python] range and enumerate

range 란엄밀하게 애기하면, range 는 숫자들의 immutable sequence (=iterable)를 나타내는 built-in type이다.  즉, 흔히 built-in function으로 애기하는 range() 는 사실은 range class의 instance를 생성하는 생성자에

dsaint31.tistory.com



list나 tuple등은 자신의 모든 item들을 memory에 할당하는 객체이기 때문 매우 큰 수의 범위를 가지는 for statement에서 사용하기는 비효율적임.

for c in range(0,21,2):
    print(c)
  • ( [0,20] ) 에서 stepsize를 2로 취하기 때문에 짝수만이 출력됨.

결과는 다음과 같음.

0
2
4
6
8
10
12
14
16
18
20

 


복수개의  iterable 객체들을 한번에 반복하기

zip 함수로 여러 iterable 객체를 묶어주어 각 iteration에 복수의 loop variable을 사용할 수 있음.
단, zip으로 묶이는 각 iterable 객체의 item 갯수가 다른 경우 짧은 쪽에 의해 반복횟수가 결정됨.

다음의 예를 확인하라.

a = [0,1,2,3,4]
s = 'abcdefgh'

for i,c in zip(a,s):
  print(f'{i},{c}')
  • 5번의 반복만 이루어지는 것을 확인할 것.
  • loop variable을 하나로 두면, 해당 variable은 tuple 객체가 된다.

결과는 다음과 같음.

0,a
1,b
2,c
3,d
4,e

code block인 loop block에는 다양한 statement가 놓일 수 있으며, 이는 중첩된 loop를 만들 수 있음.
(nested if statement에서와 비슷)


참고: break check - else

https://ds31x.tistory.com/100

 

[Python] else: break checker

반복문에서 else는loop 가 break로 끝나지 않을 경우 수행되는 code block을 지정.조건문에서 else일반적으로 else의 경우, 앞서의 if 와 elif문들에서 실행된 block이 없는 경우 수행되는 것을 의미한다.2023.

ds31x.tistory.com


Reference

https://gist.github.com/dsaint31x/f28b8b3c59483abdb3119aa31ec44d01

 

py_for_Ex.ipynb

py_for_Ex.ipynb. GitHub Gist: instantly share code, notes, and snippets.

gist.github.com

 

2023.06.07 - [Programming] - [Python] Iterable and Iterator, plus Generator

 

[Python] Iterable and Iterator, plus Generator

Iterable and Iterator, and GeneratorIterable for 문에서 in 뒤에 위치하여 iterate (반복, 순회)가 가능한 object를 가르킴.__iter__() 라는 special method를 구현하고 있으며, 이를 통해 자신에 대한 iterator object를 반환

dsaint31.tistory.com

https://ds31x.tistory.com/56

 

[Python] while statement, break and continue:

Python의 경우, loop structure로 while statement와 for statement를 제공한다.Contol Flow와 Control Structure에 대한 개념은 다음 URL을 참고 :2025.04.23 - [Python] - [Programming] Control Flow 와 Control Structure [Programming] Control F

ds31x.tistory.com


https://ds31x.tistory.com/124

 

[Python] Control Structure and Control Flow

Control structure와 Control Flow란 무엇인가?2025.04.23 - [Python] - [Programming] Control Flow 와 Control Structure [Programming] Control Flow 와 Control StructureAbstraction(추상화)을 통한 이해프로그래밍 언어에서 Abstraction은

ds31x.tistory.com

 

 

 

728x90

'Programming' 카테고리의 다른 글

[ML] Ward’s linkage method  (0) 2023.08.06
[matplotlib] bar chart 그리기 : error bar 포함  (0) 2023.08.01
[PyQt6] QSizePolicy 설정.  (0) 2023.07.03
[Python] Regular Expression : re 요약  (0) 2023.07.03
[Python] str: Overloaded Operators  (0) 2023.07.02
'Programming' 카테고리의 다른 글
  • [ML] Ward’s linkage method
  • [matplotlib] bar chart 그리기 : error bar 포함
  • [PyQt6] QSizePolicy 설정.
  • [Python] Regular Expression : re 요약
dsaint31x
dsaint31x
    반응형
    250x250
  • dsaint31x
    Dsaint31's blog
    dsaint31x
  • 전체
    오늘
    어제
    • 분류 전체보기 (785)
      • Private Life (15)
      • Programming (55)
        • DIP (116)
        • ML (34)
      • Computer (119)
        • CE (53)
        • ETC (33)
        • CUDA (3)
        • Blog, Markdown, Latex (4)
        • Linux (9)
      • ... (368)
        • Signals and Systems (115)
        • Math (176)
        • Linear Algebra (33)
        • Physics (43)
        • 인성세미나 (1)
      • 정리필요. (61)
        • 의료기기의 이해 (6)
        • PET, MRI and so on. (7)
        • PET Study 2009 (1)
        • 방사선 장해방호 (5)
        • 방사선 생물학 (3)
        • 방사선 계측 (9)
        • 기타 방사능관련 (3)
        • 고시 (9)
        • 정리 (18)
      • RI (0)
      • 원자력,방사능 관련법 (2)
  • 블로그 메뉴

    • Math
    • Programming
    • SS
    • DIP
  • 링크

    • Convex Optimization For All
  • 공지사항

    • Test
    • PET Study 2009
    • 기타 방사능관련.
  • 인기 글

  • 태그

    cv2
    math
    Python
    Optimization
    SIGNAL
    Programming
    function
    Vector
    signal_and_system
    numpy
    signals_and_systems
    fourier transform
    인허가제도
    Probability
    SS
    linear algebra
    random
    Term
    opencv
    ML
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
dsaint31x
[Python] for statement
상단으로

티스토리툴바