printf("ho_tari\n");

반복문 본문

Python

반복문

호타리 2023. 10. 12. 15:27

<for.py>

for looper in [1, 2, 3, 4, 5]:
    print("hello")

for looper in [1, 2, 3, 4, 5]:
    print(looper)

for looper in range(10):
    print("hello")

for i in 'abcdefg':
    print(i)

for i in ['americano', 'latte', 'frappuccino']:
    print(i)

for i in range(1, 10, 2):   # 1부터 9까지 2씩 증가시키면서 반복문 수행
    print(i)

for i in range(10, 1, -1):  # 10부터 2까지 1씩 감소시키면서 반복문 수행
    print(i)

<compile 결과>

 

<while.py>

i = 1               # i 변수에 1 할당
while i < 10:       # i가 10미만인지 판단
    print(i)        # 조건을 만족할 때 i 출력
    i += 1          # i에 1을 더하는 것을 반복하다가 i가 10이 되면 반복 종료

<compile 결과>

 

<break.py>

for i in range(10):
    if i == 5: break        # i가 5가되면 종료
    print(i)
print("End of Program")     # 반복 종료 후 'End of Program' 출력

<compile 결과>

 

<continue.py>

for i in range(10):
    if i == 5: continue     # i가 5가 되면 i를 출력하지 않음
    print(i)
print("End of Program")     # 반복 종료 후 'End of Program' 출력

<compile 결과>

 

<else.py>

for i in range(10):
    print(i)
else:
    print("End of Program")

<compile 결과>

 

<calaulator1.py>

print("구구단 몇 단을 계산할까?")
user_input = input()
print("구구단", user_input, "단을 계산한다.")
int_input = int(user_input)

for i in range(1, 10):
    result = int_input * i
    print(user_input, "x", i, "=", result)

<compile 결과>

 

<reverse_sentence.py>

sentence = "Ho_tari"

reverse_sentence = ''

for char in sentence:
    reverse_sentence = char + reverse_sentence

print(reverse_sentence)

<compile 결과>

 

<decimal.py>

decimal = 10

result = ''

while (decimal > 0):
    remainder = decimal % 2
    decimal = decimal // 2
    result = str(remainder) + result

print(result)

<compile 결과>

 

<guess_number.py>

import random   # 난수 발생 함수 호출

guess_number = random.randint(1, 100)   # 1~100 사이 정수 난수 발생
print("숫자를 맞혀 보세요. (1 ~ 100)")

users_input = int(input())  # 사용자 입력을 받음

while (users_input is not guess_number):    # 사용자 입력과 난수가 같은지 판단
    if users_input > guess_number:  # 사용자 입력이 클 경우
        print("숫자가 너무 큽니다.")
    else:                           # 사용자 입력이 작을 경우
        print("숫자가 너무 작습니다.")
    users_input = int(input())      # 다시 사용자 입력을 받음
else:
    print("정답입니다.", "입력한 숫자는", users_input, "입니다.")   # 종료 조건

<compile 결과>

<calculator2.py>

print("구구단 몇 단을 계산할까요(1~9)?")

x = 1

while (x is not 0):
    x = int(input())

    if x == 0:
        break

    if not(1 <= x <= 9):
        print("잘못 입력했습니다", "1부터 9 사이 숫자를 입력하세요.")
        continue

    else:
        print("구구단" + str(x) + "단을 계산합니다.")
        
        for i in range(1, 10):
            print(str(x) + "x" + str(i) + "=" + str(x*i))

        print("구구단 몇 단을 계산할까요(1~9)?")

print("구구단 게임을 종료합니다.")

<compile 결과>

 

<average.py>

kor_score = [49, 80, 20, 100, 80]
math_score = [43, 60, 85, 30, 90]
eng_score = [49, 82, 48, 50, 100]
midterm_score = [kor_score, math_score, eng_score]

student_score = [0, 0, 0, 0, 0]

i = 0

for subject in midterm_score:
    for score in subject:
        student_score[i] += score   # 학생마다 개별로 교과 점수를 저장
        i += 1  # 학생 인덱스 구분
    i = 0   # 과목이 바뀔 때 학생 인덱스 초기화

else:
    a, b, c, d, e = student_score   # 학생별 점수를 언패킹
    student_average = [a/3, b/3, c/3, d/3, e/3]
    print(student_average)

<compile 결과>

 

<trapezium_def.py>

def addition(x, y):
    return x + y

def multiplication(x, y):
    return x * y

def divided_by_2(x):
    return x / 2

if __name__ == '__main__':
    print(addition(10, 5))
    print(multiplication(10, 5))
    print(divided_by_2(50))

<compile 결과>

 

<trapezium_area.py>

def addition(x, y):
    return x + y

def divided_by_2(x):
    return x / 2

def main():
    base_line = float(input("밑변의 길이는? "))
    upper_edge = float(input("윗변의 길이는? "))
    height = float(input("높이는? "))

    print("넓이는:", divided_by_2(addition(base_line, upper_edge) * height))

if __name__ == '__main__':
    main()

<compile 결과>

'Python' 카테고리의 다른 글

문자열  (0) 2023.10.16
함수  (0) 2023.10.16
조건문  (0) 2023.10.12
리스트  (0) 2023.10.12
입출력 함수, 화씨온도 변환기  (0) 2023.10.12