쓰는 방법 :
for 변수 in range(횟수):
나오게 하고자 하는 것
① 데이터타입을 확인하고 싶은 경우
- 확인하고자 하는 데이터 타입만 입력한다.
>>> for a in range(10):
print
<built-in function print>
<built-in function print>
<built-in function print>
<built-in function print>
<built-in function print>
<built-in function print>
<built-in function print>
<built-in function print>
<built-in function print>
<built-in function print>
>>> for a in range(10):
int
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>
② 특정한 문자만 나오게 하고자 하는 경우
- for 변수 in range(횟수):
나오게 하고자 하는 것 <- 이 부분에 print 를 달면 된다.
>>> for a in range(10):
print ("test")
test
test
test
test
test
test
test
test
test
test
>>> for a in range(1,10):
print("test")
test
test
test
test
test
test
test
test
test
>>>
둘은 같은 의미이지만, 횟수를 (1,10)으로 지정해두면 10-1=9개만 출력이 된다.
만약, ①처럼만 하면, 밑과 같은 오류가 일어난다.
>>> for a in range(10):
you
Traceback (most recent call last):
File "<pyshell#20>", line 2, in <module>
you
NameError: name 'you' is not defined
>>>
변수가 아닌 문자를 출력하고 싶을 시엔, print 를 꼭 같이 붙여줘야한다.
③ for 증가폭
for 변수 in range(시작점,끝점,증가폭):
print("문구",변수)
변수는 for 다음에 적었던 변수와 같은걸로 적용해야한다.
for a in range(0,10,2):
print("Hello,World!",i)
Hello,World! 0
Hello,World! 2
Hello,World! 4
Hello,World! 6
Hello,World! 8
Hello,World! 10
그렇지 않으면 아래와 같은 오류가 발생한다.
>>> for i in range(0,12,2):
print("Hello,world",a)
Hello,world 0
Hello,world 0
Hello,world 0
Hello,world 0
Hello,world 0
Hello,world 0
출력자체는 되지만, 증가폭이 변하지 않는다.
④ for 감소폭
for 변수 in range(시작점,끝점,감소폭):
print("문구",변수)
for i in range(10,0,-1):
print("Hello",i)
Hello 10
Hello 9
Hello 8
Hello 7
Hello 6
Hello 5
Hello 4
Hello 3
Hello 2
Hello 1
위와 같은 원리로 작동하며, 감소폭 부분에 -를 설정하면 된다.
최소값에 다오면 문이 끝난다.
'파이썬 기초 > 파이썬' 카테고리의 다른 글
중첩루프 (0) | 2020.02.03 |
---|---|
while (0) | 2020.02.02 |
시퀀스 sequence - 2 (len,index,del) (0) | 2020.01.27 |
시퀀스 sequence - 1 (in, not in) (0) | 2020.01.27 |
range,list (0) | 2020.01.27 |