8월, 2020의 게시물 표시

파이썬11. 메소드

class   AttackUnit :      def   __init__ ( self , name , hp , damage ):          self .name = name           self .hp = hp          self .damage = damage       def   attack ( self , location ):          print ( " {0}  : {1}  방향으로 적군을 공격 합니다.[공격력  {2} ]"  .format( self .name,location, self .damage))           def   damaged ( self , damage ):          print ( " {0}  : {1}  데미지를 입었습니다." .format( self .name,damage))          self .hp -= damage          print ( " {0}  :현재 체력은  {1}  입니다."  .format...

파이썬10. 클래스

  class   Unit :      def   __init__ ( self , name , hp , damage ):          self .name = name           self .hp = hp          self .damage = damage           print ( " {0}  유닛이 생성 되었습니다." .format( self .name))          print ( "체력  {0} ,공격력  {1} " .format( self .hp, self .damage)) marine1 = Unit( "마린" , 40 , 5 ) marine2 = Unit( "마린" , 40 , 5 ) tank = Unit( "탱크" , 150 , 35 ) class   Unit :      def   __init__ ( self , name , hp , damage ):          self .name = name           self .hp = hp       ...

퀴즈) 주간 보고 파일 만들기

  #Quiz)당신 회사에서는 매주 1회 작성해야 하는 보고서가 있습니다. #보고서는 항상 아래와 같은 형태로 출력되어야 한다 # -X 주차 주간보고 - # 부서 : # 이름 : # 업무요약 # 파일명은 1~50 주차까지 '1주차.txt  2주차.txt ..와 같이 만듭니다. for  i  in   range ( 1 , 51 ):     fine_name = str (i)+ "주차.txt"      with   open (fine_name, "w" , encoding = "utf8" )  as  report:         report.write( "- {0}  주차 주간보고" .format(i))         report.write( " \n 부서 : " )         report.write( " \n 이름 :" )         report.write( " \n 업무요약:" )

파이썬 기초9. with

  import  pickle with   open ( "profile.pickle" , "rb" )  as  profile_file:   print (pickle.load(profile_file)) with   open ( "study.txt" , "w" , encoding = "utf8" )  as   study_files:     study_files.write( "파이썬을 열심히 하고 있다." ) with   open ( "study.txt" , "r" , encoding = "utf8" )  as  study_files:      print (study_files.read())

파이썬 기초8 pickle

 먼저 하기전에 경로에 pickle.py파일이 없어야 한다. import시 원하는 파일이 아닌 신규로 만든 파일을 import 할수 있음 아래와 같은 에러가 발생 Traceback (most recent call last):   File "c:/python_work/test_pi.py", line 1, in <module>     import pickle   File "c:\python_work\pickle.py", line 5, in <module>     pickle.dump(profile,profile_file) #profile에 있는 정보를 file에 저장  AttributeError: partially initialized module 'pickle' has no attribute 'dump' (most likely due to a circular import) import  pickle profile ={ "이름" : "박명수" , "나이" : 30 , "취미" :[ "축구" , "골프" , "코딩" ]} profile_file =  open ( "profile.pickle" , "wb" )  #쓰는 목적 binary파일 정의 print (profile) pickle.dump(profile,profile_file)  #profile에 있는 정보를 file에 저장 profile_file.close() profile_file =  open ( "profile.pickle" , "rb" ) profile = pickle.load(profile_file)  #파일에 있는 정보를 profile에 불러오는 print (profile) profile_file.close()

beautifulsoup 크롤링 예제 네이버 블로그 검색결과 크롤러 만들기

 PS C:\python_work> pip install beautifulsoup4      import  urllib.request import  urllib.parse  #한글 링크 문제 없애는 모듈  from  bs4  import  BeautifulSoup baseUrl =  'https://search.naver.com/search.naver?sm=top_hty&fbm=1&ie=utf8&query='   #네이버 검색 기본 plusUrl =  input ( '검색어를 입력하세요:' ) url = baseUrl +urllib.parse.quote_plus(plusUrl)   html = urllib.request.urlopen(url).read() soup = BeautifulSoup(html, 'html.parser' ) title = soup.find_all( class_ = 'sh_blog_title' ) # print(len(title)) for  i  in  title:      print (i.attrs[ 'title' ])      print (i.attrs[ 'href' ])      print () 검색어를 입력하세요:파이썬 파이썬 설치 다운로드부터 해야겠죠? https://blog.naver.com/sweetk2ss?Redirect=Log&logNo=221954566322 파이썬 학원 : 자기개발과 취업, 무엇을 목표로 시작하나요? https://blog.naver...

파이썬 기초.7 file 입출력

score_file =  open ( "score.txt" , "w" , encoding = "utf8" )  #새로 생성해서 print ( "수학 : 0" , file =score_file) print ( "영어 : 50" , file =score_file) score_file.close() score_file =  open ( "score.txt" , "a" , encoding = "utf8" )  #기존 파일 붙여넣기 score_file.write( "수학 : 80" ) score_file.write( " \n 코딩 : 100" ) score_file.close() score_file =  open ( "score.txt" , "r" , encoding = "utf8" )  print (score_file.read()) score_file.close() score_file =  open ( "score.txt" , "r" , encoding = "utf8" )  print (score_file.readline(), end = "" ) #한줄만 읽고,줄바꿈 유무는 end="" 넣으면 다음 줄로 이동 print (score_file.readline()) print (score_file.readline()) print (score_file.readline()) score_file.close() score_file =  open ( "score.txt" , "r" , encoding = "utf8" )  while   True :     line = score_file.readline()   ...

파이썬 기초.6 format

#빈 자리는 빈공간으로 두고,오른쪽 정렬을 하되,총 10자리 공간을 확보 print ( " {0: >10} " .format( 500 )) #양수일 땐 + 표시,음수일 땐 -로 표시 print ( " {0: >+10} " .format( 500 )) print ( " {0: >+10} " .format(- 500 )) #왼쪽 정렬하고,빈칸으로 _로 채움 print ( " {0:_<+10} " .format(- 500 )) #큰숫자가 들어올때 3자리마다 콤마를 찍어주기 print ( " {0:,} " .format( 10000000 )) #큰숫자가 들어올때 +,-에 3자리마다 콤마를 찍어주기 print ( " {0:+,} " .format( 10000000 )) #3자리마다 콤마를 찍어주기,부호도 붙이고,지릿수 확보하기 #빈자리는 ^로 표시 왼쪽 정렬 print ( " {0:^<+30,} " .format( 10000000 )) #소수점 출력 print ( " {0:f} " .format( 5 / 3 )) #소수점 특정(두번째 자리까지) 자리수 까지만 표시 print ( " {0:.2f} " .format( 5 / 3 ))

파이썬기초.5 function 키워드

#키워드값을 호출하는 함수 def   profile ( name , age , main_lang ):      print (name,age,main_lang) profile( name = "유재석" , main_lang = "java" , age = 17 ) def   profile ( name , age , lang1 , lang2 , lang3 , lang4 , lang5 ):      print ( "이름:  {0} \t  나이:  {1} \t " .format(name,age), end = " " )  #한 라인에 이어서      print (lang1,lang2,lang3,lang4,lang5) profile( "유재석" , 20 , "Python" , "java" , "C" , "C++" , "C#" ) profile( "김태호" , 20 , "" , "" , "" , "" , "" ) #가변인자 def   profile ( name , age , * language ):      print ( "이름:  {0} \t  나이:  {1} \t " .format(name,age), end = " " )  #한 라인에 이어서      for   lang  in  language:          print (lang,  end = " " )      print () profile( "유재석" , 24 , "1" , "2" ) #지역변수,전역변수...

파이썬기초.4 function

def   open_account ():      print ( "새로운 계좌가 생성되었습니다." ) open_account()  def   deposit ( balance , money ):      print ( "입급이 완료되었습니다. 잔액은  {0} 원입니다" .format(balance + money))      return  balance + money def   withdraw ( balance , money ):  #잔고가 출금보다 많다면      if  balance >= money:          print ( "출금이 완료되었습니다. 잔액은  {0}  원입니다."  .format(balance-money))          return  balance-money      else :          print ( "출금이 완료되지 않았습니다. 잔액은  {0}  원입니다" .format(balance))          return  balance # #두개의 값을 보내주는 def   withdraw_nigh ( balance , money ):  #저녁에...

파이썬 기초.3 for문 while 퀴즈

for  waiting_no  in  [ 0 , 1 , 2 , 3 , 4 ]:      print ( "대기번호 : {0} " .format(waiting_no)) for  waiting_no  in   range ( 1 , 6 ):      print ( "대기번호 : {0} " .format(waiting_no)) starbucks = [ "아이언맨" , "토르" , "아이엠" ] for  customer  in  starbucks:      print ( " {0} ,커피가 준비되어 있습니다." .format(customer)) customer =  "토르" index = 5 while  index >= 1 :      print ( " {0} ,커피가 준비되었습니다. {1} 번 남았어요" .format(customer,index))     index -= 1      if  index == 0 :          print ( "커피는 폐기처분 되었습니다." ) customer =  "아이언맨" index = 1 while   True :      print ( " {0} ,커피가 준비되었습니다. {1} 번 남았어요" .format(customer,index))     index+= 1   custo...

파이썬 기초 if문

# weather = input("오늘 날씨는 어때요?") # if weather == "비": #     print("우산을 챙기세요") # elif weather =="미세먼지": #     print("마스크를 챙기세요") # else: #     print("준비물 필요없음")  # temp = int(input("기온이 어때요?")) # if temp>=30: #     print("너무 더워요.나가지 마세요") # elif 10<=temp and temp<30: #     print("괜찮은 날씨에요") # elif 0<= temp <10: #     print("외투를 챙기세요") # else: #     print("너무 추워요. 나가지 마세요")

파이썬 기초1. Print,리스트 랜덤

# print(java - python) # print(java.difference(python)) # #python 할줄 아는 사람 늘어나는 # python.add("김태호") # print(python) # #java를 잊어먹을때 # java.remove("김태호") #자료구조 변경 # menu ={"커피","우유","주스"} # print(menu,type(menu)) # menu = list(menu) # print(menu,type(menu)) # menu = tuple(menu) # print(menu,type(menu)) #당신의 학교에서는 파이썬 코딩 대회를 주최합니다. #참석률을 높이기 위해 댓글 이벤트를 진행하기로 하였습니다. #댓글 작성자들 중에 추첨을 통해 1명은 치킨,3명은 커피쿠폰을 받게 됩니다. #추첨 프로그램을 작성하시오 #참조 # from random import * # lst = [1,2,3,4,5] # print(lst) # shuffle(lst)          #랜덤하게 배열 # print(lst) # print(sample(lst,1)) #lst 배열의 첫번째 출력 # from random import * # user =...

파이썬 마우스,키보드 자동화 (pyautogui 매크로 프로그램 만들기)

이미지
1. console 창에서 pip install pyautogui 2. pyautogui 불러오기 3. 현재 마우스 좌표보기,마우스 이동시키기(절대좌표) moveTo(141,429,2) 2는 2초안에 이동시키기  4. 지금 좌표에서 좌표 이동시키기 (y 좌표 변경) >>> pyautogui.moveRel(0,200,2) 5. 파이썬 코딩전 해당 실행할 마우스 포인트 위치를 확인 >>> pyautogui.position() Point(x=26, y=102) 6. 파이썬 프로그램부분  import  pyautogui import  time pyautogui.moveTo( 1860 , 20 , 1 ) #pyautogui.click()#클릭을 한번 #pyautogui.click(clicks=2,interval=2)#클릭을 한번하고 2초이후에 다시 클릭 pyautogui.doubleClick() time.sleep( 1 ) pyautogui.typewrite([ 'a' , 'b' , 'c' , 'enter' ]) #키보드 키를 눌러주는