Dev Hyeri

기술스택/Python

[ 파이썬 ] if for while문에서 콜론 : 과 들여쓰기 indentation

_hyeri 2023. 9. 4. 17:05

 

 

인덴테이션

들여쓰기를 통해 code block를 구분.

다른 언어는 가독성을 위해 인덴트를 하지만 파이썬은 문법적으로 필수 사항이다.

인덴트를 정확하게 지키지 않으면 원하는 대로 동작하지 않을 가능성이 크다. 

Python relies on indentation (whitespace at the beginning of a line) to define scope in the code.

Other programming languages often use curly-brackets for this purpose.

(출처 https://www.w3schools.com/python/python_conditions.asp) 

 

tip : 콜론 부터 인덴테이션 된 사항들은 다른 언어에서 culry braket {} 로 묶어준 것과 같다고 생각하면 쉽다.

 

 

if 문 사용 방법  


:  (콜론) 사용에 주의한다.

들여쓰기 사용에 주의한다. 

 

a = 33
b = 200
if b > a:
  print("b is greater than a")

 

If statement, without indentation (will raise an error):

a = 33
b = 200
if b > a:
print("b is greater than a") # you will get an error

 

 

 

 

for 문 사용 방법


:  (콜론) 사용에 주의한다.

들여쓰기 사용에 주의한다. 

횟수에 따른 반복 수행 

특정 횟수 지정 or 시퀀스를 훑게 할 수 있다. 

주어진 여러 개의 데이터를 순서대로 다룰때 사용 

 

fruits = ["apple", "banana", "cherry"]
for x in fruits:
  print(x)

 

 

 

 

while 문 


:  (콜론) 사용에 주의한다.

들여쓰기 사용에 주의한다. 

조건에 따라 반복 수행 

조건 만족 여부에 따라 명령 수행 여부 결정(횟수 x )

 

i = 1
while i < 6:
  print(i)
  i += 1