comnic's Dev&Life

[Python] 3. 기본 문법 본문

Python

[Python] 3. 기본 문법

comnic 2024. 1. 12. 15:04
반응형

3. Python 기본 문법

 

3.1 변수와 데이터 타입

- 변수의 선언과 활용

# 변수 선언
name = "John"
age = 25

# 변수 활용
print(f"My name is {name} and I am {age} years old.")

 

- 기본 데이터 타입 (int, float, str, bool)

# 정수형 (int)
age = 25

# 부동소수점형 (float)
height = 175.5

# 문자열 (str)
name = "Alice"

# 불리언 (bool)
is_adult = True

 

- 리스트, 튜플, 딕셔너리, 집합 등의 자료구조

# 리스트 (list)
numbers = [1, 2, 3, 4, 5]

# 튜플 (tuple)
coordinates = (10, 20)

# 딕셔너리 (dictionary)
person = {"name": "Alice", "age": 30}

# 집합 (set)
fruits = {"apple", "banana", "orange"}

 

 

3.2 제어문

- 조건문 (if, elif, else)

# 조건문
age = 18
if age < 18:
    print("You are a minor.")
elif 18 <= age < 65:
    print("You are an adult.")
else:
    print("You are a senior citizen.")

 

- 반복문 (for, while)

# for 반복문
numbers = [1, 2, 3, 4, 5]
for num in numbers:
    print(num)

# while 반복문
count = 0
while count < 5:
    print(count)
    count += 1

 

 

3.3 함수

- 함수의 정의와 활용

# 함수 정의
def greet(name):
    return f"Hello, {name}!"

# 함수 호출
result = greet("Alice")
print(result)

 

- 매개변수와 반환값

# 매개변수와 반환값
def add_numbers(a, b):
    return a + b

result = add_numbers(3, 5)
print(result)

 

- 내장 함수 및 라이브러리 함수 활용

# 내장 함수
num_list = [4, 2, 8, 1, 6]
print(len(num_list))          # 리스트의 길이
print(sorted(num_list))       # 리스트 정렬

# 라이브러리 함수
import math
print(math.sqrt(25))          # 제곱근 계산

 

 

반응형

'Python' 카테고리의 다른 글

[Python] 4. NumPy와 Pandas  (0) 2024.01.12
[Python] 2. 개발환경 설정  (0) 2024.01.12
[Python] 1. Python 소개 및 장단점  (0) 2024.01.10
Comments