print(say.center(10))     
# 숫자만큼 자릿수를 잡은 후, 문자열을 가운데 배치

print(say.center(10, "#"))
# 숫자만큼 자릿수를 잡은 후, 문자열을 가운데 배치
# 문자열을 제외한 다른 자리에는 #으로 채우기

print(say.ljust(10))
# 숫자만큼 자릿수를 잡은 후, 왼쪽에 붙여 출력
print(say.rjust(10))
# 숫자만큼 자릿수를 잡은 후, 오른쪽에 붙여 출력

print(say.zfill(10))
# 오른쪽으로 붙여쓰고 왼쪽 빈 공간은 0으로 채움.

 

set 자료형

> 중복 허용 X

> 입력된 순서는 중요하지 않음.

> set( ) 생성자 함수를 통해 만듦.

> { } 를 이용해서 만들 수 있음. (딕셔너리와 같은 중괄호 사용, 구분 유의)

> add, update, remove, copy, clear method 사용 가능

> 사용예시

> 집합연산과 세트함수

> 여러 자료형 저장이 가능하지만, 중복은 허용 안함.

> set에는 순서가 없기 때문에 index 사용 못 함. 

> 사용예시 2

 

a_list = ["A", "B", "C", "D", "E"]
a_list = list("ABCDE")              # 둘 다 똑같은 리스트

n_list = [65, 66, 67, 68, 69, 70]
n_list = [ascii for ascii in range(65,71)] # 이 방법 중요 

z_list = list(zip(a_list, n_list))
print(z_list)

# zip함수 : 동일한 개수로 이루어진 자료형을 튜플로 묶어줌.

## 결과: [('A', 65), ('B', 66), ('C', 67), ('D', 68), ('E', 69)]

 

 

enumerate 사용 X

x_list = [54, 50, 71, 58, 59]
index = 0

for item in x_list:
    print(f"[{index: 2d}] {item} ", end ='')
    index += 1

 

enumerate 사용 O

for index, item in enumerate(x_list):
    print(f"[{index: 2d}] {item} ", end = '')
# 인덱스 시작 번호 지정 가능

for index, item in enumerate(x_list, start = 1):
    print(f"[{index: 2d}] {item} ", end = '')

 

# 비트 논리곱(&) 연산자

# A B    A&B
# 0 0    0
# 0 1    0
# 1 0    0
# 1 1    1      >>> 0011 => 3  / 0101 => 5
5 & 3  ##결과 : 1

 

# 비트 논리합(|) 연산자

# A B    A&B
# 0 0    0
# 0 1    1
# 1 0    1
# 1 1    1
3 | 5  ## 7

 

# 비트 배타적 논리합(^) 연산자

# A B    A&B
# 0 0    0
# 0 1    1
# 1 0    1
# 1 1    0     >>> 두 값이 같으면 0, 다르면 1
5 ^ 3 ## 6

 

# 왼쪽 시프트(<<) 연산자

# 00011010 = 26
# 01101000 = 104  앞의 두 비트(00)는 사라짐. 뒤의 두 비트는 0으로 채움.
# 왼쪽으로 시프트할 때마다 2^n을 곱한 효과가 나타남.
ex = 10
expr = f"{ex << 1} {ex << 2} {ex << 3} {ex << 4}"
print(expr)

 

# 오른쪽 시프트(>>) 연산자

# 00011010 = 26
# 00000110 = 6   앞의 두 비트는 부호 비트(0)으로 채우고 뒤의 두 비트는 사라짐.
# 오른쪽으로 시프트할 때마다 2^n으로 나눈 효과
# 시프트 연산은 정수만 연산하므로 몫만 남음. (26/2^2 = 6)
ex2 = 10
expr2 = f"{ex >> 1} {ex >> 2} {ex >> 3} {ex >> 4}" 
print(expr2)

 

# 보수(~) 연산자

# 두 수에 대해 연산하는 것이 아니라, 각 비트를 반대로 만드는 연산자

# 1의 보수
# 0 >> 1 
# 1 >> 0
# 0111 1000 >> (1의 보수) = 1000 0111
a = 12345
~a   # -12346


# 2의 보수
# 1의 보수 + 1 = 2의 보수
# 0111 1000 >> 2의 보수
# = 1의 보수 + 1
# = 1000 0111 + 1
# = 1000 1000
a = 12345
~a + 1 # -12345

'프로그래밍 > Python' 카테고리의 다른 글

Python 문자열 정렬, set  (0) 2023.10.08
Python zip, enumerate 함수 사용  (2) 2023.10.08
파이썬 매개변수 기본값 설정  (0) 2023.10.06
Anaconda 기반의 Python 개발환경 구축  (0) 2023.04.25
파이썬 (~while)  (0) 2023.04.25
def f_01(x, y, z = 0):   
# 기본값 설정은 항상 기본값이 설정되지 않은 매개변수 뒤에 와야함. (위반 시 오류 발생)
	return x + y + z 
    
s = f_01(20, 30)
print("func_01(10,20) 호출 후 반환 값:", s) #이러면 50이 출력됨.

s = func_01(20, 30, 50)
print("func_01(10, 20, 30) 호출 후 반환 값:", s) #이러면 100이 출력됨.

함수 선언 시 매개변수의 기본값을 설정해두면, 

함수 사용 시 해당 매개변수 생략 가능 

기본값이 정해져 있지 않은 매개변수는 반드시 값을 전달해줘야 함. 

'프로그래밍 > Python' 카테고리의 다른 글

Python 문자열 정렬, set  (0) 2023.10.08
Python zip, enumerate 함수 사용  (2) 2023.10.08
Python 비트 연산자 정리  (0) 2023.10.07
Anaconda 기반의 Python 개발환경 구축  (0) 2023.04.25
파이썬 (~while)  (0) 2023.04.25

Anaconda(Miniconda) 플랫폼 : 다양한 데이터 분석 패키지를 지원하는 플랫폼

Jupyter Notebook : 웹 브라우저 기반 코딩 결과를 빠르게 확인할 수 있는 에디터

 

conda create -n (자기가 하고 싶은 이름) python=3.7

이런 식으로 가상환경 설치해줌.

 

가상환경을 활성화 시키기 

conda activate (자기가 하고 싶은 이름)

 

가상환경을 비활성화 시키기

conda deactivate 

 

필요한 거 설치

pip install numpy

pip install pandas matplotlib jupyter notebook

밑줄 친 부분은 꼭 가상환경에서 설치해야함.

 

 

'프로그래밍 > Python' 카테고리의 다른 글

Python 문자열 정렬, set  (0) 2023.10.08
Python zip, enumerate 함수 사용  (2) 2023.10.08
Python 비트 연산자 정리  (0) 2023.10.07
파이썬 매개변수 기본값 설정  (0) 2023.10.06
파이썬 (~while)  (0) 2023.04.25
# 대화창 만들기
"""
print("안녕하세요?")
name = input("이름을 말해주세요. ")
age = input("나이는 어떻게 되시나요? ")
print()

print("입력하신 정보는 \n이름은 {}, 나이는 {}입니다." .format(name, age))
print()

reply = input("맞으면 '예', 틀리면 '아니오'라고 입력해주세요. ")

if reply == "예":
    print("반갑습니다. {}씨 !!".format(name))
else :
    print('잘못된 정보입니다. ')
"""

# 온도 계산기
"""
celsius = int(input("섭씨 온도를 입력하세요 : "))
fahrenheit = (9/5) * celsius + 32

print("섭씨 {}도는 화씨 {:.0f}도입니다.".format(celsius, fahrenheit))
"""

# 몫과 나머지 계산
"""
print("두 개의 정수를 입력하세요.")

a = int(input())
b = int(input())

print("{} / {} 의 몫은 {}".format(a,b,a//b))
print("{} / {} 의 나머지는 {}".format(a,b,a%b))
"""

# 소금물의 농도 구하기
"""
print("소금물의 농도를 구하는 프로그램입니다.")

salt = float(input("소금의 양은 몇 g입니까? "))
water = float(input("물의 양은 몇 g입니까? "))

concentration = salt / (salt + water) * 100

print("소금물의 농도: {}".format(concentration))
"""

# BMI 구하기
"""
print("BMI를 구하는 프로그램입니다.")

a = input(" 계속하려면 아무키나 누르세요...")

height = float(input("키(cm) : "))
weight = float(input("몸무게(kg) : "))

BMI = weight/(height*0.01)**2

print("당신의 BMI : {:.2f}".format(BMI))
"""

# 성적처리 결과 출력하기
"""
name = input()
kor, math, music = int(input()),int(input()),int(input())
avg = (kor + math + music) / 3

print('\n"%s"님 성적 처리 결과입니다' % name)
print('-' * 30)
print('%s\t%s\t%s'%(" 과목","점수", "평균과의 차이"))
print('-' * 30)
print('국어 :{}  {:+5.1f}'.format(kor,kor-avg))
print('수학 :{}  {:5.1f}'.format(math,math-avg))
print('음악 :{}  {:5.1f}'.format(music,music-avg))
print('-' * 30)
print('평균 >> %5.1f' % avg)
"""

# 다항함수의 결과를 구하는 프로그램
"""
x, fx = 0, 0

x = int(input("x의 값을 입력하세요 : "))

fx = x**5-4*x**2-2*x+1/13
print("f({}) = {:.2f}".format(x, fx))
"""

# 동전 교환 프로그램
"""
w500, w100, w50, w10 = 0, 0, 0, 0

money = int(input("교환할 돈은 얼마?"))

w500 = money // 500
w100 = (money - 500*w500) // 100
w50 = (money - 500*w500 - 100*w100) // 50
w10 = (money - 500*w500 - 100*w100 - 50*w50) // 10
a = money % 10

print("500원의 개수: {}개\n100원의 개수: {}개\n50원의 개수: {}개\n10원의 개수: {}개\n바꾸지 못한 잔돈: {}원".format(w500,w100,w50,w10,a))
"""

# 윤년 계산 프로그램
"""
year = int(input("연도를 입력하세요 : "))

if year % 4 == 0 and year % 100 != 0:
    print("{}년은 윤년입니다.".format(year))

elif year % 400 == 0:
    print("{}년은 윤년입니다.".format(year))

else:
    print("{}년은 윤년이 아닙니다.".format(year))
"""

# 간단한 산술 계산기 프로그램
"""
x, y, op = 0, 0, ''

x = int(input("첫 번째 수를 입력하세요: "))
op = input("계산할 연산자를 입력하세요: ")
y = int(input("두 번째 수를 입력하세요: "))

if op == "+":
    total = x + y
    print("{} {} {} = {} 입니다.".format(x,op,y,total))

elif op == "-":
    total = x - y
    print("{} {} {} = {} 입니다.".format(x,op,y,total))

elif op == "*":
    total = x * y
    print("{} {} {} = {} 입니다.".format(x,op,y,total))

elif op == "/":
    total = x / y
    print("{} {} {} = {:.2f} 입니다.".format(x,op,y,total))
    
elif op == "%":
    total = x % y
    print("{} {} {} = {} 입니다.".format(x,op,y,total))

elif op == "//":
    total = x // y
    print("{} {} {} = {} 입니다.".format(x,op,y,total))

elif op == "**":
    total = x ** y
    print("{} {} {} = {} 입니다.".format(x,op,y,total))

else:
    print("알 수 없는 연산자입니다.")
"""

# 두 점 사이의 거리 구하기
"""
x1 = int(input("x1:"))
y1 = int(input("y1:"))
x2 = int(input("x2:"))
y2 = int(input("y2:"))

distance = ((x1-x2)**2 + (y1-y2)**2)**0.5

print("두 점 사이의 거리= {:.2f}".format(distance))
"""

# 놀이공원 입장료 구하기
"""
fee = 30000
age = int(input("나이 입력: "))

if age < 8:
    print("입장료는 무료입니다.")

elif age < 15 and age >= 8:
    print("입장료는 {}원입니다.".format(int(fee-fee*0.2)))

elif age >= 65:
    print("입장료는 {}원입니다.".format(int(fee-fee*0.5)))

else:
    print("입장료는 {}원입니다.".format(fee))
"""

# 합격 또는 불합격 표현하기
"""
first, second, interview, avg = 0, 0, 0, 0

first = int(input('1차 점수는?'))
second = int(input('2차 점수는?'))
interview = int(input('면접 점수는?'))

avg = (first + second + interview) / 3

if avg >= 80 and first >= 60 and second >= 60 and interview >= 60:
    print("축하합니다. 합격입니다.")

else:
    print('불합격입니다.')
"""

# 계절 출력하기
"""
month, season = 0, ''
month = int(input("월 입력 : "))

if month >= 3 or month <= 5:
    season = '봄'

elif month >= 6 or month <= 8:
    season = '여름'

elif month >= 9 or month <= 11:
    season = '가을'
    
elif month == 12 or month == 1 or month == 2:
    season = '겨울'

else:
    print("잘못된 월입니다.")

if month >= 1 and month < 12:
    print("{}월은 {}입니다.".format(month,season))
"""

# 자연수에서 n의 배수 출력하기
"""
cnt = 0
n = 1

while n < 100:
    if n % 7 == 0:
        print("%2d"%n, end = " ")
        n = n + 1
        cnt = cnt + 1
        if cnt % 5 == 0:
            print()

    else:
        n = n + 1
        pass

print("\n")
print("100 미만의 7의 배수는 {}개".format(cnt))
"""

# 조건이 참인 동안 반복하기
"""
count, height = 0, 0

while count != 10:
    height = float(input("키는? "))

    if height >= 140:
        count = count + 1
        print("Yes~")

    else:
        print("No~")

print("Go~ 출발합니다!")
"""

 

+ Recent posts