매일공부

[PY4E] 파이썬 반복문, 루프; while for break continue Boolean None 본문

Programming/Python

[PY4E] 파이썬 반복문, 루프; while for break continue Boolean None

aram 2022. 7. 7. 04:21

1. while 루프(불확정 루프) : False 전까진 계속 실행됨

total = 0
count = 0

while True:
    number = input('Enter a number: ')
    if number == 'done':
        if count == 0:
            print('Did not enter number') #if문 추가로 다시 입력 받음
            continue
        break
    try: 
        usernumber = int(number)
    except:
        print('Invalid input')
        continue
    total = total + usernumber # total += usernumber; 둘다 동일
    count = count + 1 # count += 1; 둘다 동일

average = total / count
print(total, count, average)


# 마지막에 if 추가로 0으로 나오도록 수정
total = 0
count = 0

while True:
    number = input('Enter a number: ')
    if number == 'done':
        break
    try: 
        usernumber = int(number)
    except:
        print('Invalid input')
        continue
    total = total + usernumber # total += usernumber; 둘다 동일
    count = count + 1 # count += 1; 둘다 동일

if count == 0:
    average = 0
else:
    average = total / count
print(total, count, average)

- 무한 루프 : 조건을 만족하면 계속해서 실행되는 루프

- break : 만나면 while 종료. 바로 빠져나가고 돌아가지 않음

- continue : #과 같은 역할. 만나면 하던 반복을 진행하지 않고 루프 시작으로 jump

  > 예제로 좀 더 자세히 알아보기 : https://dailystudy.tistory.com/55

 

2. zero trap : if문과 동일, False면 반복문 건너뜀

n = 0
while n > 0:
	print('Lather')
print('Dry off!')

 

3. 유한 루트

- 유한한 데이터 집합을 받아서 실행할 경우

- 정확히 특정 횟수 만큼만 실행. 언제 끝나는지 사용자가 알 수 있음

- for 구조로 나타낼 수 있음

for i in [5, 4, 3] :
	print(1)
print('Blastoff!')

- i : 반복 변수. 시퀀스 안의 모든 값을 실행 → 유한함

- [5, 4, 3] : 시퀀스

 

 

4. Boolean Variable 부울변수 

- True or False를 가짐

- 특정 값이 list에 있는 지 확인 가능

found = False
print('Before', found)
num = [9, 41, 12, 3]
for value in num:
	if value == 3:
    found = True
    print(found, value)
    break
print('After', found)

 

5. None 특별한 자료형

- None의 자료형 = 상수

- 주로 공백을 나타냄

- 값이 없다고 표식을 할당해서 숫자가 아니라고 나타냄.

 

 

6. is, is not 연산자

- True or False 값을 반환하는 질문을 함

- 양변은 같은 값을 의미

- 자료형과 값 둘 다 같은지를 판단 : ==보다 훨씬 강력

    > 0 == 0.0 참

    > 0 is 0.0 거짓(자료형이 다름)

- 부울형 자료 또는 None 자료형에만 사용할 것을 추천

smallgest = None
print('Before')
for value in [9, 41, 12, 3]:
	if smallgest is None:
    	smallgest = value
    elif value < smallgest:
    	smallgest = value
    print(smallgest, value)
print('After', smallgest)

 

> 주의할 점 추가 내용 https://dailystudy.tistory.com/43

 

7. 범위지정 range()

  • range(첫숫자, 끝숫자, step)
    • 끝숫자의 마지막은 포함x
    • 일반적으로 시작숫자는 0
    • step : 얼마만큼 건너뛸 것인가
  • range(5) = range(0, 5) = [0, 1, 2, 3, 4]
>>> for looper in range(0, 10, 2):
...     print (f"{looper} : hello")
0 : hello
2 : hello
4 : hello
6 : hello
8 : hello
  • 역순 range(大, 小, -step) : 숫자가 감소하면서 실행됨 > 마찬가지로 마지막 숫자 포함x
>>> for looper in range(5, 1, -1):
...     print (f"{looper} : hello")
5 : hello
4 : hello
3 : hello
2 : hello

 

Comments