본문 바로가기
Python

(문제 풀이)파이썬, python: 반복문과 제어문

by 하방주인장 2023. 5. 3.

목차

     

    1-1. if문: 특정 문자열이 포함되었는지 확인하기

    text1 = '데이터 분석에 대한 기초를 배워보세요.'
    text2 = '운동은 건강한 삶을 유지하는 데에 매우 중요한 역할을 합니다.'
    
    def check_data(text):
        if '데이터' not in text:
            result = '데이터 관련 글 아님'
        else:
            result = '데이터 관련 글임'
        return  result
        
    assert check_data(text1) == '데이터 관련 글임'
    assert check_data(text2) == '데이터 관련 글 아님'

     

    1-2. if문: 양수, 0, 음수 판별하기

    num1 = 10
    num2 = -5
    num3 = 0
    
    def check_number(num):
        if num > 0:
            result = '양수'
        elif num == 0:
            result = '0'
        else:
            result = '음수'
        return  result
        
    assert check_number(num1) == '양수'
    assert check_number(num2) == '음수'
    assert check_number(num3) == '0'

     

    2-1. while문: 정수 n을 입력받아 1~n을 모두 더하기

    def sum_n(n):
        i = 1
        total = 0
    
        while i <= n:
            total += i
            i += 1
            
        return total
        
    assert sum_n(5) == 15 # 1+2+3+4+5 = 15
    assert sum_n(7) == 28 # 1+2+3+4+5+6+7 = 28
    assert sum_n(10) == 55 #1+2+3+4+5+6+7+8+9+10 = 55

     

    2-2. while문: 모음 빼고 자음만 출력하기

    def remove_vowels(string):
        vowels = ['a','e','i','o','u']
    
        while vowels:
            vowel = vowels.pop()
            string = string.replace(vowel,'')
    
        return string
        
    assert remove_vowels('hello') == 'hll'
    assert remove_vowels('python') == 'pythn'
    assert remove_vowels('data science') == 'dt scnc'

     

    3-1. for문: 특정 이름 출력

    names = ["John Smith", "Jane Doe", "Bob Johnson"]
    for name in names:
        print(name.split()[0])
    >>> John
        Jane
        Bob

     

    3-2. for문: 1부터 n까지의 자연수 중에서 3의 배수이거나 5의 배수인 수의 합을 구하기

    -  n > 0

    def sum_multiple(n):
        result = 0
        for i in range(1, n+1):
            if i % 3 == 0 or i % 5 == 0:
                result += i
        return result
    
    assert sum_multiple(10) == 33 # 결과: 33 (3+5+6+9+10)
    assert sum_multiple(16) == 60 # 결과: 60 (3+5+6+9+10+12+15)

     

    댓글