Python, 파이썬 기초 문법

libramin·2022년 9월 1일
0

Python

목록 보기
1/5
post-thumbnail

파이썬 기초 문법

type

a = 'hello'
b = 3.5
c = [1,2,3,4,5]
d = 3==5

print(type(a)) #str
print(type(b)) #float
print(type(c)) #list
print(type(d)) #bool

List

list1 = ['a','b','c']
list2 = [1,2,3,4,5]

print(list1[0]) #a #index
list2.append(6) #[1,2,3,4,5,6] #add
list1.extend(list2) #['a','b','c',1,2,3,4,5,6] #addAll

반복문

for i in range(0,5):
	print(i)
    
# 들여쓰기 주의
# 출력결과 
#0
#1
#2
#3
#4

조건문

if(조건): 들여쓰기+결과 elif(조건): 들여쓰기+결과 else: 들여쓰기+결과

x < y #x가 y보다 작다
x > y #x가 y보다 크다
x == y #x와 y가 같나요?
x != y #x와 y가 다른가요?
x >= y #x와 y보다 크거나 같다
x <= y #x와 y보다 작거나 같다
score = 75

if score >= 90:
  print('학점 A')
elif score >= 80:
  print('학점 B')
else:
  print('학점 C')
  
#결과 '학점 C'

Function

def 함수이름 (인자1, 인자2 ...):
	실행코드
    return 출력값
def volume (width, height, length):
  return width*height*length

volume(2,3,5)
print(type(volume))
#결과 60, function

Class

  • 클래스 생성
class CreateClass:
  pass
# pass: (의도적으로 패스, 무시) 이유: IndentationError 
  • 인스턴스(객체) 생성
test_instance1 = CreateClass()
test_instance2 = CreateClass()
test_instance3 = CreateClass()
  • 클래스 변수, 클래스 함수
class Monster(): #몬스터 클래스 생성
    hp = 100	# hp가 100인 속성
    mp = 10		# mp가 10인 속성

    def damage(self, attack):
        self.hp = self.hp - attack
        #damage라는 기능: 공격받은 만큼 hp가 감소한다.
        
monster1 = Monster()	#몬스터1생성
monster1.damage(120)	#몬스터1.damage: 120공격 받음->hp -20

monster2 = Monster()	#몬스터2생성
monster2.damage(90)		#몬스터1.damage: 120공격 받음->hp 10

Try, Except

예외처리, catch error

a = 10
b = 0

try:
	print(a/b)
except:
	print('0으로는 나눌 수 없어요!')
    
#결과 : 0으로는 나눌 수 없어요!
profile
Hello, I'm libramin!

0개의 댓글