개발일기 21.05.02_파이썬 기본 문법

Nhahan·2021년 5월 2일
0

항해99 개발일기

목록 보기
4/31

기본 연산

a = 3
b = 2
print(a+b)
print(a*b)
print(a-b)
print(a/b)
print(a**b)
print(a%b)
print(a>b)
print(a==b)

문자열 연산
first_name = "SY"
last_name = "Kim"
print(first_name + last_name)

문자열 길이
text = "abcdefghijk"
result = len(text)
print(result)

슬라이싱
result2 = text[3:]
print(result2)

스플릿
myemail = "abc@sparta.co"
result3 = myemail.split('@')[1].split('.')[0]
print(result3)

리스트, 리스트 추가(append)
a_list = ["사과","배","감"]
print(a_list[0])
a_list.append(99)
print(a_list)

리스트 추출
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}}
]
print(people[0]["score"]["math"])


조건문
money = 3000
if money > 3800:
    print("택시못타")
elif money > 1200:
    print("버스타자")
else:
    print("택시타자")

for문
fruits = ["사과","배","감","수박","딸기"]
for aaa in fruits:
    print(aaa)

for문과 리스트, 딕셔너리
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 ppp in people:
    name = ppp["name"]
    age = ppp["age"]
    if age > 20:
        print(name, age)

for문과 enumerate / 리스트 갯수, 총합, 최댓값
count = 0
sum = 0
max = 0
num_list = [1, 2, 3, 6, 3, 2, 4, 5, 6, 2, 4]
for i, num in enumerate(num_list):
    sum = sum + num
    if (num % 2) == 0:
        print(num)
        count += 1
    if (num > max):
        max = num
print(count)
print(sum)
print(max)

함수
def hello():
    print("안녕!")
hello()

def sum(a,b):
    return a + b
print(sum(2,1))

함수를 이용한 주민등록번호 성별 체크
def check_gender(pin):
    check = pin.split('-')[1][:1]
    if (int(check) % 2) == 0:
        print("여자입니다")
    else:
        print("남자입니다")
check_gender("123456-1234567")
check_gender("123456-4242424")

튜플
a = ("사과","감","배")
print(a[1]) #튜플은 리스트와 비슷하지만 불변형이다. 뭔가를 추가하거나 뺄 수 없음.

set을 이용한 집합, 리스트, 튜플 간의 변환 (중복제거)
a_set = set([1,2,3,4,1])
print(a_set)
a_list = list(a_set) #집합을 리스트로 변환 (튜플로도 변환 가능)
a_tuple = tuple(a_set)
print(a_list) #집합은 중복을 제거해준다

집합의 연산(교집합&, 합집합+, 차집합-)
student_a = ['물리2','국어','수학1','음악','화학1','화학2','체육']
student_b = ['물리1','수학1','미술','화학2','체육']
difference = set(student_b) - set(student_a)
print(difference)

f스트링
scores = [
    {'name':'영수','score':70},
    {'name':'영희','score':65},
    {'name':'기찬','score':75},
    {'name':'희수','score':23},
    {'name':'서경','score':99},
    {'name':'미주','score':100},
    {'name':'병태','score':32}
]
print(scores[1])
for i in scores:
    name = i["name"]
    score = str(i["score"])
    print(f'{name}의 점수는 {score}점입니다.')

0개의 댓글