파이썬 문법
이 글은 파이썬 문법에 대해 설명합니다.
YouTube Video
파이썬 문법
들여쓰기
파이썬은 들여쓰기를 사용하여 코드 블록을 정의합니다. 코드 블록을 정의하는 데 중괄호 {}
를 사용하는 많은 다른 언어와 달리, 파이썬은 들여쓰기를 사용합니다. 일반적으로 네 칸의 공백으로 들여쓰기를 하지만, 탭을 사용할 수도 있습니다. 다만, 한 파일 안에서는 공백과 탭을 섞어 사용하지 않도록 주의해야 합니다.
1x = 5
2if x > 0:
3 print("Positive")
4else:
5 print("Non-positive")
주석
한 줄 주석
파이썬에서 주석은 #
으로 시작합니다. 한 줄의 끝까지 모든 내용이 주석으로 처리됩니다.
1# This is a comment
2print("Hello, World!") # This is also a comment
문서 문자열(Docstring
)
docstring
은 코드를 설명하는 데 사용되는 문자열로, 세 개의 큰따옴표 """
또는 세 개의 작은따옴표 '''
로 둘러싸입니다. 주로 모듈, 클래스, 함수 등을 설명하는 데 사용됩니다.
1def greet(name):
2 """
3 This function displays a greeting to the specified name.
4
5 Parameters:
6 name (str): The name of the person to greet.
7 """
8 print(f"Hello, {name}!")
help()
함수를 사용하여 Docstring
을 볼 수 있습니다.
1help(greet)
주석 작성에 대한 모범 사례
주석 작성의 모범 사례는 다음과 같은 점들을 포함합니다:.
1# Good example
2# Validate user input and display a personalized message
3
4# Ask for the user's name
5name = input("Enter your name: ")
6
7# Ask for the user's age and convert it to an integer
8age = int(input("Enter your age: "))
9
10# Check eligibility based on age
11if age >= 18:
12 # Inform the user that they can register
13 print(f"Welcome, {name}! You are eligible to register.")
14else:
15 # Inform the user that they are underage
16 print(f"Sorry, {name}. You must be at least 18 years old to register.")
17
18# Bad example
19# Store the user's name in the variable 'name'
20name = input("Enter your name: ")
21
22# Convert the input to an integer and store it in 'age'
23age = int(input("Enter your age: "))
24
25# Check if the user is greater than or equal to 18
26if age >= 18:
27 # Print a welcome message
28 print(f"Welcome, {name}! You are eligible to register.")
29else:
30 # Print a rejection message
31 print(f"Sorry, {name}. You must be at least 18 years old to register.")
-
명확하고 간결하게 작성하기 주석은 코드의 의도를 명확히 설명하는 데 사용됩니다.
-
코드의 의미를 반복하지 않기 자명한 코드는 주석을 피하십시오.
-
일관성을 유지하기 팀 개발에서는 주석 스타일과 형식을 통일하는 것이 중요합니다.
변수와 데이터 타입
파이썬에서는 변수를 선언할 때 타입을 지정할 필요가 없습니다. 타입은 값을 할당하는 시점에 자동으로 결정됩니다.
1x = 10 # Integer
2y = 3.14 # Floating-point number
3name = "Alice" # String (text)
4is_active = True # Boolean value (True or False)
조건문
조건문은 if
, elif
(else if), 그리고 else
를 사용합니다.
1x = 0
2if x > 0:
3 print("Positive")
4elif x == 0:
5 print("Zero")
6else:
7 print("Negative")
반복문
파이썬은 for
반복문과 while
반복문을 제공하며, 각각 다른 방식으로 사용됩니다.
for
문
for
문은 일반적으로 리스트나 튜플의 요소를 순회(iterate)하는 데 사용됩니다.
1fruits = ["apple", "banana", "cherry"]
2for fruit in fruits:
3 print(fruit)
while
문
while
문은 조건이 참인 동안 루프를 반복합니다.
1count = 0
2while count < 5:
3 print(count)
4 count += 1
함수 정의하기
파이썬에서는 def
키워드를 사용하여 함수를 정의합니다.
1def greet(name):
2 print(f"Hello, {name}!")
3
4greet("Alice")
클래스 정의하기
파이썬에서는 class
키워드를 사용하여 클래스를 정의할 수 있으며, 이를 통해 객체 지향 프로그래밍이 가능합니다.
1class Dog:
2 def __init__(self, name):
3 self.name = name
4
5 def bark(self):
6 print("Woof!")
7
8dog = Dog("Fido")
9dog.bark()
모듈과 임포트
Python에서는 import
키워드를 사용하여 모듈을 가져오고 기존 코드를 이용할 수 있습니다.
1# Importing the sqrt function from the math module
2from math import sqrt
3
4result = sqrt(16)
5print(result) # Output: 4.0
에러와 예외 처리
Python의 try-except
구조는 에러와 예상치 못한 상황을 처리합니다.
1# Catching a division-by-zero error example
2try:
3 result = 10 / 0
4except ZeroDivisionError:
5 print("Cannot divide by zero.")
결론
파이썬의 기본 문법은 매우 간단하고 가독성이 높습니다. 이 기본 요소들은 파이썬 코드를 작성하는 데 필수적인 요소입니다.
위의 기사를 보면서 Visual Studio Code를 사용해 우리 유튜브 채널에서 함께 따라할 수 있습니다. 유튜브 채널도 확인해 주세요.