'+++++SW 일일 공부+++++'에 해당되는 글 40건

 ###단축키

import   모듈 호출
math.radians(<각도) 각도  라디안 각도를 변환한다
math.ceil(숫자)   숫자 올림
math.floor(숫자)   숫자 내림
math.pi   3.141592653589793
import 모듈명 as 이름 ...은 모듈을 넣어주고 쓸 이름 정한다 모듈이름을 짧게 만들어준다
form 모듈명 import  사용할모듈   모듈중 호출한거 사용한다
import sys   시작 입력갑 받아오기
from random import ... random, uniform, randrange, choice, choies, sample, shuffle

함수오 값을 가져오기위한 모듈명지정

from datetime import ... datetime, timezone, timedelta 시간 정보 모듈
now.strftime(fmt).format(*"년월일시분초")   시간 정보를 나타냄
__name__    
     

### import

import math

print("math.radians(90) - {0}".format(math.radians(90)))

print("math.ceil(3.2) = {0}"/format(math.ceil(3.2)))

print("math.floor(3.2) = {0}".format(math.floor(3.2)))

print("math.pi = {0}".format(maht.pi))

//math.radian(90) = 1.5707963267948966
//math.ceil(3.2) = 4

### form  ~ import ~

 from math import *
 form math import radians, ceil, floor, pi
 
 print("radians(90) = {0}".format(radians(90)))
 
 print("ceil(3.2) = {0}".format(ceil(3.2)))
 print("floor(3.2) = {0}".format(floor(3.2)))
 
 print("pi = {0}".format(pi))
 

###import  sys

import sys

print("sys.argv => {0} {1}".format(type(sys.argv), sys.argv))

for i, val in enumerate(sys.argv):
	print("sys.argv[{0}] => {1}".format(i,val))

###import random

forma random import random, uniform, randrange, choice, choices, sample, shuffle

print("random() => {0}".format(random()))

print("uniform({0}, {1}) =>{2}".format(1.0, 10.0, unifrom(1.0, 10.0)))
start,stop, step = 1, 45, 2
print("randrange({0}, {1}) => {2}".format(start, stop, randrange(start, stop)))
print("randrange({0}, {1}, {2}) => {3}".format(start, stop, step, randrange(start, stop, step))) //범위 랜덤

data_list = [1, 2, 3, 4, 5]
print("choice({0}) => {1}".format(data_list, choice(data_list))) // 하나선택
print("choice({0}) => {1}".format(data_list, choices(data_list, k=2))) //중복 OK
print("sample({0}) => {1}".format(data_list, sample(data_list, k=2))) // 중복 X

shuffle(data_list) // 섞어서 반환
print("data_list => {0}".format(data_list))

###from datetime import 

from datetime import datetime, timezone, timedelta

now = datetime.now()
print("{0}-{1:02}-{2:02} {3:02}:{4:02}:{5:02}".format(now.year, now.mouth, now.day, now.hour, now.minute, now.second))

fmt = "%Y{0} %m{1} %d{2} %H{3} %M{4} %S{5}"
print(now.strftime(fmt).format(*"년월일시분초"))

##from datetime import datetime

##from pytz import commont_timezones, timezone, utc

form datetime import datetime
from pytz import common_timezones, timezone, utc

for tz in list(common_timezones): //common_timezones 입력값이 있으며 
	if tz.lower().find("paris") >=0: // paris 가있으면 시작 인덱스 값으 반환 없을경우 -1 반환
    	print(tz)
        
tz_utc = timezone(utc.zone)
tz_seoul = timezone("Asia/Seoul")
tz_pacific = timezone("US/Pacific")
tz_paris = timezone("Europe/Paris")


fmt = "%Y-%m-%d %H:%M:%S %Z%z"   /// %Z 객체 나라  %Z UTC시간차이


#UTC 현재 시각
now_utc = datetime.now(tz_utc)
print(now_utc.strftime(fmt))

#Asia/Seoul.strftime(fmt))
now_seoul = now_utc.astimezone(tz_seoul)
print(now_seoul.strftime(fmt))

# US/Pacific 타임존
now_pacific = now_seoul.astimezone(tz_pacific)
print(now_pacific.strftime(fmt))

# Europ/Paris 타임존
now_paris = now_pacific.astimezone(tz_paris)
print(now_paris.strftime(fmt))

 

#__name__

def plus(x, y):
	return x + y
    
    
def minus(x, y):
	return x - y
    
if __name__ == "__main__":
	print("plus(3, 2) => {0}".format(plus(3, 2)))
    print("minus(3, 2) => {0}".format(minus(3, 2)))
    
    
    
    
    //// 아직 잘 모르겟다
    //메인에 서언된 def 에서 이름을 찾으면 실행한다는 건가???

#패키지 사용

from package_mycalc import

op1, op2 = 2, 3

result = module_mycalc_1.plus(op1, op2)
print("plus({0}, {1}) => {2}".format(po1, po2, result))

result = module_mycalc_1.minus(op1, op2)
print("minus({0},[1})=> {2}".format(op1, op2, result))

result = module_mycalc_2.multiply(op1, op2)
print("multiply({0}, {1}) => {2}".format(po1, po2, result))

result = module_mycalc_2.divide(op1, op2)
print("divide({0},[1})=> {2:.2}".format(op1, op2, result))

##로또번호 생성기

import random

lotto = random.sample(range(1, 46, 1), 6)
print(sorted(lotto))   // sorted 오름차순 정열 함수

def imput_start()
	start = 0
    try:
    	start = int(input("로또 번호의 시작 번호를 입력하세요 (기본값: 1): "))
    except:
    	start = 1 
    finally:
    	return start
        
def input_end():
	end = 0
    try:
    	end = int(input("로또 번호의 끝작 번호를 입력하세요 (기본값: 45): "))
    except:
    	end = 45
    finally:
    	return end
        
def input_count():
	count = 0
    try:
    	count = int(input("로또 번호의 시작 번호를 입력하세요 (기본값: 1): "))
    except:
    	count = 6
    finally:
    	return count
        
        
def print_lotto(start, end, count):
	lotto = random.sample(rage(start, end +1, 1), count)
    print("행운의 로또 번호는 ", end="")
    print(sorted(lotto0, end="")
    for i, num in enumerate(sorted(lotto)):
    	if i ==len(lotto) - 1:
        	print("{0} ".format(num), end="")
        else:
        	print({0}, ".format(num), end="")
     
	print("입니다")
    
    

### import lotto

import lotto

start = lotto.input_start()
end = lotto.input_end()
count = lotto.input_count()

lotto.print_lotto(start, end, count)

'+++++SW 일일 공부+++++ > SW Expert Aademy' 카테고리의 다른 글

Python 튜플  (0) 2020.01.28
리스트 조작법  (0) 2020.01.24
Python 구문오류와 예외  (0) 2020.01.11
가변함수에 대하여  (0) 2020.01.11
실행 관련 함수  (0) 2020.01.11
블로그 이미지

Or71nH

,

###단축키

SyntaxError   뭔가 파이썬이 해석못하게 되있다는뜻
IdexError   범위가 넘어간 경우
if 제어 :    
    isdigit()   숫자일 경우 True
try 제어 :   되나안되나 검사
except : 예외처리 안되면 실행
else : 예외발생하지 않았을떄 잘되면 실행
finally : 예외발생과 상관없이 실행 언제나 끝나고 실행
except Exception as ex: 거의 마즈막에씀 예외객체 오류 에 대한 정보를 알려줌
except ValueError as ve: 숫자에러있을때 값이 숫자아니면 에러
except ZeroDivisionError as ze: 분모에러있을때 분모가 0일때 에러 
raise 에러코드   강제 에러 만들기

### isdigit()

width=input()
height =input()
area = 0

if width.isdigit() and height. isdigit():
	area = int(width) * int(height)
    print("{0} x {1} = {2}".format(width, height, area))
else:
	print("숫자가 아닌 값이 입력 되었습니다.")
    

 

 

### try

width=input()
height =input()
area = 0

try :
	area = int(width) * int(height)
    print("{0} x {1} = {2}".format(width, height, area))
except:
	print("숫자가 아닌 값이 입력 되었습니다.")
    

### else

width=input()
height =input()
area = 0

try :
	area = int(width) * int(height)
except:
	print("숫자가 아닌 값이 입력 되었습니다.")
else:	
    print("{0} x {1} = {2}".format(width, height, area))

### finally

width=input()
height =input()
area = 0

try :
	area = int(width) * int(height)
except:
	print("숫자가 아닌 값이 입력 되었습니다.")
else:	
    print("{0} x {1} = {2}".format(width, height, area))
finally:
	print("finally 코드 블록은 예외 발생 여부에 상관 없이 실행됩니다.")
    

### except Exception as ex

width=input()
height =input()
area = 0

try :
	area = int(width) * int(height)
except Exception as ex:
	print("{0}: {1}".format(type(ex), ex)))
else:	
    print("{0} x {1} = {2}".format(width, height, area))
finally:
	print("finally 코드 블록은 예외 발생 여부에 상관 없이 실행됩니다.")
    

###raise

def calc_area(w, h):
	if w.isdigit() and h.isdigit():
    	resturn int(w) * int(h)
    else:
    	raise ValueError("숫자가아닌값이 입력되었습니다.")
        
print("사각형의 면적을 구해봅시다.")

width = input("폭을 입력하세요: 0")
height = input("높이를 입력하세요: ")

try:
	area = clac_area(width, height)
expect ValueError as ve:
	print("{0}: {1}".format(type(ve), ve))
expect Exception as ex:
	print("{0}: {1}".format(type(ex), ex))
else:
	print("{0} x {1} = {2}".format(width, height, area))
  

###연습

def input_index():
	num =0
    try:
    	num = int(input("인덱스로 사용할 숫자를 입력하세요: "))
    except ValueError as exception
    	raise exception
    else:
    	return num
        
def print_in_bounds(list, index):
	value - 0
    try:
    	value = list[index]
    except:
    	print("{0} {1}".format(type(exception),exception)
        index = len(list) -1
        print("인덱스는 0 ~ {0}까지 사용할 수 있습니다."format(index))
        value = list[index]
    finally:
    	print("[{0}]: {1}".format(data_list))
        
data_list = list(range(1, 11))
print("data_list: {0}".format(data_list))
try:
	num = input_index()
    print("[{0}]: {1}".format(num1, data_list[num1]))
except IndexError as exception:
	print(exception)
except ValueError as exeption:
	print("{0} {1}".format(type(exception),exception))
except Exception as exception:
	print(exception)
    

'+++++SW 일일 공부+++++ > SW Expert Aademy' 카테고리의 다른 글

리스트 조작법  (0) 2020.01.24
Python 표준 모듈과 활용  (0) 2020.01.14
가변함수에 대하여  (0) 2020.01.11
실행 관련 함수  (0) 2020.01.11
Python 변환함수  (0) 2020.01.11
블로그 이미지

Or71nH

,
def sum_all(*args):
    result = 0
    for i in args:
        result += i

    return result

print(sum_all(1, 2, 3, 4, 5))
print(sum_all(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))

 

 

https://psychoria.tistory.com/530

 

파이썬 가변인자 함수 사용

가변인자 함수는 함수가 몇 개의 인자를 받을지 정해지지 않은 함수입니다. 파이썬에서는 가변인자 함수를 지원하고 있습니다. C++에도 가변인자 함수를 구현하고 있는데 아래 링크에서 내부 구조를 확인할 수 있..

psychoria.tistory.com

 

 

https://wayhome25.github.io/python/2017/02/26/py-12-exception/

 

 

파이썬 파트12. 예외처리 - try / except, raise · 초보몽키의 개발공부로그

파이썬 파트12. 예외처리 try hello world 파이썬 입문 강의 try / except 파이썬으로 프로그래밍 중에 다양한 에러가 발생할 수 있다. 이 에러가 발생하는 예외상황은 유연하게 프로그래밍을 할 수 있는 도구가 되기도 한다. 에러 예시 # IndexError >>> list = [] >>> list[0] IndexError: list index out of range # ValueError >>> text = 'abc' >>> number

wayhome25.github.io

 

'+++++SW 일일 공부+++++ > SW Expert Aademy' 카테고리의 다른 글

Python 표준 모듈과 활용  (0) 2020.01.14
Python 구문오류와 예외  (0) 2020.01.11
실행 관련 함수  (0) 2020.01.11
Python 변환함수  (0) 2020.01.11
Python 수칙연산 함수  (0) 2020.01.08
블로그 이미지

Or71nH

,

###함수

eval(계산식이 포함된 문자열) 문자열 이지만 계산하고 싶을때 문자열안에 식을 계산하여 반환한다

### 정보

expr = "2 + 5 * 3"

print("{0} => {1}".format(expr, eval(expr)))

expr = "'hello, python!'.upper()"

print("{0} => {1}".format(exdpr, eval(expr)))

// 2 + 5 * 3 => 17
// ' hello, python!'.upper() => HELLO, PYTHON!

'+++++SW 일일 공부+++++ > SW Expert Aademy' 카테고리의 다른 글

Python 구문오류와 예외  (0) 2020.01.11
가변함수에 대하여  (0) 2020.01.11
Python 변환함수  (0) 2020.01.11
Python 수칙연산 함수  (0) 2020.01.08
중복제거  (0) 2020.01.07
블로그 이미지

Or71nH

,

###표

chr(정수)   문자로 변환
ord(문자)   유니코드 값 (10진수)변환
hex(10진정수)   16진수 변환
int(문자&부동소수) 숫자같이 생긴애들 정수로 변환
float(문자&정수) 숫자같이 생긴애들 소수로 변환
str(객체) 암거나 문자로 변환함
dir(속성정보) 무엇을 할수있나 보여줌 메소드 정보를 출력해줌
globals()   현재의 전역 심볼 테이블을 보여주는 딕셔너리를 반환하는 함수
locals()   현재의 지역 심볼 테이블을 보여주는 딕셔너리 를 반환 하는 함수
id(...) 특정 문자의 주소값 이값을 불러오는 주소를 찾음
isinstance()   포함되나?
insubclass()   부분인가?
     

### dir()

print("dir() => {0}".format(dir()))
//지역 스코프에 대한 정보를 리스트 객체로 반환
data_str = "Hello Python!"
print("dir(data_str) = {0}".format(dir(data_str)))
// 문자열이 가지고 있는 많은 메소드 정보를 리스트 객체에 담아 반환
data_list = [ 10, 20, 30, 40, 50]
print("dir(data_list) => {0}".format(dir(data_list)))
//정수형 리스트 객체가 가지고 있는 메소드 정보들을 리스트 객체에 담아 반환
data_dict = {"key1": 10, "key2" :20, "key3": 30}
print("dir(data_dict) => {0}".format(dir(data_dict)))
//객체가 가지고 있는 메소드 정보들을 리스트 객체에 담아반환



///... 결과는 넘 빡셈 해보셈

###globals() , locals()

class MyClass:
	pass
    
def test_fn(param):
	def inner_fn():
    	pass
    val1 = 5
    val2 = 8
    for item in locals().items():
    	print("\t{0} : {1}".format(item[0], item[1]))
        //첫번째 항목인 키를, 두번째 항목인 값을 접근해 지역 정보 출력
        
value1 = 10
value2 = 20 
obj1 = MyClass()

g = dict(globals())

print("globals()")
for item in g.items():
	print("\t{0} : {1}".format(item[0], item[1]))
    
prnt("\n\nlocals()")
test_fn(10)

잘 이해 안됫음

 

### id()

x = 10
print("{0} x의 주소 값: {1}".format(type(x), hex(id(x))))

y = 10
print("{0} y의 주소 값: {1}".format(type(y), hex(id(y))))

//<class 'int'> x의 주소 값: 0x751e6f00
//<class 'int'> y의 주소 값: 0x751e6f00

####isinstance(), ussubclass

class Parent:
	pass
    
class Child(Parent):
	pass
    
p = Parent()
c = Child()

print("p 객체는 Parent 클래스의 인스턴스입니까? {0}".format(isinstance(p, Parent)))
print("c 객체는 Child 클래스의 인스턴스입니까? {0}".format(isinstance(c, Child)))
print("c 객체는 Parent 클래스의 인스턴스입니까? {0}".format(isinstance(c, Parent)))
print("p 객체는 Child 클래스의 인스턴스입니까? {0}".format(isinstance(p,Child)))

print("Child 객체는 Parent 클래스의 서브클래스입니까? {0}".format(issubclass(Child, Parent)))

//p 객체는 Parent 클래스의 인스턴스입니까?  True 
//c 객체는 Child 클래스의 인스턴스입니까?    True
//c 객체는 Parent 클래스의 인스턴스입니까?    True
//p 객체는 Child 클래스의 인스턴스입니까?    False
//Child 객체는 Parent 클래스의 서브클래스입니까?    True

'+++++SW 일일 공부+++++ > SW Expert Aademy' 카테고리의 다른 글

가변함수에 대하여  (0) 2020.01.11
실행 관련 함수  (0) 2020.01.11
Python 수칙연산 함수  (0) 2020.01.08
중복제거  (0) 2020.01.07
Python 가위바위보  (0) 2020.01.07
블로그 이미지

Or71nH

,