파이썬 반복문

JOOYEUN SEO·2024년 8월 12일

100 Days of Python

목록 보기
5/76
post-thumbnail

🔁 반복문(loops)

❖ 리스트로 for 반복문 사용

  • 리스트 내 각 항목에 개별적으로 접근하여 작업을 수행하는 것을 반복
  • 들여쓰기로 for문 안에 작성한 명령어들이 모두 수행됨
for item in list_of_items:
	# Do something to each item
fruits = ["Apple", "Peach", "Pear"]
for fruit in fruits:
  print(fruit)
  print(fruit + " Pie")
print(fruits)	# 들여쓰기 주의
Apple
Apple Pie
Peach
Peach Pie
Pear
Pear Pie
['Apple', 'Peach', 'Pear']

💯 coding exercises

Average Height
학급 학생들의 평균 키를 구하는 프로그램

  • for문 사용하기
# Input a Python list of student heights
student_heights = input().split()
for n in range(0, len(student_heights)):
  student_heights[n] = int(student_heights[n])
  
# Write your code below this row 👇
total_height = 0
num_of_students = 0

for h in student_heights:
  total_height += h
  num_of_students += 1

average_height = round(total_height / num_of_students)

print(f"total height = {total_height}")
print(f"number of students = {num_of_students}")
print(f"average height = {average_height}")
151 145 179
total height = 475
number of students = 3
average height = 158

💯 coding exercises

High Score
학생들의 성적 중 가장 높은 점수를 찾는 프로그램

  • for문으로 숫자가 담긴 리스트 순회하기
# Input a list of student scores
student_scores = input().split()
for n in range(0, len(student_scores)):
  student_scores[n] = int(student_scores[n])

# Write your code below this row 👇
max_number = 0

for score in student_scores:
  if score > max_number:
    max_number = score

print(f"The highest score in the class is: {max_number}")
78 65 89 86 55 91 64 89
The highest score in the class is: 91

❖ for 반복문과 range() 함수

range( start, stop, step )

  • start : 범위의 시작(포함) [ 디폴트 값 = 0]
  • stop : 범위의 끝(제외)
  • step : 숫자의 증가량 [ 디폴트 값 = 1]
# for문과 range() 함수로 1부터 100까지 모두 더한 수 계산
total = 0
for number in range(1, 101):
  total += number
print(total)
5050

💯 coding exercises

Adding Even Numbers
1부터 입력한 숫자까지의 사이에 있는 모든 짝수의 합을 구하는 프로그램

target = int(input()) # Enter a number between 0 and 1000

# Write your code here 👇
even_sum = 0
for number in range(2, target+1, 2):
  even_sum += even
print(even_sum)
52
702

💯 coding exercises

FizzBuzz
피즈버즈(FizzBuzz) 게임 프로그램

규칙

  • nn명의 참가자들이 원형으로 서서 1부터 시작해 돌아가면서 한 명씩 숫자를 외침
  • 3의 배수를 만나면, 숫자 대신 '피즈'를 외침
  • 5의 배수를 만나면, 숫자 대신 '버즈'를 외침
  • 3과 5의 배수를 만나면, 숫자 대신 '피즈버즈'를 외침 (가장 먼저 체크해야 하는 조건)
# Write your code here 👇
end_number = 100
for number in range(1, end_number+1):
  if number % 3 == 0 and number % 5 == 0:
    print("FizzBuzz")
  elif number % 3 == 0:
    print("Fizz")
  elif number % 5 == 0:
    print("Buzz")
  else:
    print(number)
1
2
Fizz
4
Buzz
...중략...
Fizz
Buzz

🗂️ Day5 프로젝트 : 비밀번호 생성기

해킹에 안전한 복잡한 비밀번호를 생성해 주는 프로그램

🔍 유의 사항

  • 2가지 버전 존재
    • 쉬운 버전 : 입력 순서(글자, 기호, 숫자)대로 출력
    • 어려운 버전 : 입력한 것들을 무작위 순서대로 출력
  • 리스트에서 사용하는 random() 함수 메서드 (Python Random Module)
    • random.choice( sequence )
      • 리스트에서 랜덤으로 한 개의 원소 추출 후, 문자열로 반환
      • 같은 문자를 중복 추출 가능하게 하려면 for문과 함께 사용
    • random.sample( sequence, k )
      • 리스트에서 랜덤으로 여러 개의 원소 추출 후, 리스트로 반환
      • k : 추출하고자 하는 원소의 개수
      • 같은 문자를 중복 추출하지 않으므로, k는 기존 리스트의 길이보다 작아야 함
      • 기존 리스트는 변경되지 않음
    • random.shuffle( sequence )
      • 리스트의 항목들을 랜덤으로 재배열
      • 새로운 리스트를 반환하는 것이 아니라, 기존 리스트가 변경됨

⌨️ 작성한 코드

#Password Generator Project
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"))

#Eazy Level - Order not randomised:
#e.g. 4 letter, 2 symbol, 2 number = JduE&!91
letter_list = random.sample(letters, nr_letters)
symbol_list = random.sample(symbols, nr_symbols)
number_list = random.sample(numbers, nr_numbers)
password_list = letter_list + symbol_list + number_list

easy_password = ""
for char in password_list:
    easy_password += word
print(f"Here is your password : {easy_password}")

#Hard Level - Order of characters randomised:
#e.g. 4 letter, 2 symbol, 2 number = g^2jk8&P
letter_list = random.sample(letters, nr_letters)
symbol_list = random.sample(symbols, nr_symbols)
number_list = random.sample(numbers, nr_numbers)
password_list = letter_list + symbol_list + number_list
random.shuffle(password_list)

hard_password = ""
for char in password_list:
    hard_password += word
print(f"Here is your password : {hard_password}")
# Eazy Level
Welcome to the PyPassword Generator!
How many letters would you like in your password?
4
How many symbols would you like?
2
How many numbers would you like?
3
Here is your password : gPnO!%183

# Hard Level
Welcome to the PyPassword Generator!
How many letters would you like in your password?
4
How many symbols would you like?
3
How many numbers would you like?
2
Here is your password : 0#wD4+(Ga

🖍️ 답안

#Eazy Level
password = ""				# 빈 문자열로 초기화

for char in range(1, nr_letters + 1):
  password += random.choice(letters)
for char in range(1, nr_symbols + 1):
  password += random.choice(symbols)
for char in range(1, nr_numbers + 1):
  password += random.choice(numbers)

print(password)

#Hard Level
password_list = []			# shuffle 메서드를 쓰기 위해 빈 리스트로 초기화

for char in range(1, nr_letters + 1):
  password_list.append(random.choice(letters))	# append(), + 둘 다 가능 
for char in range(1, nr_symbols + 1):
  password_list += random.choice(symbols)
for char in range(1, nr_numbers + 1):
  password_list += random.choice(numbers)

random.shuffle(password_list)

password = ""
for char in password_list:	# 리스트를 문자열로 바꾸는 작업
  password += char

print(f"Your password is: {password}")

random 모듈의 sample 메서드는 같은 문자를 중복으로 뽑을 수 없기 때문에
일반적인 비밀번호 생성에서는 답안처럼 choice 메서드를 쓰는 것이 더 적절할 것 같다




▷ Angela Yu, [Python 부트캠프 : 100개의 프로젝트로 Python 개발 완전 정복], Udemy, https://www.udemy.com/course/best-100-days-python/?couponCode=ST3MT72524

0개의 댓글