A byte of python筆記

5.6三引號字符串''' '''(多行字符串)


5.7 \ 需要說明的是,在一個字符串中,在一行末尾的反斜槓僅僅表示下一行的字符串
是上一行的繼續。,但並不增加新的行。例如:
1 "This is the first sentence.\
2 This is the second sentence."


"This is the first sentence. This is the second sentence."

 等價。


5.8 自然字符串(保留字符串原來的格式,不受轉義影響)
>>>print('Newlines are indicated by \n')
Newlines are indicated by 




>>>print(r'Newlines are indicated by \n')
Newlines are indicated by \n
>>>




5.10 字符串按字面意義連接
>>>print('What\'s'"your name?")
What'syour name?



5.12 format()!!!!!
print('the length of the string is {0}'.format(len(s))) == 
print('the length of the string is',len(s))




5.   end=
for item in shopList:
    print(item, end=' ')


( ,end=' ')使得print打印後不會以'\n'結尾,回車換行


7:控制流


1): if guess < number :
2): elif guess > number :
3): 沒有switch 語句
4): while帶有else :
5): 
for i in range(1,10):	else:	//for i in [1,2,3,4]:


6):
 for i in range(1,10,2):	else:	//for i in [1,3,5,7,9]:


7): 如果你從 for 或 while 循環中終止,任何對應的循環 else 塊將不執行


8: 函數


1): 全局語句 global
2): 非局部語句 nonlocal
3): 默認參數值 def say(message, times = 1):(只有在形參表末尾的那些參數可以有默認參數值)
    (例如, def func(a, b=5) 是有效的,但是 def func (a=5, b) 是無效的。)

4): 關鍵參數:
def func2(a, b=4, c=9):
    	print('a =',a,'b =',b,'c =',c)
func2(1,2,3)
func2(1,c=5)
func2(3,c=2,b=4)


5): VarArgs參數:
def func3(init = 5, *numbers, **keyWorlds):
    	count = init
    	for num in numbers:
        	count += num
   	for key in keyWorlds:
       		#count += key
        	count += keyWorlds[key]
    	return count


6):如果你想使用 keyword-only 參數,但又不需要帶星的參數,可以簡單地使用不適
用名字的空星,如 def total(initial=5, *, vegetables)。

7): DocStrings 

//help(print())就是使用的DocStrings



9: 模塊


1): import sys
   
from sys import argv //import java.util.Scanner
from sys import *   //import java.util.*

2): if __name__ == '__main__':
3): del: —— 該語句用於刪除變量/名字
del a (# delete/remove a name)


10: 數據結構


1): 列表(可變)
shopList = ['apple', 'mango', 'carrot', 'banana']
shopList.append('rice')
print('My shop list is now', shopList)


2): 元組(元組用來將多樣的對象集合到一起)(和字符串一樣不可變)
	zoo = ('python', 'elephant', 'penguin')
	new_zoo = ('monkey', 'camel', zoo)
	print('Animals bought from the old zoo are:', new_zoo[2])
	print('Last Animal bought from the old zoo is', new_zoo[2][2])


2.2): 含有 0 個或 1 個項目的元組:
一個空的元組由一對空的圓括號組成,如 myempty = ()。然而,含有單個元素的元組就不那麼簡
單了。你必須在第一個(唯一一個)項目後跟一個逗號,這樣 Python 才能區分元組和表達式中一
個帶圓括號的對象。即如果你想要的是一個包含項目 2 的元組的時候,你應該指明 singleton = (2 ,
)。

3): 字典
	ab = {
    		'Swaroop' : '[email protected]',
   		 'Larry' : '[email protected]',
  		  'Matsumoto' : '[email protected]',
   		 'Spammer' : '[email protected]'
   	      }


3.1): ab['Swaroop']
	print('Swaroop\'s address is:', ab['Swaroop'])


3.2): 字典中的 for循環, ab.items()//map.entry()
for name, address in ab.items():
    	print('Contact {0} at {1}'.format(name, address))


3.3): 字典中的 if判斷, ab.has_key()//map.keyset()
if 'Guido' in ab :# or ab.has_key('Guido')
    	print('Guido\'s address is', ab['Guido'])


4): 序列 (列表,元組,字符串) (切片操作)
	fruitList = ['apple', 'mango', 'carrot', 'banana']
	name = 'swaroop'
	print('Item 1 to 3 is', fruitList[1:3])
	print('Item 1 to -1 is', fruitList[1:-1])
	print('Item 2 to end is', fruitList[2:])
	print('Item start to end is', fruitList[:])
	print('The length of steps is 2', fruitList[::2])
	print('The length of steps is -1', name[::-1])


5): 集合
	bri = set(['brazil', 'russia', 'india'])
	print( 'india in bri set?','india' in bri )
	bric = bri.copy()
	bric.add('china')
	print( 'bric is super set of bri?', bric.issuperset( bri ) )
	bric.remove('russia')
	print('The intersection between bric and bri:', bric & bri)


6): 引用
引用複製(目標引用和原引用所指地址一樣):mylist = shoplist
切片複製(目標引用和原引用所指地址不同):mylist = shoplist[:]

7): 字符串
	author_name = 'Swaroop'
	if author_name.startswith('Swa'):
   		 print('Yes, the string start with "Swa"')
	if 'a' in author_name:
  		  print('Yes, it contains the string "a"')
	if author_name.find('war'):
  		  print('Yes, it contains the string "war"')
	delimiter = '_*_'
	list = ['Brazil', 'Russia', 'India', 'China']
	print(delimiter.join(list))




12:面向對象編程


1): self
2): pass
(空白塊)

3): __init__(constructor)
4): 類的變量由一個類的所有對象(實例)共享使用。只有一個類變量的拷貝,所以
當某個對象對類的變量做了改動的時候,這個改動會反映到所有其他的實例上。
4.2): 類變量相當於 Java 中的 static變量

class Robot:
    '''Represents a robot, with a name'''
    
    population = 0;
    def __init__(self, name):
        self.name = name
        print('(Initialize {0})'.format(self.name))
        Robot.population += 1


5): 類方法 相當於 Java 中的 static方法
    def howMany():
        print('We have {0:d} robots'.format(Robot.population))


    或者:
    @staticmethod
    def howMany():
        print('We have {0:d} robots'.format(Robot.population))


6): Class.__doc__ 來獲得 docstring
    Class.method.__doc__ 來獲得方法的 docstring

7): Python 中所有的類成員(包括數據成員)都是公共的,所有的方法都是有效的。
只有一個例外:如果你使用的數據成員名稱以雙下劃線前綴比如 __privatevar, Python 的名稱
管理體系會有效地把它作爲私有變量。
這樣就有一個慣例,如果某個變量只想在類或對象中使用,就應該以單下劃線前綴。而其他
的名稱都將作爲公共的,可以被其他類/對象使用。記住這只是一個慣例,並不是 Python 所要求
的(與雙下劃線前綴不同)。

8): 繼承
	class SchoolMamber:
	class Teacher(SchoolMember)


8.2): 多重繼承
	class SchoolMember:
	class FamliyMember:
	class Swaroop( SchoolMember, FamliyMember)




13: 輸入輸出
1): 文件 read readline write
	f = open('poem.txt', 'r')
	while True:
		line = f.readline()
		if len(line) == 0:
			break


2): pickle
使用該模塊你可以將任意對象存儲在文件中,之後你又可以將其完整地取出來。這被稱爲
持久地存儲對象。

pickle.dump() 
pickle.load()




14:異常


1): try except
	try:
 		text = input('Enter something --> ')
 	except EOFError:
 		print('Why did you do an EOF on me?')
	except KeyboardInterrupt:
		print('You cancelled the operation.')
	else:
		print('You entered {0}'.format(text))


2): 自定義異常(繼承 Exception)
class ShortInputException(Exception):


3): raise 拋出異常 (throws)
	class ShortInputException(Exception):
    		def __init__(self, length, atleast):
        		self.length = length
        		self.atleast = atleast


	try:
   		 text = input('Enter something-->')
   		 if len(text) < 3:
      			 raise ShortInputException(len(text), 3)
	except EOFError:
    		print('Why did you do an EOF on me?')
	except ShortInputException as ex:
    		print('ShortInputException the input was {0} long, excepted at least {1}'
         		 .format( ex.length, ex.atleast))
	else:
   		print('NO exception was raise')


4): try except finally
5): with 語句 ( finally : f.close() )

	with open('poem.txt', 'r') as f:
   		 for line in f:
      			print(line, end = ' ')






16.更多內容


1): 函數放回元祖(一起返回兩個元素)
	def get_err_info():
		return (2, 'second err info')
	errnum, errstr = get_err_info()
	print(errnum, errstr)


1.2): 兩個變量一起定義時,列表 * 的使用
	a, *b = [1,2,3,4]
	print('a:',a)
	print('b:',b)


1.3): 兩個變量互換
	print('a和b交換:')
	a, b = b, a
	print('a:',a)
	print('b:',b)

1.4):特殊方法


3): lambda
(lambda 語句用來創建函數對象。本質上, lambda 需要一個參數,後面僅跟單個表達式作爲函數體,
  而表達式的值被這個新建的函數返回。)
def make_reapter(n):
	return lambda s: s*n
twice = make_reapter(2)
>>>print( twice(4) )
8
>>>print( twice('lambda: twice!') )
lambda: twice!lambda: twice!

4): 列表綜合

listone = [1, 2, 3, 4, 5, 6]
listtwo = [2*i for i in listone if i > 2]
>>>print(listtwo)
[6, 8, 10, 12]

5): 在函數參數中接受元祖(*)和字典(**)
def powersum(power, *args):
	total = 0
	for i in args:
		total += pow(i, power)
	return total
>>>print( powersum(2, 3, 4) )
25
>>>print( powersum(2, 10) )
100

6): exec 和 eval 語句

>>>exec( 'print("hello world!")' )
hello world!
>>>print( eval('2*3') )
7): assert 斷言語句:
>>>mylist = ['item']
>>>assert len(mylist) > 1
>>>mylist.pop()
AssertionError


8): repr 函數(repr 函數用來獲取對象的可打印的表示形式 eval( repr(object)) )== object

>>>newlist = ['item']
>>>newlist
['item']
>>>repr(newlist)
"['item']"
>>>eval( repr(newlist) )
['item']



發佈了23 篇原創文章 · 獲贊 9 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章