[Python] 파이썬 기초
Y
Yerim
- Python
name = "Alice"
print(f"Hello, {name}")def great(name: str) -> str:
return f"Hello, {name}"# id, name, emial이 각각 3번씩 반복
# 이러한 현상을 보일러 플레이트(boiler-plate)라고 함
# print를 해도 필드 값이 보이지 않아 불편
class User:
def __init__(self, id, name, email):
self.id = id
self.name = name
self.email = email# id, name, emial이 각각 3번씩 반복
# 이러한 현상을 보일러 플레이트(boiler-plate)라고 함
# print를 해도 필드 값이 보이지 않아 불편
class User:
def __init__(self, id, name, email):
self.id = id
self.name = name
self.email = email
def __repr__(self):
return (f'{self.__class__.__qualname__}{self.id, self.name, self.email}')
user = User(123,'hojun', 'hojun@gmail')
userfrom dataclasses import dataclass
@dataclass
class User:
id: int
name: str
email: str
user = User(123,'hojun', 'hojun@gmail')
user# 기본적인 왈러스 연산자의 사용
x = (n := 10) * 2 # 10을 n에 할당, 그 값을 반환
print(x) # 출력: 20
print(n) # 출력: 10# 왈라스 연산자가 없을 때의 코드
import random
while True:
x = random.randint(0, 10)
if x == 7:
break
print(x)
# 왈라스 연산자를 사용한 코드
import random
while(x := random.randint(0, 10)) != 7:
print(x)def sigma(n):
count = 0
result = 0
while(count := count+ 1) < n + 1:
result += count
return result
if(sum := sigma(100)) ** 5050:
print('5050이 출력되었습니다.')
else:
print('1부터 정수형태로 입력이 가능합니다.')
print(sum * 1000)# 딕셔너리 언패킹 -> 3.5 버전
x = {"key1": "value1"}
y = {"key2": "value2"}
z = {**x, **y}
z# 딕셔너리 병합 -> 3.9 버전
x = {"key1": "value1"}
y = {"key2": "value2"}
z = x | y
zdef add(a, b):
"""Add two numbers and return the result."""
return a + bdef comlex_function(a, b):
"""
Perform a complex operation.
This function does many things, and we need multiple lines to describe it.
"""
passdef add(a, b):
"""
Add two numbers and return the result.
Args:
a (int or float): The first number.
b (int or float): The second number.
Returns:
int or float: The sum of the two numbers.
"""
return a + b> def fetch_smalltable_rows(
table_handle: smalltable.Table,
keys: Sequence[bytes | str],
require_all_keys: bool = False,
) -> Mapping[bytes, tuple[str, ...]]:
"""Fetches rows from a Smalltable.
Retrieves rows pertaining to the given keys from the Table instance
represented by table_handle. String keys will be UTF-8 encoded.
Args:
table_handle: An open smalltable.Table instance.
keys: A sequence of strings representing the key of each table
row to fetch. String keys will be UTF-8 encoded.
require_all_keys: If True only rows with values set for all keys will be
returned.
Returns:
A dict mapping keys to the corresponding table row data
fetched. Each row is represented as a tuple of strings. For
example:
{b'Serak': ('Rigel VII', 'Preparer'),
b'Zim': ('Irk', 'Invader'),
b'Lrrr': ('Omicron Persei 8', 'Emperor')}
Returned keys are always bytes. If a key from the keys argument is
missing from the dictionary, then that row was not found in the
table (and require_all_keys must have been False).
Raises:
IOError: An error occurred accessing the smalltable.
"""