우선 파이썬 문법을 급하게 공부하는 이유는 코딩테스트에 파이썬이 가장 적합하다는것을 이제 깨달았다.
아무리 자바를 사랑하고 애정을 가진다해도 코딩테스트 만큼은 파이썬으로 공부하리..
파이썬 변수 선언과 자료형
- 파이썬에서 새 변수를 만들 때는
변수이름 = 값
의 형태 - .
a = b
와b = a
는 다르다
숫자형과 자료형
a = 7
b = 2
a+b # 9
a-b # 5
a*b # 14
a/b # 3.5
a//b # 3 (몫)
a%b # 1 (나머지)
a**b # 49 (거듭제곱)
bool 자료형
- 참/ 거짓을 나타내는 boolean 자료형
x = True # 참
y = False # 거짓
# 소문자로 쓰면 자료형으로 인식하지 않고 변수명이라 생각해 에러가 납니다~
z = true # name 'true' is not defined
True = 1 # True/False는 변수명으로 쓸 수 없다
숫자들의 평균 구하기
a= 3
b= 5
c= 6
result = (a+b+c)/3
문자열 다루기
a = "aa"
b = 'aa'
둘다 같음
문자열의 길이는
len() 써서 구할수있음
len(a)
==2
그외 다양한기능 . <- 을써서 메소드를 사용가능
sentance = 'kimjongha'
sentance.upper() #KIMJONGHA
sentance.lower() #kimjongha
#이메일에서 아이디만 빼기
email = 'rlawhdgk99@gmail.com'
result = email.split('@')
print(result) #['rlawhdgk99', 'gmail.com']
result2 = result[1].split('.')
print(result2) #['gmail', 'com']
#이 행위를 한번에하면
print(email.split('@')[1].split('.')[0]) #gmail
인덱싱과 슬라이싱
#문자열을 일부를 잘라내는것을 슬라이싱
sentence = "abcdefghijklmnopqrstuvwxyz"
print(sentence[1]) #b
print(sentence[0:5]) #abcde 0부터 4개 즉 5개
print(sentence[:3])
# 지역번호출력하기
phone = "02-123-1234"
print(phone.split('-')[0])
리스트
순서가 있는, 다른 자료형들의
a = [1, 5, 2]
b = [3, "a", 6, 1]
c = []
d = list()
e = [1, 2, 4, [2, 3, 4]]
리스트의 길이도 len() 함수를 사용해서 가능
a = [1, 5, 2]
print(len(a)) # 3
b = [1, 3, [2, 0], 1]
print(len(b)) # 4
덧붙이기
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]
요소가 리스트안에 있는지
a = [2, 1, 4, "2", 6]
print(1 in a) # True
print("1" in a) # False
print(0 not in a) # True
딕셔너리
딕셔너리는 key 와 value 로 이루어진 자료의 모임이다.
person = {"name":"Bob", "age": 21}
print(person["name"]) #Bob
print(person[0]) # 0이라는 key가 없으므로 KeyError 발생!
person["name"] = "Robert"
print(person) # {'name': 'Robert', 'age': 21} 업데이트 가능
person["height"] = 174.8
print(person) # {'name': 'Robert', 'age': 21, 'height': 174.8} 값 추가도 가능
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}]
print(people[0]['name'])
newperson ={'name':'jongha','age':26}
people.append(newperson)
print(people)
조건문
if
문
money = 5000
if money > 3800:
print("택시 타자!")
elif money>2000:
print("킥보드타자")
else:
print("걷자")
반복문
fruits = ['사과', '배', '감', '귤']
for fruit in fruits:
print(fruit)
for i in range(4):
print(fruits[i])
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}
]
이 리스트에서 나이가 20보다 큰 사람만 출력합니다.
for person in people:
if person['age'] >20:
print(person)