'과거의 컴퓨터 공부/Python'에 해당하는 글 5건

반응형

import struct

data를 binary string으로 표현할 때 struct module을 사용한다


[proto type]

lambda 인자 : 표현식


라이트업을 쓰는 사람들도 그렇고 파이썬으로 소켓프로그래밍 하는사람들은 

대부분 이 함수를 애용하는 것 같다.

프로토 타입은 위에 적어논거 처럼 굉장히 간단하다. (+함수를 한줄만으로 만들게 해준다)

[ex1]

>>> def  hap(x,y):

return x + y


>>> hap(10,20)

30

>>> (lambda x,y: x+y) (10,20)

30

>>> 

인터넷에서 찾아본예제고 실제로 써봣는데 컬쳐 쇼크엿다 ㄷㄷ ; 함수의 이름 조차 선언해주지 않고도 

함수처럼 사용할 수 있다 


 [ex2] 

import struct

p=lambda x: struct.pack("<Q",x)  #Q   unsigned long long   integer   8   (2), (3)
# > : Big endian  <: Little endian 
#리틀엔디언 형식으로 unsigned long long 타입 파이썬데이터를  binary로 뽑아온다 

up= lambda x:struct.unpack("<L",x) # L  unsigned long   integer   4   (3)
#리틀엔디언 형식으로 unsgined long 타입 binary string을 파이썬 데이터로 뽑아온다 

참조 : https://docs.python.org/2/library/struct.html


위의 예제는 내가 실제로 많이 봐왓던 선언 부분이다 .. p,up 부분은 변수의 이름이 될테고

pack 과 unpack은 string을 c/c++처럼 각 character를 binary value로 다루게 해준다(+파이썬에서 아스키값을 바로 처리하기 위해 c의 struct 기능을 제공해 준다)
pack 은 파이썬 data를 binary로 변경할때 쓰고
unpack은 binary string을 python로 변경할때 사용한다 

[pack]
>>> import struct
>>> buffer=struct.pack("ibh",1,2,3)
>>> print repr(buffer)
'\x01\x00\x00\x00\x02\x00\x03\x00'

+) i: type을 int로 b: (signed char) h: short. 즉 1,2,3 번째 받는 인자들의 타입들을 선언해주는것 


[unpack]

>>> unpack('%sB'%len('abc'), 'abc')
(97, 98, 99)
>>> unpack('%sB'%3, 'abc')
(97, 98, 99)
>>> unpack('ssB', 'abc')
('a', 'b', 99)
>>> unpack('2sB', 'abc')
('ab', 99)

pack& unpack 참조  :

 http://coreapython.hosting.paran.com/grimoire/Python%20Grimoire.htm


`



반응형

'과거의 컴퓨터 공부 > Python' 카테고리의 다른 글

sys모듈 사용  (0) 2014.08.29
자판기.py  (0) 2014.08.28
자료형  (0) 2014.08.28
기본적인 연산, for 문, if 문  (0) 2014.08.25
,
반응형


sys1.py


sys2.py


test.txt(뻘짓거리) 

+) 파이썬 언어가 쉬워서 그런지 점점 속도가 붙는 느낌  


반응형

'과거의 컴퓨터 공부 > Python' 카테고리의 다른 글

lambda(),struct.pack, struct.unpack  (0) 2014.09.05
자판기.py  (0) 2014.08.28
자료형  (0) 2014.08.28
기본적인 연산, for 문, if 문  (0) 2014.08.25
,
반응형

Python 2.6.5 (r265:79096, Mar 19 2010, 21:48:26) [MSC v.1500 32 bit (Intel)] on win32

Type "copyright", "credits" or "license()" for more information.


    ****************************************************************

    Personal firewall software may warn about the connection IDLE

    makes to its subprocess using this computer's internal loopback

    interface.  This connection is not visible on any external

    interface and no data is sent to or received from the Internet.

    ****************************************************************

    

IDLE 2.6.5      

>>> a=[1,2,3]

>>> b=a

>>> a[1]

2

>>> a[1]=4

>>> b

[1, 4, 3]

>>> 1

1

>>> a

[1, 4, 3]

>>> a=[1,2,3]

>>> b=a[:]

>>> a[1,4,3]


Traceback (most recent call last):

  File "<pyshell#9>", line 1, in <module>

    a[1,4,3]

TypeError: list indices must be integers, not tuple

>>> from copy import copy

>>> b=copy(a)

>>> b is a

False

>>> 

>>> money=1

>>> if money:

print "taxi"

else:

print "on foot"


taxi

>>> if a>3:

print "Hello"

else:

print "nop!"

a=3


Hello

>>> money=1

>>> x=3

>>> y=2

>>> x>y

True

>>> x<y

False

>>> print "Using : %p\n",0x1032

Using : %p

4146

>>> money=2000

>>> if money >=3000:

print "taxi"

else:

print "on foot"


on foot

>>> 1 in [1,2,3]

True

>>> 1 not in [1,2,3]

False

>>> pocket=['paper','handphone','money']

>>> if

SyntaxError: invalid syntax

>>> if

SyntaxError: invalid syntax

>>> if

SyntaxError: invalid syntax

'

>>> if 'money' in 'pocket':

print "taxi"

else:

print "on foot"


on foot

>>> 

>>> pocket=['paper','hadndphone']

>>> watch=1

>>> if 'money' in pocket:

print "taxi"

elif watch:

print "taxi"

else:

print "on foot"


taxi

>>> 

>>> pocket=['paper','money','handphone']

>>> if 'money' in pocket:

pass

else:

print "ttttt"


>>> if 'money' in pocket:pass

else: print "ttttt"


>>> treeHit=0

>>> while treeHit<10:

treeHit=treeHit+1

print "나무를 %d번 찍엇음." % treeHit

if treeHit==10:

print"나무가넘어감"


나무를 1번 찍엇음.

나무를 2번 찍엇음.

나무를 3번 찍엇음.

나무를 4번 찍엇음.

나무를 5번 찍엇음.

나무를 6번 찍엇음.

나무를 7번 찍엇음.

나무를 8번 찍엇음.

나무를 9번 찍엇음.

나무를 10번 찍엇음.

나무가넘어감

>>> 나무를 2번 찍엇음.

SyntaxError: invalid syntax

>>> while 1:

print "ctrl+c"


ctrl+c

ctrl+c

ctrl+c

ctrl+c

ctrl+c

ctrl+c

ctrl+c

ctrl+c

ctrl+c

ctrl+c





Traceback (most recent call last):

  File "<pyshell#83>", line 2, in <module>

    print "ctrl+c"

KeyboardInterrupt

>>> prompt ="""

1.Add

2.Del

3.List

4.Quit


Enter number: """

>>> 

>>> number=0

>>> while number !=4:

print prompt

number = int(raw_input())



1.Add

2.Del

3.List

4.Quit


Enter number: 

'


Traceback (most recent call last):

  File "<pyshell#96>", line 3, in <module>

    number = int(raw_input())

ValueError: invalid literal for int() with base 10: "'"

>>> coffee =10

>>> money =300

>>> while money:

print "give coffee"

coffee=coffee-1

print "남은양 : %d" % coffee

if not coffee:

print "don't have coffee"

break


give coffee

남은양 : 9

give coffee

남은양 : 8

give coffee

남은양 : 7

give coffee

남은양 : 6

give coffee

남은양 : 5

give coffee

남은양 : 4

give coffee

남은양 : 3

give coffee

남은양 : 2

give coffee

남은양 : 1

give coffee

남은양 : 0

don't have coffee

>>> don't have coffee

SyntaxError: EOL while scanning string literal

>>> a=0

>>> while a<10:

a=a+1

if a%2==0:continue

print a


1

3

5

7

9

>>> test_list=['one','two','three']

>>> for i in test_list:

print i


one

two

three

>>> mark=[90,25,67,45,80]

>>> number=0

>>> for mar in mark:Python 2.6.5 (r265:79096, Mar 19 2010, 21:48:26) [MSC v.1500 32 bit (Intel)] on win32

Type "copyright", "credits" or "license()" for more information.


    ****************************************************************

    Personal firewall software may warn about the connection IDLE

    makes to its subprocess using this computer's internal loopback

    interface.  This connection is not visible on any external

    interface and no data is sent to or received from the Internet.

    ****************************************************************

    

IDLE 2.6.5      

>>> a=[1,2,3]

>>> b=a

>>> a[1]

2

>>> a[1]=4

>>> b

[1, 4, 3]

>>> 1

1

>>> a

[1, 4, 3]

>>> a=[1,2,3]

>>> b=a[:]

>>> a[1,4,3]


Traceback (most recent call last):

  File "<pyshell#9>", line 1, in <module>

    a[1,4,3]

TypeError: list indices must be integers, not tuple

>>> from copy import copy

>>> b=copy(a)

>>> b is a

False

>>> 

>>> money=1

>>> if money:

print "taxi"

else:

print "on foot"


taxi

>>> if a>3:

print "Hello"

else:

print "nop!"

a=3


Hello

>>> money=1

>>> x=3

>>> y=2

>>> x>y

True

>>> x<y

False

>>> print "Using : %p\n",0x1032

Using : %p

4146

>>> money=2000

>>> if money >=3000:

print "taxi"

else:

print "on foot"


on foot

>>> 1 in [1,2,3]

True

>>> 1 not in [1,2,3]

False

>>> pocket=['paper','handphone','money']

>>> if 'money' in 'pocket':

print "taxi"

else:

print "on foot"


on foot

>>> 

>>> pocket=['paper','hadndphone']

>>> watch=1

>>> if 'money' in pocket:

print "taxi"

elif watch:

print "taxi"

else:

print "on foot"


taxi

>>> 

>>> pocket=['paper','money','handphone']

>>> if 'money' in pocket:

pass

else:

print "ttttt"


>>> if 'money' in pocket:pass

else: print "ttttt"


>>> treeHit=0

>>> while treeHit<10:

treeHit=treeHit+1

print "나무를 %d번 찍엇음." % treeHit

if treeHit==10:

print"나무가넘어감"


나무를 1번 찍엇음.

나무를 2번 찍엇음.

나무를 3번 찍엇음.

나무를 4번 찍엇음.

나무를 5번 찍엇음.

나무를 6번 찍엇음.

나무를 7번 찍엇음.

나무를 8번 찍엇음.

나무를 9번 찍엇음.

나무를 10번 찍엇음.

나무가넘어감

>>> 나무를 2번 찍엇음.

SyntaxError: invalid syntax

>>> while 1:

print "ctrl+c"


ctrl+c

ctrl+c

ctrl+c

ctrl+c

ctrl+c

ctrl+c

ctrl+c

ctrl+c

ctrl+c

ctrl+c

ctrl+c

ctrl+c

ctrl+c

ctrl+c

ctrl+c



Traceback (most recent call last):

  File "<pyshell#83>", line 2, in <module>

    print "ctrl+c"

KeyboardInterrupt

>>> prompt ="""

1.Add

2.Del

3.List

4.Quit


Enter number: """

>>> 

>>> number=0

>>> while number !=4:

print prompt

number = int(raw_input())



1.Add

2.Del

3.List

4.Quit


Enter number: 

'


Traceback (most recent call last):

  File "<pyshell#96>", line 3, in <module>

    number = int(raw_input())

ValueError: invalid literal for int() with base 10: "'"

>>> coffee =10

>>> money =300

>>> while money:

print "give coffee"

coffee=coffee-1

print "남은양 : %d" % coffee

if not coffee:

print "don't have coffee"

break


give coffee

남은양 : 9

give coffee

남은양 : 8

give coffee

남은양 : 7

give coffee

남은양 : 6

give coffee

남은양 : 5

give coffee

남은양 : 4

give coffee

남은양 : 3

give coffee

남은양 : 2

give coffee

남은양 : 1

give coffee

남은양 : 0

don't have coffee

>>> don't have coffee

SyntaxError: EOL while scanning string literal

>>> a=0

>>> while a<10:

a=a+1

if a%2==0:continue

print a


1

3

5

7

9

>>> test_list=['one','two','three']

>>> for i in test_list:

print i


one

two

three

>>> mark=[90,25,67,45,80]

>>> number=0

>>> for mar in mark:

number=number+1

if mar >=60:

print "%d번 학생은 합격" %number

else:

print "%d번 학생은 불합격" %number


1번 학생은 합격

2번 학생은 불합격

3번 학생은 합격

4번 학생은 불합격

5번 학생은 합격

number=number+1

if mar >=60:

print "%d번 학생은 합격" %number

else:

print "%d번 학생은 불합격" %number


1번 학생은 합격

2번 학생은 불합격

3번 학생은 합격

4번 학생은 불합격

5번 학생은 합격



자판기.py

+)미숙해서 그런건지 짱구가 안굴러가서 그런건지 ㅡㅡ ;아직은 진전이없음 


반응형

'과거의 컴퓨터 공부 > Python' 카테고리의 다른 글

lambda(),struct.pack, struct.unpack  (0) 2014.09.05
sys모듈 사용  (0) 2014.08.29
자료형  (0) 2014.08.28
기본적인 연산, for 문, if 문  (0) 2014.08.25
,
반응형

Python 2.6.5 (r265:79096, Mar 19 2010, 21:48:26) [MSC v.1500 32 bit (Intel)] on win32

Type "copyright", "credits" or "license()" for more information.


    ****************************************************************

    Personal firewall software may warn about the connection IDLE

    makes to its subprocess using this computer's internal loopback

    interface.  This connection is not visible on any external

    interface and no data is sent to or received from the Internet.

    ****************************************************************

    

IDLE 2.6.5      

>>> pinr


Traceback (most recent call last):

  File "<pyshell#0>", line 1, in <module>

    pinr

NameError: name 'pinr' is not defined

>>> 

>>> print "I eat %s apples."%"five"

I eat five apples.

>>> number=3

>>> print"I eat %d apples."%nuber


Traceback (most recent call last):

  File "<pyshell#4>", line 1, in <module>

    print"I eat %d apples."%nuber

NameError: name 'nuber' is not defined

>>> print "I eat %d apples." % number

I eat 3 apples.

>>> a="hi"

>>> a.upper()

'HI'

>>> a="hobby"

>>> a.count('b')

2

>>> NameError: name 'nuber' is not defined

SyntaxError: invalid syntax

>>> a='Python is best choice"

SyntaxError: EOL while scanning string literal

>>> a.find('b')

2

>>> a="life is too short"

>>> a.index('t')

8

>>> a=","

>>> a.join('abcd')

'a,b,c,d'

>>> a="Hi man"

>>> a.swapcase()

'hI MAN'

>>> odd=[1,3,5,7,9]

>>> dic={'name':'pey','phone':'0119993323','birth':'1118'}

>>> grade={'pey':10,'juliet':99}

>>> grade['pey']

10

>>> grade['juliet']

99

>>> a=[1,2,3,4]

>>> while a:

a.pop()


4

3

2

1

>>> if[]:

print "True"

else:

SyntaxError: invalid syntax

>>> if []:

print "True"

else:

SyntaxError: invalid syntax

>>> if[1,2,3]:

print "True"

else:

print "False"


True


+)쭉한번 훑은다음에 프로그램하나 만들 계획

반응형

'과거의 컴퓨터 공부 > Python' 카테고리의 다른 글

lambda(),struct.pack, struct.unpack  (0) 2014.09.05
sys모듈 사용  (0) 2014.08.29
자판기.py  (0) 2014.08.28
기본적인 연산, for 문, if 문  (0) 2014.08.25
,
반응형

Python 2.6.5 (r265:79096, Mar 19 2010, 21:48:26) [MSC v.1500 32 bit (Intel)] on win32

Type "copyright", "credits" or "license()" for more information.


    ****************************************************************

    Personal firewall software may warn about the connection IDLE

    makes to its subprocess using this computer's internal loopback

    interface.  This connection is not visible on any external

    interface and no data is sent to or received from the Internet.

    ****************************************************************

    

IDLE 2.6.5      

>>> 1+2

3

>>> 3/1.24

2.4193548387096775

>>> a=1

>>> b=2

>>> c=3

>>> a+b+c

6

>>> a="Python"

>>> print a

Python

>>> a=2+3j

>>> b=3

>>> a*b

(6+9j)

>>> a=3

>>> if a>1:

print "a>1"


a>1

>>> for a in [1,2,3]:

print a


1

2

3

>>> i=0

>>> while 1<3:

i=i+1

print i


예전부터 하긴햇는데 제대로하는건 이번이 첨인듯 ㅠㅠ 신세계이긴한데 아직 문법이 미숙 

반응형

'과거의 컴퓨터 공부 > Python' 카테고리의 다른 글

lambda(),struct.pack, struct.unpack  (0) 2014.09.05
sys모듈 사용  (0) 2014.08.29
자판기.py  (0) 2014.08.28
자료형  (0) 2014.08.28
,