티스토리 뷰

파이썬[python]

파이썬 강좌 1-1

xemaker 2022. 5. 10. 08:56

파이썬 설치하고 jupyter 를 설치하고 실행하면 아래와 같이 뜬다.

자 이제 본격적으로 기초 파이썬에 관해 살펴보면

코드 입력 후 실행 Ctrl+Enter

코드 입력 후 실행 및 새 코드창 생성 Alt+Enter

아래는 코드 입력 다음에 결과 이런 순서로 쭉 진행된다.

print(100*3); 
print(2)
print(3)
300
2
3

 

for i in range(3):
    print(i)
print("실행종료")
0
1
2
실행종료

 

# 자료형
# 숫자형: 정수, 실수
print(10)
print(10.5)
# 연산자(+,-,*,/,%,//,**)
print(10+5)
print(10-5)
print(10*5)
print(10%3) # 나머지 연산자
print(10//3) # 몫 연산자
print(10**2) # 제곱
print(10**3) # 제곱

#리터럴 : 자연어 : 정수 리터럴, 실수 리터럴
a=10
print(a)
a=20
print(a)
a=20.5
print(a)

#문자 리터럴 : '',""
a='a'
print(a)
a="a"
print(a)
b="가나다"
print(b)
가나다='a'
print(가나다)
print(b)
print("가나다")
10
10.5
15
5
50
1
3
100
1000
10
20
20.5
a
a
가나다
a
가나다
가나다

 

print("Life is too short, You need python")
str1="Life is too short, You need python"
print(str1)
Life is too short, You need python
Life is too short, You need python

 

print("""Life is too short, 
      You need python""")
Life is too short, 
      You need python

 

print('''Life is too short, 
      You need python''')
# 문자열 리터럴: "", '', """""",''''''
Life is too short, 
      You need python

 

print("Life's too short, You need python")
Life's too short, You need python

 

print('Life is too short, "You need python"')
Life is too short, "You need python"

 

#숫자 리터럴(+,-,*,/,%,//,**)
#문자열 연산자:+,*
#print("가나다"+3)
head="Python "
tail="is fun"
print(head+tail) # 연결 연산자
print(head*3) # 반복연산자
print("="*30)
Python is fun
Python Python Python 
==============================

 

# indexing
a="Life is too short"
#  01234567890123456  # index
#            1 
#  76543210987654321 -
#         1
print(a[2])
print(a[16])
print(len(a))
print(a[len(a)-1])
print(a[-1]) # print(a[16])
print(a[-15]) #print(a[2])

# Life 가져오기
print(a[0],a[1],a[2],a[3])
print(a[0]+a[1]+a[2]+a[3])
f
t
17
t
t
f
L i f e
Life

 

#slicing
a="Life is too short"
#  01234567890123456  # index
#            1 
#  76543210987654321 -
#         1
print(a[1])
print(a[0:4]) # 0번부터 4번 이전까지
print(a[12:12+5])
print(a[-5:])
print(a[:0+4])
i
Life
short

short
Life

 

a="20010331Rainy"
birth=a[:8]
name=a[8:]
print(birth)
print(name)
year=a[:4]
month=a[4:4+2]
day=a[6:6+2]
print(year)
print(month)
print(day)
20010331
Rainy
2001
03
31

 

#가나다의 계좌 1111에는 100원이 있다.
name='가나다'
account='1111'
money=100
#문자열 포매팅
#print(name+"의 계좌" +account+" 에는+" +money+"원이 있다.")
print("%s의 계좌 %s에는 %d원이 있다."%(name,account,money))

###가나다의 나이는 25살이고 키는 175.3 입니다.
age=25
height=175.3
print("%s의 나이는 %d살이고 키는 %f 입니다."%(name,age,height))
print("%s의 나이는 %d살이고 키는 %.1f 입니다."%(name,age,height))
print("%s의 나이는 %10d살이고 키는 %.1f 입니다."%(name,age,height))
print("%s의 나이는 %-10d살이고 키는 %.1f 입니다."%(name,age,height))
print("%10s의 나이는 %-10d살이고 키는 %.1f 입니다."%(name,age,height))
print("%-10s의 나이는 %-0d살이고 키는 %.1f 입니다."%(name,age,height))
가나다의 계좌 1111에는 100원이 있다.
가나다의 나이는 25살이고 키는 175.300000 입니다.
가나다의 나이는 25살이고 키는 175.3 입니다.
가나다의 나이는         25살이고 키는 175.3 입니다.
가나다의 나이는 25        살이고 키는 175.3 입니다.
       가나다의 나이는 25        살이고 키는 175.3 입니다.
가나다       의 나이는 25살이고 키는 175.3 입니다.

 

# format 함수를 이용한 포매팅
#가나다의 계좌 1111에는 100원이 있다.
name='가나다'
account='1111'
money=100
print("%s의 계좌 %s에는 %d원이 있다."%(name,account,money))
print("{1}의 계좌 {0}에는 {2}원이 있다.".format(account,name,money))

###가나다의 나이는 25살이고 키는 175.3 입니다.
age=25
height=175.3
a="{0}의 나이는 {a}살이고 키는 {h} 입니다."\
            .format(name,a=age,h=height)
print(a)
가나다의 계좌 1111에는 100원이 있다.
가나다의 계좌 1111에는 100원이 있다.
가나다의 나이는 25살이고 키는 175.3 입니다.

 

#가나다의 계좌 1111에는 100원이 있다.
a=f"{name}의 계좌 {account}에는 {money}원이 있다."
print(a)
가나다의 계좌 1111에는 100원이 있다.

 

#문자열을 가공하기 위한 문자열 함수
a='Life is too short, You need python'
print(a.count('o'))
print(a.find('n'))
print(a[a.find('n') : a.find('n')+4])
print(a[23 : 23+4])
print(a.find('need'))
print(a.find('s',7))
print(a.find('x')) # -1
print(a.index('n'))
print(a.index('need'))
print(a.index('s',7))
#print(a.index('x')) #실행 오류
print(a.rindex('n'))
print(a.rfind('n'))
5
23
need
need
23
12
-1
23
23
12
33
33

 

print(a)
print(a.lower())
print(a.upper())
l=a.split() # 공백문자가 구분문자
print(l) # 리스트로 반환
s="Life:is:too:short,:You:need:python"
l=s.split(":") # : 이 구분문자임
print(l)
print("abcd")
s="  ab cd  "
print(s)
print(s.strip())
print(s.rstrip())
print(s.lstrip())
s="abcabdab"
print(s.strip("ab"))
a='Life is too short, You need python'
print(a) # Your leg is too short, You need python
print(a.replace("Life","Your leg"))
digit="0101237890"
print(digit.isdigit()) # True
digit="010-123-7890"
print(digit.isdigit())
alpha="abcd"
print(alpha.isalpha()) # True
alpha="ab cd"
print(alpha.isalpha()) # False
print(a.islower())
print(a.isupper())
Life is too short, You need python
life is too short, you need python
LIFE IS TOO SHORT, YOU NEED PYTHON
['Life', 'is', 'too', 'short,', 'You', 'need', 'python']
['Life', 'is', 'too', 'short,', 'You', 'need', 'python']
abcd
  ab cd  
ab cd
  ab cd
ab cd  
cabd
Life is too short, You need python
Your leg is too short, You need python
True
False
True
False
False
False

 

# 숫자 리터럴 : 정수, 실수:10
# 문자열 리터럴 : "a",'a','''a''',"""a""","10", a:변수 : 영어, 한국어, 중국어
# 리스트 자료형 : []
l=["가나다","라마바"] # 문자열이 있는 리스트
print(l)
# 각각의 자료형 확인
i=10
str1="가나다"
print(type(i))
print(type(str1))
print(type(l))
l=["가나다",100,10.5] #혼합형 리스트
print(l)
['가나다', '라마바']
<class 'int'>
<class 'str'>
<class 'list'>
['가나다', 100, 10.5]

 

a=["가나다",35,175.5,[1,2,3]] # 리스트를 포함한 혼합형 리스트
print(a)
a=[[1,2,3],[4,5,6]] # 리스트를 포함한 리스트
print(a)
a=[] # 빈 리스트
print(a)
a="Life:is:too:short"
c=a.split(":")
print(c)
['가나다', 35, 175.5, [1, 2, 3]]
[[1, 2, 3], [4, 5, 6]]
[]
['Life', 'is', 'too', 'short']

 

a="Life is too short"
#  01234567890123456
#            1
print(a)
print(a[8])
l=['Life','is','too','short']
#    0      1    2      3
#    4      3    2      1      -
print(l[2])
s=l[2]
print(type(s)) # 문자열 :too
#                        123
print(l[2][1])
print(l[1]+l[2]) # 'is'+'too'
print(l[-2])
Life is too short
t
too
<class 'str'>
o
istoo
too

 

a=[1,2,3,['a','b','c']]
#  0 1 2       3
#          0   1   2
print(a[3][1])
b

 

a="Life is too short"
#  01234567890123456
print(a[8:8+3]) # slicing
l=["Life","is","too","short"]
#    0     1     2      3
#    4     3     2      1   -
print(l[1:1+2])
print(l[-3:-3+1])
print(l[1])
l[0]="Your leg"
print(l)
too
['is', 'too']
['is']
is
['Your leg', 'is', 'too', 'short']

 

# 리스트 함수
l=["Life","is","too","short"]
del l[2] # ['Life', 'is', 'short']
print(l)
del l[0:0+2]
print(l)
['Life', 'is', 'short']
['short']

 

l=["Life","is","too","short"]
del l[1:]
print(l)
l.append('is')
print(l)
l.append('too')
print(l)
l.append('short')
print(l)
['Life']
['Life', 'is']
['Life', 'is', 'too']
['Life', 'is', 'too', 'short']

 

a=[1,4,2,3]
# 데이터를 정렬
a.sort() # 실제 대이터가 변경이 됨
print(a)
a=[1,4,2,3]
a.reverse()
print(a)
print(a.index(3))
#print(a.find(3))
print(a)
a.insert(2,6)
print(a)
a.remove(4)
print(a)
a.append(6)
print(a)
a.remove(6)
print(a)
a.append(6)
print(a)
print(a.count(6))
[1, 2, 3, 4]
[3, 2, 4, 1]
0
[3, 2, 4, 1]
[3, 2, 6, 4, 1]
[3, 2, 6, 1]
[3, 2, 6, 1, 6]
[3, 2, 1, 6]
[3, 2, 1, 6, 6]
2

 

a=[1,4,2,5,4,3]
a.sort(reverse=True)
print(a)
a=[1,2,3]
b=[4,5,6]
c=a+b
print(c)
print(a*3)
a.extend([8,9,7])
print(a)
[5, 4, 4, 3, 2, 1]
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 1, 2, 3, 1, 2, 3]
[1, 2, 3, 8, 9, 7]

 

a=[1,4,2,5,4,3]
# 크기
print(len(a))
# 삭제
del a[1]
a.remove(4)
a.pop()
a.pop(2)
# 추가 및 삽입 그리고 확장
a.append(4)
a.insert(3,6)
a.extend([4,5,6])
# 정렬
a.sort()
a.reverse()
a.sort(reverse=True)
print(a)
c=['Life','is','too','short']
d=" ".join(c) # 리스트를 문자열로 변화
print(d)
# 요소 번호 찾기
print(a.index(5))
6
[6, 6, 5, 4, 4, 2, 1]
Life is too short
2

 

# 숫자 자료형 : 10, 10.5
# 문자 자료형 : '',"","""""",''''''
# 리스트 자료형 : []
# 튜플 자료형 : ()
l = [1,2,3,4]
t = (1,2,3,4)
t1=("가나다",12,[1,2,3],(4,5,6))
#      0      1    2       3
print(t1[2])
print(t1.index(12))
l[1]=10
print(l)
#t[1]=10 # 튜플은 요소를 변경하지 못함
print(len(t))
# indexing, slicing
[1, 2, 3]
1
[1, 10, 3, 4]
4

 

l=[]
t=()
l1=[1]
t1=(1,) #
l2=[1,2]
t2=(1,2)
print(t1)
print( (4)*5  )
(1,)
20

 

### 딕셔너리 : 키와 값이 하나의 쌍으로 되어 있는 것을 딕셔너리라고 한다.
### {Key1:Value1, Key2:Value2, Key3:Value3, ...}
### html : json 자료형과 같다.
name='가나다'
age=35
height=170.4
dic={'name':'가나다','age':35,'height':174.6}
# 딕셔너리는 index가 없다
print(dic['name'])
print(dic['age'])
dic['name']='홍길동'
print(dic)
l=[1,2,3,4]
#  0 1 2 3
l[3]=10
print(l)
#l[4]=20
dic['add']='서울' # 키가 없으면 추가
print(dic)
d={1:'이',1:'박'} # 키의 중복을 허용하지 않는다.
print(d)
가나다
35
{'name': '홍길동', 'age': 35, 'height': 174.6}
[1, 2, 3, 10]
{'name': '홍길동', 'age': 35, 'height': 174.6, 'add': '서울'}
{1: '박'}

 

dic={'name': '홍길동', 'age': 35, 'height': 174.6, 'add': '서울'}
print(dic)
del dic['add']
print(dic)
{'name': '홍길동', 'age': 35, 'height': 174.6, 'add': '서울'}
{'name': '홍길동', 'age': 35, 'height': 174.6}

 

dic={'name': 'pey', 'phone': '01088889999', 'birth': '19991118'}
#pey라는 사람의 년도,월,일을 따로 출력
print(dic['birth'])
print(dic['birth'][:4])
print(dic['birth'][4:6])
print(dic['birth'][6:])
print(dic.keys())
print(dic.values())
print(dic.items())
print(dic['name'])
print(dic.get('name'))
#print(dic.get['money'])
print(dic.get('money'))
19991118
1999
11
18
dict_keys(['name', 'phone', 'birth'])
dict_values(['pey', '01088889999', '19991118'])
dict_items([('name', 'pey'), ('phone', '01088889999'), ('birth', '19991118')])
pey
pey
None

 

dic1={'classic':500, "pop":600}
dic2={'classic':500, "pop":600, "money":100}
print(dic1['classic']+dic2['classic'])
#print(dic1['money']+dic2['money'])
print(dic1.get('money',0)+dic2.get('money',0))
1000
100

 

# 부울 타입 / True | False
a=True # 참
b=False # 거짓
i=10
s1="10"
c="True"
dic={'name':'가나다','age':35,'height':174.6}
print(type(a))
print(type(b))
print(type(s))
print(type(dic))
<class 'bool'>
<class 'bool'>
<class 'str'>
<class 'dict'>

 

x=10;y=20
a=x<y
print(a)
# 비교 연산자의 결과 값은 부울 타입
a=x>y
print(a)

z=30
# 부울과 부울 끼리의 연산 : 논리 연산자
a = x>y or x<z
print(a)
True
False
True

 

print(bool("가나다"))
print(bool(""))
print(bool([1,2,3,4]))
print(bool([]))
print(bool((1,2,3,4)))
print(bool())

print(bool(0))
print(bool(-1))
print(bool(1))
print(bool(None))
print(bool({}))
True
False
True
False
True
False
False
True
True
False
False

 

### 2200년은 윤년일까요(True)? 평년일까요(False)?
### 4년마다 윤년이지만 100년마다는 윤년이 아니다 그렇지만 400년마다는 윤년이다.
a=2200%4==0 and 2200%100 !=0 or 2200 %400==0
print(a)

if 2200%4==0 and 2200%100 !=0 or 2200 %400==0:
    print("윤년")
else:
    print("평년")
False
평년

 

### 파이썬 변수 선언법
a=b=c=0
print(a,b,c)
a,b='python','life'
print(a,b)
a,b=('python','life')
print(a,b)
(a,b)='python','life'
print(a,b)
(a,b)=('python','life')
print(a,b)
(a,b)=([1,2,3,4],'life')
print(a,b)
(a,b)=[[1,2,3,4],'life']
print(a,b)
0 0 0
python life
python life
python life
python life
[1, 2, 3, 4] life
[1, 2, 3, 4] life

 

a=3
b=4

a,b=b,a
print(a,b)
4 3

파이썬 자료형에는
숫자, 문자열, 리스트, 튜플, 딕셔너리, 부울, 집합

# 제어문
### bool 타입을 이용해서 원하는 결과를 얻어 오는 것을 말한다.
## 조건문 : 여러개의 명령문 중 하나를 선택하는 것
## 조건식을 사용한다.
## 조건식 뒤에는 ":"를 꼭 적어준다.
## 조건식에 맞는 명령문이 실행되기 위해서는 들여쓰기가 되어야한다.
### 들여쓰기할 때는 주로 탭을 많이 사용한다.
# 단일 조건문
'''
if 조건식 :
    명령어1
    명령어2
    ...
명령어
'''

#2900원 이상 돈이 있으면 버스를 타고 가세요.
money=3000
if money >= 2900:
    print("버스를 타고 가세요")
print("명령문 끝")
버스를 타고 가세요
명령문 끝

 

money=2800
if money >= 2900:
    print("버스를 타고 가세요")
print("명령문 끝")
명령문 끝

 

#if ~ else
money=2800
if money >= 2900:
    print("버스를 타고 가세요")
else:
    print("걸어가시오.")
print("명령문 끝")
걸어가시오.
명령문 끝

 

x=10;y=20
print(x==y)
print(x>y)
print(x<y)
print(x>=y)
print(x<=y)
print(x!=y)
if x>y:
    print("x가 y보다 크다")
else:
    print("x가 y보다 작다")
False
False
True
False
True
True
x가 y보다 작다

 

a=4 in [1,2,3,4,5] #bool type
print(a)
if 4 in [1,2,3,4,5]:
    print("리스트안에는 4가 있습니다")
else:
    print("리스트안에는 4가 없습니다")
True
리스트안에는 4가 있습니다

 

a=7 in [1,2,3,4,5] #bool type
print(a)
a=7 not in [1,2,3,4,5]
print(a)

if 7 not in [1,2,3,4,5]: # not True : False, not False : True
    print("7이 없습니다")
else:
    print("7이 있습니다.")
    
print('j' in "python")
print('j' not in "python")
False
True
7이 없습니다
False
True

 

# score가 90이상이면 A, 80이상이면 B, 70이상이면 C, 60이상이면 D,
# 그렇지 않으면 F

score=78
if score >=90:
    print('A')
elif score>=80:
    print('B')
elif score>=70:
    print('C')
elif score>=60:
    print('D')  
else:
    print("F")
C

 

# score가 90이상이면 A, 80이상이면 B, 70이상이면 C, 60이상이면 D,
# score가 95이상이면 A+, 85이상이면 B+, 75이상이면 C+, 65이상이면 D+,
# 그렇지 않으면 F

score=78
if score >=90:
    if score>=95:
        print('A+')
    else:
        print('A')
elif score>=80:
    if score>=85:
        print('B+')
    else:
        print('B')
elif score>=70:
    if score>=75:
        print('C+')
    else:
        print('C')
elif score>=60:
    if score>=65:
        print('D+')
    else:
        print('D')
else:
    print("F")
C+

 

if score>=60:
    message='success'
else:
    message='failure'
print(message)
success

 

message='success' if score>=60 else 'failure'
print(message)
success

 

a=10; b=20; opt='add'
if opt=="add":
    result=a+b
elif opt=="sub":
    result=a-b
elif opt == "mul":
    result=a*b;
else:
    result=a/b
print(result)
30

 

if opt=="add":
    result=a+b
else:
    if opt=="sub":
        result=a-b
    else:
        if opt=="mul":
            result=a*b
        else:
            result=a/b
print(result)
30

 

result=a+b if opt=="add" else (a-b if opt=="sub" 
                          else(a*b if opt=="mul" else a/b) )
print(result)
30

'파이썬[python]' 카테고리의 다른 글

파이썬 강좌 4  (0) 2022.05.13
파이썬 강좌 3  (0) 2022.05.12
파이썬 오프라인  (0) 2022.05.11
파이썬 강좌 2  (0) 2022.05.11
파이썬 강좌 1 (설치)  (0) 2022.05.09
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함