개발/python

python 기본 문법

희운1205 2024. 5. 23. 10:17
반응형

python 이란?

1990년에 귀도반 로섬이라는 네덜란드 개발자가 만든  동적으로 작동되는 대화형 프로그래밍 언어입니다.

이 언어의 주요 특징으로 들여쓰기를 통해 블록을 구분하여 코드를 작성하도록 하는 것입니다.

주요 기본 문법

1. 변수와 자료형

1) 변수선언 

# 변수 선언
a = 1         # 정수형
b = 3.14      # 실수형
c = "Hello"   # 문자열
d = True      # boolean형

# 자료형 확인
print(type(a))  # <class 'int'>
print(type(b))  # <class 'float'>
print(type(c))  # <class 'str'>
print(type(d))  # <class 'bool'>

2. 연산자

 

x = 5
y = 3

print(x + y)  # 8
print(x - y)  #  2
print(x * y)  # 15
print(x / y)  # 1.666..
print(x // y) # 1
print(x % y)  # 2
print(x ** y) # 125

print(x == y)  # False
print(x != y)  # True
print(x > y)   # True
print(x < y)   # False
print(x >= y)  # True
print(x <= y)  # False

a = True
b = False

print(a and b)  # False
print(a or b)   # True
print(not a)    # False


3. 조건문

age = 10

if age >= 18:
    print("성인.")
elif age >= 13:
    print("청소년.")
else:
    print("어린이.")


4. 반복문

# for 문
for i in range(5):
    print(i)  # 0 1 2 3 4

# while 문
count = 0
while count < 5:
    print(count) # 0 1 2 3 4
    count += 1


5. 리스트와 튜플

#리스트문

fruits = ["apple", "banana", "cherry"]
print(fruits[0])  # apple
fruits.append("date")
print(fruits)     # ['apple', 'banana', 'cherry', 'date']

# 튜플문
dimensions = (1920, 1080)

print(dimensions[0])  # 1920
# dimensions.append(720)  # 오류: 튜플은 변경 불가능


6. 딕셔너리

student = {
    "name": "John",
    "age": 20,
    "major": "Computer Science"
}

print(student["name"])  # John
student["age"] = 21
print(student)  # {'name': 'John', 'age': 21, 'major': 'Computer Science'}


7. 함수

def greet(name):
    return f"Hello, {name}!"

print(greet("Alice"))  # Hello, Alice!


8. 클래스

class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def bark(self):
        return f"{self.name} says woof!"

my_dog = Dog("Rex", 2)
print(my_dog.bark())  # Rex says woof!
반응형