[TIL] Python 천천히 복습_List, Dictionary, if, for, enumerate, break, max, def

2023. 8. 18. 19:53Today I Learned (TIL)

Python 기초부터 심화강의를 모두 들었다. 이전 웹개발강의나 SQL강의는 강의를 들으면서 바로 코드를 써보면서 하니, 중간에 이해안가는 부분들은 생각해보기도 하고 다시 듣기도 하면서 수업을 듣는데 시간이 꽤 많이 필요했는데, 이번에는 우선 한번 훑고 다시한번 듣자는 마음으로 코드를 쓰지 않고 수업만 먼저 들어버렸는데, 그러니 수업을 꽤나 날려들은것 같다는 생각이 든다. 이제 기초부터 심화까지 강의자료를 보면서 혼자 코드를 써보면서 따라가보고, 이해가 안가는 부분이나 설명이 필요한 부분은 그때그때 다시 강의를 찾아보면서 학습을 하려고 한다. 

 

오늘목표: 기초강의자료를 모두 한번씩 써보면서 머릿속에, 그리고 손가락에 문법을 익힌다. 


List

 

# 이메일 주소에서 도메인 'gmail'만 추출하기
myemail = 'test@gmail.com'

result = myemail.split('@') # ['test','gmail.com'] (뒤에 배울 '리스트'라는 자료형이에요 :))

result[0] # test (리스트의 첫번째 요소)
result[1] # gmail.com (리스트의 두 번째 요소

result2 = result[1].split('.') # ['gmail','com']

result2[0] # gmail -> 우리가 알고 싶었던 것
result2[1] # com

# 한 줄로 한 번에!
myemail.split('@')[1].split('.')[0]

 

myemail = 'abc@sparta.co'

domain = myemail.split('@')[1].split('.')[0]
print(domain[:3]) #spa

Dictionary

person = {"name": "Bob", "age": 21}
print(person["name"]) #Bob

 

person = {"name":"Alice", "age": 16, "scores": {"math": 81, "science": 92, "Korean": 84}}
print(person["scores"])             # {'math': 81, 'science': 92, 'Korean': 84}
print(person["scores"]["science"])  # 92
people = [{'name': 'bob', 'age': 20}, {'name': 'carry', 'age': 38}]

# people[0]['name']의 값은? 'bob'
# people[1]['name']의 값은? 'carry'

person = {'name': 'john', 'age': 7}
people.append(person)

# people의 값은? [{'name':'bob','age':20}, {'name':'carry','age':38}, {'name':'john','age':7}]
# people[2]['name']의 값은? 'john'

if, elif, else

age = 27
if age < 20:
    print("청소년입니다.")
elif age < 65:
    print("성인입니다.")
else:
    print("무료로 이용하세요!")

for

fruits = ['사과', '배', '감', '귤']

for fruit in fruits:
    print(fruit)
people = [
    {'name': 'bob', 'age': 20},
    {'name': 'carry', 'age': 38},
    {'name': 'john', 'age': 7},
    {'name': 'smith', 'age': 17},
    {'name': 'ben', 'age': 27},
    {'name': 'bobby', 'age': 57},
    {'name': 'red', 'age': 32},
    {'name': 'queen', 'age': 25}
]

for person in people:
    if person['age'] > 20:
        print(person['name'])

enumerate, break

 

fruits = ['사과', '배', '감', '귤', '귤', '수박', '참외', '감자', '배', '홍시', '참외', '오렌지']

for i, fruit in enumerate(fruits):
    print(i, fruit)
    if i == 4:
        break

max

 

num_list = [1, 2, 3, 6, 3, 2, 4, 5, 6, 2, 4]

max_value = 0
for num in num_list:
    if max_value < num:
        max_value = num
print(max_value)

def

def bus_rate(age):
    if age > 65:
        print("free")
    elif age > 20:
        print("adult")
    else:
        print("adolescence")

bus_rate(35)
bus_rate(18)
bus_rate(91)

 

 

Friday Venus