ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 10.for, while: 흐름제어
    공부합시다!/python 2023. 2. 2. 00:14
    728x90

    if문에 이어서 오늘은 for와 while문 입니다.

    순환은 꼭 필요하고 재밌는 부분입니다.

     

    # 기본 반복문 : for, while
    
    from cgi import print_directory
    
    
    v1 = 1
    while v1 < 11:
      print('v1 is : ', v1)
      v1 += 1
      
    
    for v2 in range(10):
      print('v2 is : ', v2)
      
    for v3 in range(1,11):
      print('v3 is : ', v3)
      
      
    # 1~100까지의 합
    
    sum1 = 0
    cnt1 = 1
    
    while cnt1 <= 100:
      sum1 += cnt1
      cnt1 += 1
    print('1~100 : ', sum1 )
    
    # range 함수 사용
    print('1~100 : ', sum(range(1,101)))
    print('1~100 중 홀수의 합 : ', sum(range(1,101,2)))
    
    # 시퀀스(순서가 있는 ) 자료형 반복
    # 문자열, 리스트, 튜플, 집합, 사전
    # iterable: range, reversed, enumerate, filter, map, zip
    
    names = ['Kim', 'Park', 'Cho', 'Choi', 'Yoo']
    for v in names:
      print('You are : ', v)
    
    word = 'Dreams'
    for s in word:
      print('Word : ', s)
    
    my_info = {
      'name': 'Kim',
      'age': 33,
      'city': 'Seoul'
    }
    
    # 기본값은 key
    for key in my_info:
      print('my_info', key)    
    
    print()
    
    # kye 값 출력
    for key in my_info.keys():
      print('my_info', key)  
    
    print()
    # values 값 출력
    for values in my_info.values():
      print('my_inof', values)  
    
    print()
    # items 출력
    for k, v in my_info.items():
      print('my_inof', k, v)    
    
    # 대소문자 바꾸기
    name = 'sdKim_AT'
    
    for n in name:
      if n.isupper():
        print(n.lower())
      else:
        print(n.upper())    
    
    # break : 원하는 값을 찾으면 중단
    numbers = [12, 11, 99, 88, 77, 66, 55, 44, 33, 22, 11, 108]
    
    for num in numbers:
      if num == 55:
        print('Found : ', num)
        break
      else:
        print('Not Fount : ', num)    
    
    print()
    print()
    
    # for - else 구문(반복문이 정상적으로 수행된 경우 else 블럭 수행)
    numbers1 = [12, 11, 99, 88, 77, 66, 56, 44, 33, 22, 11, 108]
    
    for num in numbers1:
      if num == 55:
        print('Found : ', num)
        break
      else:
        print('Not Fount : ', num)
    else:
      print('Not Found 55 ...............')
    
    
    # continue : 조건과 일치하면 continue구문 이하를 수행하지 않고 계속 조건 실행
    lt = ['1', 2, 5, True, 4.3, complex(4)]
    
    for v in lt:
      if type(v) is float:
        continue
      print('타입 : ', type(v))

    728x90

    '공부합시다! > python' 카테고리의 다른 글

    12. DB: database 및 table 다루기  (0) 2023.02.06
    11.Function  (0) 2023.02.03
    9.if 조건문: 흐름제어  (0) 2023.02.01
    8.Set  (0) 2023.01.31
    7. Dictionary  (0) 2023.01.25
Designed by Tistory.