본문 바로가기

Python

[Python3] 기본 문법 정리2

반응형

조건문

weekday = 1  # 1=월, 2=화, 3=수, 4=목, 5=금, 6=토, 7=일
if 1 <= weekday <= 5:
    print('번호 끝자리가 %d, %d인 차량은 주차금지' % (weekday, weekday + 5))
elif weekday in (6, 7):
    print('주말은 차량 5부제를 시행하지 않습니다.')
else:
    pass

### 결과 : 번호의 끝자리가 1, 6인 차량은 주차금지 ###

 

반복문

# For Loop
for i in (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) :
    print('ㅋ' * i)

# For Loop의 다른 표현
for i in range(0, 10) :
    print('z' * i)

# While
i = 1
while i <= 10:
    print('ㅋ' * i)
    i = i + 1

 

반복문 - 감소

# For Loop
for j in (10, 9, 8, 7, 6, 5, 4, 3, 2, 1):
    print('ㅠ' * j)

for j in range(10, 0):
    print('z' * j)

# while
j = 10
while i >= 1:
    print('ㅠ' * i)
    i = i - 1;

 

반복문 - continue, break

  • continue : 다음 루프를 처리

  • break : 루프 중단 (빠져나옴)

    for x, y in ((0,1), (1,2), (3,5), (8, 13), (21, 34), (55, 89)) :
        if(x + y < 10) :
            continue
        elif (x + y >= 100) :
            break
        print(x, y)

     

연산자 관련

비교 연산자(in, not in)

  • in

    print('a' in 'baby')
    print('o' in 'baby')
    print('prune' in ['apple', 'banana', 'orange'])
    print('orange' in ['apple', 'banana', 'orange'])
    ------------------Result--------------------
    True
    False
    False
    True
  • not in

    print('a' not in 'baby')
    print('o' not in 'baby')
    print('prune' not in ['apple', 'banana', 'orange'])
    print('orange' not in ['apple', 'banana', 'orange'])
    ------------------Result--------------------
    False
    True
    True
    False

 

비교 연산자(is, is not)

  • is, is not

    A = 'baby'
    B = 'baby'
    print(A is B)
    print('b' + 'oy' is 'boy')
    
    A = ['a', 'b', 'c']
    B = A
    C = ['a', 'b', 'c']
    
    print(A is B)
    print(A is C) # 같은 객체인지 아닌지
    print(A is not C)
    
    ------------------Result------------------
    True
    True
    True
    False
    True

 

형 변환

  • Python 자체가 strongly typed language 이기 때문에 묵시적인 형 변환을 허용하지 않는다.

    name = 'Python'
    ver = 3.4
    print(name + ver) # TypeError: Can't convert 'float' object to str implicityly
    
    print(name + str(ver))

     


반응형

'Python' 카테고리의 다른 글

[Python3] 제어문 관련 정리  (0) 2020.03.12
[Python3] Dictionary 관련 정리  (0) 2020.03.11
[Python3] List 관련 정리  (0) 2020.03.11
[Python3] 문자열 관련 정리  (0) 2020.03.10
[Python3] 기본 문법 정리  (0) 2020.03.08