본문 바로가기

알고리즘/파이썬 문법

파이썬 문법 뽀개기 기초

728x90

파이썬 문법 뽀개기 기초

 

파이썬을 설치했다 = 일종의 번역팩을 설치했다.

 

editor : Pycharm

파이썬 : Python 3.8 

 


Pycharm 폰트 Size 조절

[Setting]-[Editor]-[General]-[Change font size with Ctrl+Mouse Wheel in] 체크

 

 

파일

[New Project]

  • Location : 마지막 \venv 파일 확인
  • Base interpreter : Python38 확인

변수

 

값을 담는 박스

메모리에 저장된 값을 가리키고 있다.

 

📌 문자열

a = 'dbyeon'

변수랑 헷갈리지 않도록 작은따음표(')로 감싸줌

 

📌 기본 사칙연산

a = 3
b = 2

a+b
a-b
a*b
a/b

# 나머지
a%b

# 제곱
a**b

# 몫
a//b

 

📌 Boolean

a = (3 < 2)

print(a)

# False

 

숫자들 평균 구하기 quiz

a = 24
b = 16
c = 26

avg = (a+b+c)/3
print(avg)

문자열

 

따음표로 감싸지 않으면 변수를 의미하기 때문에 꼭 구분해서 사용해야 함!

a = '2'
b = str(2)

print(a + b)

a와 b는 모두 문자열 2를 의미함.

str은 string을 의미함. 보통 형변환을 해줄때 사용.

 

str(Integer)는 정수형을 문자열로 변환해라. 

 

 

📌 슬라이싱

문자열 일부를 잘라낼 때 사용

text = 'abcdefghijk'

# 문자열 길이
result = len(text)

# 인덱스 0, 1, 2 abc
result = text[:3]

# 인덱스 3부터 끝까지 defghijk
result = text[3:]

# text 전체 복사
result = text[:]

 

문자열 quiz

# spa만 추출
myemail = 'abc@sparta.co'
result = myemail.split('@')[1].split('.')

print(result[0][:3])

# 지역번호만 추출
phone = "02-123-1234"

print(phone.split('-')[0])

 


리스트(list) 와 딕션너리(dictionary)

 

📌 리스트(list)

순서가 중요한 자료형

a_list = [2, '배', False, ['사과', '감']]

print(a_list[3])
print(a_list[3][1])

 

리스트에 값 추가

a_list = [1,5,6,3,2]
print(a_list)
# [1, 5, 6, 3, 2]

a_list.append(99)
print(a_list)
# [1, 5, 6, 3, 2, 99]

 

덧붙이기, 정렬, 요소가 리스트 안에 있는지 알아보기

a_list = [1,5,6,3,2]

# [1, 5, 6]
result = a_list[:3]

# 리스트 맨 끝 2
result = a_list[-1]

# 리스트 길이 구하기
result = len(a_list)

# 리스트 오름차순
a_list.sort()

# 리스트 내림차순
a_list.sort(reverse=True)

# 5가 a_list에 있니? True
result = (5 in a_list)

 

📌 딕션너리(dictionary)

key:value로 값을 담는 자료형

순서가 없음.

a_dict = {'name':'bob', 'age':27, 'friend':['영희', '철수']}

# key값으로 value 접근, bob
result = a_dict['name']

# key값으로 value list 접근, 철수
result = a_dict['friend'][1]

# dictionary에 키와 벨류 추가
a_dict['height'] = 180

# dictionary에 height키값 있니? True
result = ('height' in a_dict)

 

리스트안에 딕션너리 여러개 들어가 있는 형태

people = [
    {'name':'bob', 'age':27},
    {'name':'John', 'age':30}
]

# list형태 딕션너리 접근, 30
print(people[1]['age'])

 

리스트와 딕셔너리의 조합 quiz

smith의 science 점수를 추출

people = [
    {'name': 'bob', 'age': 20, 'score':{'math':90,'science':70}},
    {'name': 'carry', 'age': 38, 'score':{'math':40,'science':72}},
    {'name': 'smith', 'age': 28, 'score':{'math':80,'science':90}},
    {'name': 'john', 'age': 34, 'score':{'math':75,'science':100}}
]

# smith의 science 점수 출력
science_score = people[2]['score']['science']

print(science_score)

조건문

if와 else

money = 3000

if money > 3800:
    print('택시  를 타자!')
elif money > 1200:
    print('버스를 타자!')
else:
    print('걸어가자')

파이썬 문법에서 들여쓰기가 매우 중요!!


반복문

fruits = ['사과', '배', '감', '수박', '딸기']

for fruit in fruits:
    print(fruit)

반복문의 기본적인 형태. fruit는 리스트 값 인덱스를 의미하므로 aaa라고 써도 무방.

 

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 i, person in enumerate(people):
    name = person['name']
    age = person['age']
    print(i, name, age)

    if i > 2:
        break

 

출력

0 bob 20
1 carry 38
2 john 7
3 smith 17

 

📌 enumerate란?

요소를 numbering해줌.

무수히 많은 데이터를 처리할 때, 시간이 많이 소요되므로 일부 데이터만 추출해(if i>2: break) 코드 작업을 해줄 때 사용.


📌 반복문 연습

 

quiz1. 리스트에서 짝수만 출력

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

for num in num_list:
    if num % 2 == 0:
        print(num)

 

quiz2. 리스트에서 짝수의 갯수 출력

count = 0
for num in num_list:
    if num % 2 == 0:
        count += 1
        
print(count)

 

quiz3. 리스트안에 모든 숫자 더하기

sum = 0
for num in num_list:
    sum += num

print(sum)


print(sum(num_list))

 

quiz4. 리스트안에 가장 큰 숫자 구하기

max = num_list[0]
for num in num_list:
    if max < num:
        max = num

print(max)


print(max(num_list))

함수

def bus_rate(age):
    if age > 65:
        print('무료입니다')
    elif age > 20:
        print('성인입니다')
    else:
        print('청소년입니다')

bus_rate(15)

구문을 여러번 쓰지 않아도 로직을 사용할 수 있는 것.

 

quiz 주민등록번호 입력받아 성별 출력하는 함수

def check_gender(pin):
    num = int(pin.split('-')[1][0])
    if num % 2 != 0:
        print('남성')
    else:
        print('여성')

check_gender('200101-3012345')
check_gender('990101-2012345')
check_gender('940101-1012345')

'알고리즘 > 파이썬 문법' 카테고리의 다른 글

입출력  (0) 2023.02.22
파이썬 문법 뽀개기 심화  (0) 2022.11.21