1. for(반복문)
for문은 원하는 명령을 반복할 때 쓰입니다
ex) 리스트를 만들어 for문을 시용해 리스트의 원소들을 출력해 보겠습니다
fruits = ["Apple", "Peach", "Pear"]
for fruit in fruits:
print(fruit)
결과: Apple
Peach
Pear
1) 실습예제
Exercise)
student_heights = input("Input a list of student heights ").split()
for n in range(0, len(student_heights)):
student_heights[n] = int(student_heights[n])
위 코드는 수정하지 않고 코드를 추가하여 입력한 키들의 평균을 출력하는 프로그램을 작성하세요
Solution)
student_heights = input("Input a list of student heights ").split()
for n in range(0, len(student_heights)):
student_heights[n] = int(student_heights[n])
total_height = 0
for sum_height in student_heights:
total_height += sum_height
len_height = 0
for sum_len_height in student_heights:
len_height += 1
avg_height = total_height / len_height
print(round(avg_height))
- 먼저 키의 합계를 담을 변수를 선언합니다
- for문 안에 total_height += sum_height는 다음과 같은 수식을 의미합니다
- total_height = total_height + sum_height
- 따라서 반복문을 통해 입력된키를 최종키에 더하고 그 최종키를 다시 다음 입력된키와 더해서 모든 입력된 키들의 합을 구합니다
- 평균키를 구하려면 키의합계를 사람수대로 나누면됩니다
- 키의개수는 반복문을 통해 계속 1씩더하고 새로운 변수를 만들어 평균키를 저장하여 출력합니다.
2. for문과 range()함수
- 앞에서는 리스트를 이용해 for문을 사용하는 방법이었습니다.
- 이번에는 숫자를 이용해 1 부터 100까지의 합과 같은 사람이 계산하기에 시간이 많이드는 계산을 하는 방법입니다.
ex) 1부터 100까지 합을 구하는 for문을 만들어보겠습니다
total = 0
for number in range(1, 101):
total += number
print(total)
- 최초합계는 0으로 저장합니다
- for문 안에 number라는 변수를 선언하고 1부터 100까지(1, 100은 1부터 99를 의미합니다) 반복하게 합니다
- 처음은 합계의 1을더해 total변수에 저장하고 그 다음은 total변수의 1에 2를 더한 값을 total에 저장하는 방식으로 100까지 반복합니다
- 최종적으로 계산한 값을 출력합니다.
1) 실습예제
Exercise) 1부터 100까지 짝수만 더한 값을 출력하는 프로그램을 만드세요
Solution)
total = 0
for number in range(2, 101, 2):
total += number
print(total)
- total변수를 선언합니다
- range(a, b, c)는 a부터 b-1까지 c만큼 건너뛴 숫자들을 반복하라는 뜻입니다 즉, (2, 101, 2)는 2부터 100까지 2만큼 건너서 숫자들을 계산하라는 뜻입니다 (ex)2+4+6+8+10+...
- total변수에 더한값들을 저장해 반복합니다
- 최종적으로 계산한 값을 출력합니다
3. 비밀번호 생성기
Exercise)
import random
letters = [
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D',
'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
]
numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+']
print("Welcome to the PyPassword Generator!")
nr_letters = int(input("How many letters would you like in your password?\n"))
nr_symbols = int(input(f"How many symbols would you like?\n"))
nr_numbers = int(input(f"How many numbers would you like?\n"))
위 코드는 수정하지 않고 코드를 추가하여 랜덤한 비밀번호를 만들어주는 프로그램을 작성하세요(단, 문자와숫자,기호의 위치는 고정되어도 괜찮습니다)
Solution)
import random
letters = [
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D',
'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
]
numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+']
print("Welcome to the PyPassword Generator!")
nr_letters = int(input("How many letters would you like in your password?\n"))
nr_symbols = int(input(f"How many symbols would you like?\n"))
nr_numbers = int(input(f"How many numbers would you like?\n"))
password = ""
for f_letters in range(1, nr_letters+1):
ch_letters = random.choice(letters)
password += ch_letters
for f_numbers in range(1, nr_numbers+1):
ch_numbers = random.choice(numbers)
password += ch_numbers
for f_symbols in range(1, nr_symbols+1):
ch_symbols = random.choice(symbols)
password += ch_symbols
print(password)
'Python Study' 카테고리의 다른 글
Python Study(반복문(While)) (0) | 2023.02.18 |
---|---|
Python Study(함수 정의 및 호출/들여쓰기) (0) | 2023.02.18 |
Python Study(리스트/중첩 리스트) (0) | 2023.02.01 |
Python Study(random모듈) (0) | 2023.02.01 |
Python Study(조건문/중첩 조건문/논리 연산자) (0) | 2023.01.26 |