내일배움캠프 사전캠프 8일차 - 파이썬 기본 문법
1. 오늘 학습 키워드
파이썬 변수, 숫자형, bool, 문자열, 리스트, 딕셔너리, 조건문(if/ else), 반복문(for), 함수
2. 오늘 학습 한 내용을 나만의 언어로 정리하기
1. 변수 선언과 자료형
-파이썬에서 새 변수를 만들때는 변수이름=값의 형태로 씀. (a=b와 b=a는 다르다..)
-출력은 print()
*모르는 것은 검색!
구글에 파이썬 나머지 구하기, 파이썬 거듭제곱 등 쳐보기
1) 변수 선언
a = 3 # 3을 a에 넣는다.
print(a)
b = a # a에 들어 있는 값인 3을 b에 넣는다.
print(b)
a = 5 # a에 5라는 새로운 값을 넣는다.
print(a, b) # 5 3
2) 숫자형 자료형 - ( +, -, *, / )
a=7
b=2
a//b # 3 (몫)
a%b # 1 (나머지)
a**b # 49 (거듭제곱)
a+3*b # 13 (여러 연산을 한 줄에 할 경우 사칙연산의 순서대로!)
(a+3)*b # 20 (소괄호를 이용해서 먼저 계산할 부분을 표시o)
a = 5
a = a + 3 # a+=3
print(a) #8
3) Bool 자료형
x = True # 참
y = False # 거짓
# 소문자로 쓰면 자료형으로 인식하지 않고 변수명이라 생각해 에러가 남
z = true # name 'true' is not defined
True = 1 # True/False는 변수명으로 쓸 수 없음
a = 4 > 2 # True
not a # False NOT 연산자로 참을 거짓으로, 거짓을 참으로 바꿔준다.
a and b # False AND 연산자로 모두 참이어야 참을 반환한다.
a or b # True OR 연산자로 둘 중 하나만 참이면 참이다.
4) 문자열 (반드시 작은따옴표 or 큰따옴표로 묶어주기)
first_name = "Harry"
last_name = "Potter"
first_name + last_name # HarryPotter
first_name + " " + last_name # Harry Potter
a = "3"
b = "5" # b=str(5)
a + b # 35
*숫자와 문자를 더하면 에러 !
*대문자/소문자 변환: sentence.upper() // sentence.lower()
-문장 길이: print(len("문자열"))
print(len("abcde")) # 5
print(len("Hello, Sparta!")) # 14
print(len("안녕하세요.")) # 6
text = 'abcdefghijk'
result = text[:3] #abc
result = text[3:] #defghijk
result = text[3:8] #defgh
result = text[:] #abcdefghijk
print(result)
-특정 문자 기준으로 문자열 나누기
# 이메일 주소에서 도메인 '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]
-특정 문자를 다른 문자로 바꾸기
txt = '서울시-마포구-망원동'
print(txt.replace('-', '>')) # '서울시>마포구>망원동'
2. 리스트와 딕셔너리
1) 리스트 : 순서가 있는, 다른 자료형들의 모임
*len()으로 길이 잴 수 있음
a = [1, 5, 2]
b = [3, "a", 6, 1]
c = []
d = list()
e = [1, 2, 4, [2, 3, 4]]
a = [1, 2, [2, 3], 0]
print(a[2]) # [2, 3]
print(a[2][0]) # 2
-인덱싱과 슬라이싱 가능함
a = [1, 3, 2, 4]
print(a[3]) # 4
print(a[1:3]) # [3, 2]
print(a[-1]) # 4 (맨 마지막 것)
-덧붙이기(a.append(5)), 정렬하기(a.sort())
a = [1, 2, 3]
a.append(5)
print(a) # [1, 2, 3, 5]
a.append([1, 2])
print(a) # [1, 2, 3, 5, [1, 2]]
# 더하기 연산과 비교!
a += [2, 7]
print(a) # [1, 2, 3, 5, [1, 2], 2, 7]
a = [2, 5, 3]
a.sort()
print(a) # [2, 3, 5]
a.sort(reverse=True)
print(a) # [5, 3, 2]
-요소가 리스트 안에 있는지 보기 (in/ not in)
a = [2, 1, 4, "2", 6]
print(1 in a) # True
print("1" in a) # False
print(0 not in a) # True
2) 딕셔너리: 한 쌍(key + value)으로 이루어진 자료의 모임
*순서가 없어서 인덱싱 사용할 수 없음 (print(person[0]))
person = {"name":"Bob", "age": 21}
print(person["name"])
# 빈 딕셔너리 만들기
a = {}
a = dict()
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
-업데이트 및 추가
person = {"name":"Bob", "age": 21}
person["name"] = "Robert"
print(person) # {'name': 'Robert', 'age': 21}
person["height"] = 174.8
print(person) # {'name': 'Robert', 'age': 21, 'height': 174.8}
-키 존재 여부(in/ not in)
person = {"name":"Bob", "age": 21}
print("name" in person) # True
print("email" in person) # False
print("phone" not in person) # True
-리스트와 딕녀너리 조합
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'
3. 조건문
1) if문 : 조건을 만족했을 때만 특정 코드를 실행하도록 하는 문법
money = 5000
if money > 3800:
print("택시 타자!")
*들여쓰기 중요
2) else와 elif
money = 2000
if money > 3800:
print("택시 타자!")
else:
print("걸어가자...")
age = 27
if age < 20:
print("청소년입니다.")
elif age < 65:
print("성인입니다.")
else:
print("무료로 이용하세요!")
4. 반복문
1) for문
fruits = ['사과', '배', '감', '귤']
for fruit in fruits:
print(fruit)
people = [...] #각 사람의 name, age가 있음
# 리스트에서 나이가 20보다 큰 사람만 출력
for person in people:
if person['age'] > 20:
print(person['name'])
-enumerate, break
fruits = [...]
#앞에 5개만 출력
for i, fruit in enumerate(fruits):
print(i, fruit)
if i == 4:
break
-퀴즈: 짝수 출력
num_list = [1, 2, 3, 6, 3, 2, 4, 5, 6, 2, 4]
num_list = [1, 2, 3, 6, 3, 2, 4, 5, 6, 2, 4]
for num in num_list:
if num % 2 == 0:
print(num)
*짝수 출력= 2로 나눈 나머지가 0 -> if num % 2 ==0:
-퀴즈: 짝수 개수 출력 **
num_list = [1, 2, 3, 6, 3, 2, 4, 5, 6, 2, 4]
count = 0
for num in num_list:
if num % 2 == 0:
count += 1
print(count)
-퀴즈: 리스트 안에 있는 모든 숫자 더하기
result = 0
for num in num_list:
result += num
print(result)
*result += num
-퀴즈: 리스트 안에 있는 자연수 중 가장 큰 숫자 구하기
max = 0
for num in num_list:
if max < num:
max = num
print(max)
*변수를 하나 만들고, for문이 진행되면서 변수를 키우는 방식
5. 함수
-반복적으로 사용하는 코드들에 이름을 붙여놓은 것
def hello():
print("안녕!")
print("또 만나요!")
hello()
hello()
def bus_rate(age):
if age > 65:
print("무료로 이용하세요")
elif age > 20:
print("성인입니다.")
else:
print("청소년입니다")
bus_rate(27)
bus_rate(10)
bus_rate(72)
def bus_fee(age):
if age > 65:
return 0
elif age > 20:
return 1200
else:
return 0
money = bus_fee(28)
print(money)
-퀴즈: 주민등록번호를 입력받아 성별을 출력하는 함수 만들기
def check_gender(pin):
print(' ')
my_pin = '200101-3012345'
check_gender(my_pin)
def check_gender(pin):
num = pin.split('-')[1][0]
if int(num) % 2 == 0:
print('여성')
else:
print('남성')
my_pin = "200101-3012345"
check_gender(my_pin)
*최대한 쪼개서 적기(변수 설정)
*문자열을 출력할 때는 return이 아닌 print(' ')
* '2'라는 문자열을 숫자로 바꾸려면 -> int('2')
3. 학습하며 겪었던 문제점 & 에러
*변수를 하나 만들고, for문이 진행되면서 변수를 키우는 방식이 기본적임
*최대한 쪼개서 적기(변수 설정)
*문자열을 출력할 때는 return이 아닌 print(' ')
* '2'라는 문자열을 숫자로 바꾸려면 -> int('2')
4. 내일 학습 할 것은 무엇인지
파이썬 심화 문법