Python 筆記

1. Python的hello-world:

print ("Hello, Python!")缭乘、

完了 搖就完事兒了·

2. Python怎么表達程序塊:

不需要{}捏雌,用不同的換行表示


像這樣

3. Python如何表示多行語句:

如果正常語句要換行:

后面加\ ? ? ? ? ? ? ?像這樣:


如果是【】之類的括號里面的不需要加\

4. Python怎么引用外界的東西:

單詞用一個‘ ? ? ? ? ? ? ’

句子用兩個‘’ ? ? ? ? ? ? ? ?‘’

段落用三個‘’‘ ? ? ? ? ? ? ? ’‘’

5. Python如何添加注釋:

用#后面接東西

Python不支持多行注釋

所以得一行一個#

6. 創(chuàng)建空白行:

/n植袍, 空白行在程序里不識別

7. 讓程序等待用戶操作:

input("\n\nPress the enter key to exit.")

可以把程序窗口保持直到用戶輸入指定按鍵

8. 干什么的稿黍?沒懂

9. options.py:

#!/usr/bin/python3

import sys, getopt

def main(argv):

inputfile = ''

outputfile = ''

try:

opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])

except getopt.GetoptError:

print ('test.py -i -o ')

sys.exit(2)

for opt, arg in opts:

if opt == '-h':

print ('test.py -i -o ')

sys.exit()

elif opt in ("-i", "--ifile"):

inputfile = arg

elif opt in ("-o", "--ofile"):

outputfile = arg

print ('Input file is "', inputfile)

print ('Output file is "', outputfile)

if __name__ == "__main__":

main(sys.argv[1:])


運行如下:

$ test.py -h

usage: test.py -i -o

$ test.py -i BMP -o

usage: test.py -i -o

$ test.py -i inputfile -o outputfile

Input file is " inputfile

Output file is " outputfile

10. 變量定義:

vars.py

#!/usr/bin/python3

counter = 100 # An integer assignment

miles = 1000.0 # A floating point

name = "John" # A string

print (counter)

print (miles)

print (name)

11. 對string進行運算:

#!/usr/bin/python3

str = 'Hello World!'

print (str) # Prints complete string

print (str[0]) # Prints first character of the string

print (str[2:5]) # Prints characters starting from 3rd to 5th

print (str[2:]) # Prints string starting from 3rd character

print (str * 2) # Prints string two times

print (str + "TEST") # Prints concatenated string

12. python組件:list(可修改)

提取組件內(nèi)信息:

#!/usr/bin/python3

list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]

tinylist = [123, 'john']

print (list) # Prints complete list

print (list[0]) # Prints first element of the list

print (list[1:3]) # Prints elements starting from 2nd till 3rd

print (list[2:]) # Prints elements starting from 3rd element

print (tinylist * 2) # Prints list two times

print (list + tinylist) # Prints concatenated lists

*為什么給出的答案里面有很多位小數(shù)

13. python組件:tuple(元組):不可修改

#!/usr/bin/python3

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )

tinytuple = (123, 'john')

print (tuple) # Prints complete tuple

print (tuple[0]) # Prints first element of the tuple

print (tuple[1:3]) # Prints elements starting from 2nd till 3rd

print (tuple[2:]) # Prints elements starting from 3rd element

print (tinytuple * 2) # Prints tuple two times

print (tuple + tinytuple) # Prints concatenated tuple

14. python組件:字典(dict)

#!/usr/bin/python3

dict = {}

dict['one'] = "This is one"

dict[2] = "This is two"

tinydict = {'name': 'john','code':6734, 'dept': 'sales'}

print (dict['one']) # Prints value for 'one' key

print (dict[2]) # Prints value for 2 key

print (tinydict) # Prints complete dictionary

print (tinydict.keys()) # Prints all the keys

print (tinydict.values()) # Prints all the values

15. python基本運算:

#!/usr/bin/python3

a = 21

b = 10

c = 0

c = a + b

print ("Line 1 - Value of c is ", c)

c = a - b

print ("Line 2 - Value of c is ", c )

c = a * b

print ("Line 3 - Value of c is ", c)

c = a / b

print ("Line 4 - Value of c is ", c )

c = a % b

print ("Line 5 - Value of c is ", c)

a = 2

b = 3

c = a**b

print ("Line 6 - Value of c is ", c)

a = 10

b = 5

c = a//b

print ("Line 7 - Value of c is ", c)

16. python二元運算(比較等)

#!/usr/bin/python3

a = 21

b = 10

if ( a == b ):

print ("Line 1 - a is equal to b")

else:

print ("Line 1 - a is not equal to b")

if ( a != b ):

print ("Line 2 - a is not equal to b")

else:

print ("Line 2 - a is equal to b")

if ( a < b ):

print ("Line 3 - a is less than b" )

else:

print ("Line 3 - a is not less than b")

if ( a > b ):

print ("Line 4 - a is greater than b")

else:

print ("Line 4 - a is not greater than b")

a,b=b,a #values of a and b swapped. a becomes 10, b becomes 21

if ( a <= b ):

print ("Line 5 - a is either less than or equal to b")

else:

print ("Line 5 - a is neither less than nor equal to b")

if ( b >= a ):

print ("Line 6 - b is either greater than or equal to b")

else:

print ("Line 6 - b is neither greater than nor equal to b")

17. 其他運算:

#!/usr/bin/python3

a = 21

b = 10

c = 0

c = a + b

print ("Line 1 - Value of c is ", c)

c += a

print ("Line 2 - Value of c is ", c )

c *= a

print ("Line 3 - Value of c is ", c )

c /= a

print ("Line 4 - Value of c is ", c )

c = 2

c %= a

print ("Line 5 - Value of c is ", c)

c **= a

print ("Line 6 - Value of c is ", c)

c //= a

print ("Line 7 - Value of c is ", c)

*其中:%是取余數(shù)運算镣衡;**是求冪次方運算,//是返回商的整數(shù)部分

18. 對數(shù)字背后8位碼的運算:

#!/usr/bin/python3

a = 60 # 60 = 0011 1100

b = 13 # 13 = 0000 1101

print ('a=',a,':',bin(a),'b=',b,':',bin(b))

c = 0

c = a & b; # 12 = 0000 1100

print ("result of AND is ", c,':',bin(c))

c = a | b; # 61 = 0011 1101

print ("result of OR is ", c,':',bin(c))

c = a ^ b; # 49 = 0011 0001

print ("result of EXOR is ", c,':',bin(c))

c = ~a; # -61 = 1100 0011

print ("result of COMPLEMENT is ", c,':',bin(c))

c = a << 2; # 240 = 1111 0000

print ("result of LEFT SHIFT is ", c,':',bin(c))

c = a >> 2; # 15 = 0000 1111

print ("result of RIGHT SHIFT is ", c,':',bin(c))

比特位運算符:

& Binary AND Operator copies a bit to the result, if it exists in both operands(a & b) (means 0000 1100)

| Binary OR It copies a bit, if it exists in either operand.(a | b) = 61 (means 0011 1101)

^ Binary XOR It copies the bit, if it is set in one operand but not both.(a ^ b) = 49 (means 0011 0001)

~ Binary Ones ComplementIt is unary and has the effect of 'flipping' bits.(~a ) = -61 (means 1100 0011 in 2's complement form due to a signed binary number.

<< Binary Left Shift The left operand’s value is moved left by the number of bits specified by the right operand.a << = 240 (means 1111 0000)

>> Binary Right Shift The left operand’s value is moved right by the number of bits specified by the right operand.a >> = 15 (means 0000 1111)

19. in和notin運算符:

#!/usr/bin/python3

a = 10

b = 20

list = [1, 2, 3, 4, 5 ]

if ( a in list ):

print ("Line 1 - a is available in the given list")

else:

print ("Line 1 - a is not available in the given list")

if ( b not in list ):

print ("Line 2 - b is not available in the given list")

else:

print ("Line 2 - b is available in the given list")

c=b/a

if ( c in list ):

print ("Line 3 - a is available in the given list")

else:

print ("Line 3 - a is not available in the given list")

20. is和isnot運算符

#!/usr/bin/python3

a = 20

b = 20

print ('Line 1','a=',a,':',id(a), 'b=',b,':',id(b))

if ( a is b ):

print ("Line 2 - a and b have same identity")

else:

print ("Line 2 - a and b do not have same identity")

if ( id(a) == id(b) ):

print ("Line 3 - a and b have same identity")

else:

print ("Line 3 - a and b do not have same identity")

b = 30

print ('Line 4','a=',a,':',id(a), 'b=',b,':',id(b))

if ( a is not b ):

print ("Line 5 - a and b do not have same identity")

else:

print ("Line 5 - a and b have same identity")

21. 運算符優(yōu)先級的例子:

#!/usr/bin/python3

a = 20

b = 10

c = 15

d = 5

print ("a:%d b:%d c:%d d:%d" % (a,b,c,d ))

e = (a + b) * c / d #( 30 * 15 ) / 5

print ("Value of (a + b) * c / d is ", e)

e = ((a + b) * c) / d # (30 * 15 ) / 5

print ("Value of ((a + b) * c) / d is ", e)

e = (a + b) * (c / d) # (30) * (15/5)

print ("Value of (a + b) * (c / d) is ", e)

e = a + (b * c) / d # 20 + (150/5)

print ("Value of a + (b * c) / d is ", e)

22. if語句:

#!/usr/bin/python3

var1 = 100

if var1:

print ("1 - Got a true expression value")

print (var1)

var2 = 0

if var2:

print ("2 - Got a true expression value")

print (var2)

print ("Good bye!")

23. if-else-循環(huán)

#!/usr/bin/python3

amount=int(input("Enter amount: "))

if amount<1000:

discount=amount*0.05

print ("Discount",discount)

else:

discount=amount*0.10

print ("Discount",discount)

print ("Net payable:",amount-discount)

24. elseif語句:elif

#!/usr/bin/python3

amount=int(input("Enter amount: "))

if amount<1000:

discount=amount*0.05

print ("Discount",discount)

elif amount<5000:

discount=amount*0.10

print ("Discount",discount)

else:

discount=amount*0.15

print ("Discount",discount)

print

("Net payable:",amount-discount)

25. 嵌套if-else:

# !/usr/bin/python3

num=int(input("enter number"))

if num%2==0:

if num%3==0:

print ("Divisible by 3 and 2")

else:

print ("divisible by 2 not divisible by 3")

else:

if num%3==0:

print ("divisible by 3 not divisible by 2")

else:

print ("not Divisible by 2 not divisible by 3")

26. if語句結(jié)果只有一行--可以寫在同一行

#!/usr/bin/python3

var = 100

if ( var == 100 ) : print ("Value of expression is 100")

print ("Good bye!")

27. while循環(huán):

#!/usr/bin/python3

var = 1

while var == 1 : # This constructs an infinite loop

num = int(input("Enter a number :"))

print ("You entered: ", num)

print ("Good bye!")

28. 在while循環(huán)里添加else跳出:

#!/usr/bin/python3

count = 0

while count < 5:

print (count, " is less than 5")

count = count + 1

else:

print (count, " is not less than 5")

29. range函數(shù):

a = range(5)

print(a)

a=list(range(5))

print(a)

for var in list(range(5)): print (var)

30. for循環(huán):

#!/usr/bin/python3

for letter in 'Python': # traversal of a string sequence

print ('Current Letter :', letter)

print()

fruits= ['banana', 'apple', 'mango']

for fruit in fruits: # traversal of List sequence

print ('Current fruit :', fruit)

print ("Good bye!")

31. 利用index遍歷:

#!/usr/bin/python3

fruits = ['banana', 'apple', 'mango']

for index in range(len(fruits)):

print ('Current fruit :', fruits[index])

print ("Good bye!")

32. 在for循環(huán)中插入if-else判定:

#!/usr/bin/python3

numbers=[11,33,55,39,55,75,37,21,23,41,13]

for num in numbers:

if num%2==0:

print ('the list contains an even number')

break

else:

print ('the list doesnot contain even number')

33. 嵌套循環(huán):

遍歷10-10乘法表

#!/usr/bin/python3

import sys

for i in range(1,11):

for j in range(1,11):

k=i*j

print (k, end=' ')

print()

為什么是1-11:

34. 利用break跳出循環(huán):

#!/usr/bin/python3

for letter in 'Python': # First Example

if letter == 'h':

break

print ('Current Letter :', letter)

var = 10 # Second Example

while var > 0:

print ('Current variable value :', var)

var = var -1

if var == 5:

break

print ("Good bye!")

35. 利用for-else跳出循環(huán)

#!/usr/bin/python3

no=int(input('any number: '))

numbers=[11,33,55,39,55,75,37,21,23,41,13]

for num in numbers:

if num==no:

print ('number found in list')

break

else:

print ('number not found in list')

36. continue語句:

#!/usr/bin/python3

for letter in 'Python': # First Example

if letter == 'h':

continue

print ('Current Letter :', letter)

var = 10 # Second Example

while var > 0:

var = var -1

if var == 5:

continue

print ('Current variable value :', var)

print ("Good bye!")

37. ceil():向上取整

#!/usr/bin/python3

import math # This will import math module

print ("math.ceil(-45.17) : ", math.ceil(-45.17))

print ("math.ceil(100.12) : ", math.ceil(100.12))

print ("math.ceil(100.72) : ", math.ceil(100.72))

print ("math.ceil(math.pi) : ", math.ceil(math.pi))

38. exp():指數(shù)次方

#!/usr/bin/python3

import math # This will import math module

print ("math.exp(-45.17) : ", math.exp(-45.17))

print ("math.exp(100.12) : ", math.exp(100.12))

print ("math.exp(100.72) : ", math.exp(100.72))

print ("math.exp(math.pi) : ", math.exp(math.pi))

39. fabs():絕對值

#!/usr/bin/python3

import math # This will import math module

print ("math.fabs(-45.17) : ", math.fabs(-45.17))

print ("math.fabs(100.12) : ", math.fabs(100.12))

print ("math.fabs(100.72) : ", math.fabs(100.72))

print ("math.fabs(math

.pi) : ", math.fabs(math.pi))

40. floor():向下取整

#!/usr/bin/python3

import math # This will import math module

print ("math.floor(-45.17) : ", math.floor(-45.17))

print ("math.floor(100.12) : ", math.floor(100.12))

print ("math.floor(100.72) : ", math.floor(100.72))

print ("math.floor(math.pi) : ", math.floor(math.pi))

42.獲取字符串中的信息:

#!/usr/bin/python3

var1 = 'Hello World!'

var2 = "Python Programming"

print ("var1[0]: ", var1[0])

print ("var2[1:5]: ", var2[1:5])

43. 對字符串進行修改:

#!/usr/bin/python3

var1 = 'Hello World!'

print ("Updated String :- ", var1[:6] + 'Python')

44. 字符串格式化嗤放?

#!/usr/bin/python3

var1 = 'Hello World!'

print ("Updated String :- ", var1[:6] + 'Python')

45. 三引號:

可以保留格式思喊?

#!/usr/bin/python3

para_str = """this is a long string that is made up of

several lines and non-printable characters such as

TAB ( \t ) and they will show up that way when displayed.

NEWLINEs within the string, whether explicitly given like

this within the brackets [ \n ], or just a NEWLINE within

the variable assignment will also show up.

"""

print (para_str)

46. raw-string:功能存疑

#!/usr/bin/python3

print ('C:\\nowhere')

print (r'C:\\nowhere')

47. capitalize():首字母大寫

#!/usr/bin/python3

str = "this is string example....wow!!!"

print ("str.capitalize() : ", str.capitalize())

48. 訪問list里的值:

#!/usr/bin/python3

list1 = ['physics', 'chemistry', 1997, 2000]

list2 = [1, 2, 3, 4, 5, 6, 7 ]

print ("list1[0]: ", list1[0])

print ("list2[1:5]: ", list2[1:5])

49. 修改list:

#!/usr/bin/python3

list1 = ['physics', 'chemistry', 1997, 2000]

list2 = [1, 2, 3, 4, 5, 6, 7 ]

print ("list1[0]: ", list1[0])

print ("list2[1:5]: ", list2[1:5])

50. 刪除list:”

#!/usr/bin/python3

list = ['physics', 'chemistry', 1997, 2000]

print (list)

del list[2]

print ("After deleting value at index 2 : ", list)

51. max():返回最大值(首字母/數(shù)字)

#!/usr/bin/python3

list1, list2 = ['C++','Java', 'Python'], [456, 700, 200]

print ("Max value element : ", max(list1))

print ("Max value element : ", max(list2))

52.list():把tuple轉(zhuǎn)化為list

#!/usr/bin/python3

aTuple = (123, 'C++', 'Java', 'Python')

list1 = list(aTuple)

print ("List elements : ", list1)

str="Hello World"

list2=list(str)

print ("List elements : ", list2)

53. append:向list里添加元素

#!/usr/bin/python3

list1 = ['C++', 'Java', 'Python']

list1.append('C#')

print ("updated list : ", list1)

54. count():對list里的目標元素計數(shù)

#!/usr/bin/python3

aList = [123, 'xyz', 'zara', 'abc', 123];

print ("Count for 123 : ", aList.count(123))

print ("Count for zara : ", aList.count('zara'))

55. pop():從list中剔除/什么方式里面的元素?

#!/usr/bin/python3

list1 = ['physics', 'Biology', 'chemistry', 'maths']

list1.pop()

print ("list now : ", list1)

list1.pop(1)

print ("list now : ", list1)

56. remove():從list里刪除指定元素

#!/usr/bin/python3

list1 = ['physics', 'Biology', 'chemistry', 'maths']

list1.remove('Biology')

print ("list now : ", list1)

list1.remove('maths')

print ("list now : ", list1)

57. reverse():對list內(nèi)順序進行顛倒

#!/usr/bin/python3

list1 = ['physics', 'Biology', 'chemistry', 'maths']

list1.reverse()

print ("list now : ", list1)

58. sort():對list里元素排序

#!/usr/bin/python3

list1 = ['physics', 'Biology', 'chemistry', 'maths']

list1.sort()

print ("list now : ", list1)

59. 調(diào)用tuple里的信息

#!/usr/bin/python3

tup1 = ('physics', 'chemistry', 1997, 2000)

tup2 = (1, 2, 3, 4, 5, 6, 7 )

print ("tup1[0]: ", tup1[0])

print ("tup2[1:5]: ", tup2[1:5])

60. tuple不能修改次酌,但可以調(diào)用現(xiàn)有的tuple注入到新的tuple里進行類似修改的重新賦值:

#!/usr/bin/python3

tup1 = (12, 34.56)

tup2 = ('abc', 'xyz')

# Following action is not valid for tuples

# tup1[0] = 100;

# So let's create a new tuple as follows

tup3 = tup1 + tup2

print (tup3)

61. len(): 對tuple進行計數(shù)

#!/usr/bin/python3

tuple1, tuple2 = (123, 'xyz', 'zara'), (456, 'abc')

print ("First tuple length : ", len(tuple1))

print ("Second tuple length : ", len(tuple2))

62. max():返回數(shù)組中的最大值

#!/usr/bin/python3

tuple1, tuple2 = ('maths', 'che', 'phy', 'bio'), (456, 700, 200)

print ("Max value element : ", max(tuple1))

print ("Max value element : ", max(tuple2))

63. tuple():把list轉(zhuǎn)化為tuple

#!/usr/bin/python3

list1= ['maths', 'che', 'phy', 'bio']

tuple1=tuple(list1)

print ("tuple elements : ", tuple1)

64. 對字典里的數(shù)進行訪問

#!/usr/bin/python3

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}

print ("dict['Name']: ", dict['Name'])

print ("dict['Age']: ", dict['Age'])

65. 更新dict里的內(nèi)容

#!/usr/bin/python3

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}

dict['Age'] = 8; # update existing entry

dict['School'] = "DPS School" # Add new entry

print ("dict['Age']: ", dict['Age'])

print ("dict['School']: ", dict['School'])

66. 刪除字典里的信息

#!/usr/bin/python3

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}

del dict['Name'] # remove entry with key 'Name'

dict.clear() # remove all entries in dict

del dict # delete entire dictionary

print ("dict['Age']: ", dict['Age'])

print ("dict['School']: ", dict['School'])

67. dict內(nèi)容沒有限制:

#!/usr/bin/python3

dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'}

print ("dict['Name']: ", dict['Name'])

68. str():把字典字符化

#!/usr/bin/python3

dict = {'Name': 'Manni', 'Age': 7, 'Class': 'First'}

print ("Equivalent String : %s" % str (dict))

69. type()返回字典內(nèi)的數(shù)據(jù)類型:

#!/usr/bin/python3

dict = {'Name': 'Manni', 'Age': 7, 'Class': 'First'}

print ("Variable Type : %s" % type (dict))

70. clear()清空字典

dict = {'Name': 'Zara', 'Age': 7}

print ("Start Len : %d" % len(dict))

dict.clear()

print ("End Len : %d" % len(dict))

71. copy()從字典中copy信息:

#!/usr/bin/python3

dict1 = {'Name': 'Manni', 'Age': 7, 'Class': 'First'}

dict2 = dict1.copy()

print ("New Dictionary : ",dict2)

72. fromkeys()從原字典中拿出值和類型構(gòu)成一個新字典

#!/usr/bin/python3

seq = ('name', 'age', 'sex')

dict = dict.fromkeys(seq)

print ("New Dictionary : %s" % str(dict))

dict = dict.fromkeys(seq, 10)

print ("New Dictionary : %s" % str(dict))

73. items()返回(key value)類型

#!/usr/bin/python

dict = {'Name': 'Zara', 'Age': 7}

print ("Value : %s" % dict.items())

74. keys()返回(字典里所有的0key)

#!/usr/bin/python3

dict = {'Name': 'Zara', 'Age': 7}

print ("Value : %s" % dict.keys())

75.?setdefault()方法類似于get()

#!/usr/bin/python3

dict = {'Name': 'Zara', 'Age': 7}

print ("Value : %s" % dict.setdefault('Age', None))

print ("Value : %s" % dict.setdefault('Sex', None))

print (dict)

76. tick()好像是獲得時間的函數(shù)(不確定)

#!/usr/bin/python3

import time; # This is required to include time module.

ticks = time.time()

print ("Number of ticks since 12:00am, January 1, 1970:", ticks)

時間間隔是以秒為單位的浮點數(shù)恨课。 從1970年1月1日上午12:00(epoch),這是一種時間的特殊時刻表示岳服。

在Python中剂公,當前時刻與上述特殊的某個時間點之間以秒為單位的時間。這個時間段叫做Ticks吊宋。

77. clock()時鐘函數(shù)

#!/usr/bin/python3

import time

def procedure():

time.sleep(2.5)

# measure process time

t0 = time.clock()

procedure()

print (time.clock() - t0, "seconds process time")

# measure wall time

t0 = time.time()

procedure()

print (time.time() - t0, "seconds wall time")

Python time clock() 函數(shù)以浮點數(shù)計算的秒數(shù)返回當前的CPU時間纲辽。用來衡量不同程序的耗時,比time.time()更有用璃搜。

這個需要注意拖吼,在不同的系統(tǒng)上含義不同。在UNIX系統(tǒng)上这吻,它返回的是"進程時間"绿贞,它是用秒表示的浮點數(shù)(時間戳)。而在WINDOWS中橘原,第一次調(diào)用,返回的是進程運行的實際時間涡上。而第二次之后的調(diào)用是自第一次調(diào)用以后到現(xiàn)在的運行時間趾断。(實際上是以WIN32上QueryPerformanceCounter()為基礎(chǔ),它比毫秒表示更為精確)


78.?如何定義函數(shù)

#!/usr/bin/python3

# Function definition is here

def printme( str ):

"This prints a passed string into this function"

print (str)

return

# Now you can call printme function

printme("This is first call to the user defined function!")

printme("Again second call to the same function")

79. 參數(shù)通過reference傳遞

#!/usr/bin/python3

# Function definition is here

def changeme( mylist ):

"This changes a passed list into this function"

print ("Values inside the function before change: ", mylist)

mylist[2]=50

print ("Values inside the function after change: ", mylist)

return

# Now you can call changeme function

mylist = [10,20,30]

changeme( mylist )

print ("Values outside the function: ", mylist)

80. 例子2

#!/usr/bin/python3

# Function definition is here

def changeme( mylist ):

"This changes a passed list into this function"

mylist = [1,2,3,4] # This would assi new reference in mylist

print ("Values inside the function: ", mylist)

return

# Now you can call changeme function

mylist = [10,20,30]

changeme( mylist )

print ("Values outside the function: ", mylist)

81. 函數(shù)外給參數(shù)賦值:

#!/usr/bin/python3

# Function definition is here

def printinfo( name, age ):

"This prints a passed info into this function"

print ("Name: ", name)

print ("Age ", age)

return

# Now you can call printinfo function

printinfo( age=50, name="miki" )

82.默認給參數(shù)賦值:

?#!/usr/bin/python3

# Function definition is here

def printinfo( name, age = 35 ):

"This prints a passed info into this function"

print ("Name: ", name)

print ("Age ", age)

return

# Now you can call printinfo function

printinfo( age=50, name="miki" )

printinfo( name="miki" )

83. 針對asterisk吩愧?的賦值和調(diào)用

#!/usr/bin/python3

# Function definition is here

def printinfo( arg1, *vartuple ):

"This prints a variable passed arguments"

print ("Output is: ")

print (arg1)

for var in vartuple:

print (var)

return

# Now you can call printinfo function

printinfo( 10 )

printinfo( 70, 60, 50 )

84. lambda:

ambda 定義了一個匿名函數(shù)

  lambda 并不會帶來程序運行效率的提高芋酌,只會使代碼更簡潔。

  如果可以使用for...in...if來完成的雁佳,堅決不用lambda脐帝。

  如果使用lambda,lambda內(nèi)不要包含循環(huán)糖权,如果有堵腹,我寧愿定義函數(shù)來完成,使代碼獲得可重用性和更好的可讀性星澳。

  總結(jié):lambda 是為了減少單行函數(shù)的定義而存在的疚顷。

#!/usr/bin/python3

# Function definition is here

sum = lambda arg1, arg2: arg1 + arg2

# Now you can call sum as a function

print ("Value of total : ", sum( 10, 20 ))

print ("Value of total : ", sum( 20, 20 ))

85. return語句:

#!/usr/bin/python3

# Function definition is here

def sum( arg1, arg2 ):

# Add both the parameters and return them."

total = arg1 + arg2

print ("Inside the function : ", total)

return total

# Now you can call sum function

total = sum( 10, 20 )

print ("Outside the function : ", total )

86. global和local變量的區(qū)別

#!/usr/bin/python3

total = 0 # This is global variable.

# Function definition is here

def sum( arg1, arg2 ):

# Add both the parameters and return them."

total = arg1 + arg2; # Here total is local variable.

print ("Inside the function local total : ", total)

return total

# Now you can call sum function

sum( 10, 20 )

print ("Outside the function global total : ", total )

87. module:規(guī)范的程序塊

def print_func( par ):

? ? print ("Hello : ", par)

? ? return

88. import關(guān)鍵字:

#!/usr/bin/python3

# Import module support

import support

# Now you can call defined function that module as follows

support.print_func("Zara")

89. 另一種斐波那契數(shù)列的寫法:

#!/usr/bin/python3

# Fibonacci numbers module

def fib(n): # return Fibonacci series up to n

result = []

a, b = 0, 1

while b < n:

result.append(b)

a, b = b, a+b

return result

>>> from fib import fib

>>> fib(100)

90. dir用法:

#!/usr/bin/python3

# Import built-in module math

import math

content = dir(math)

print (content)

91. 打開文件:

#!/usr/bin/python3

# Open a file

fo = open("foo.txt", "wb")

print ("Name of the file: ", fo.name)

print ("Closed or not : ", fo.closed)

print ("Opening mode : ", fo.mode)

fo.close()

92. write-file方法

#!/usr/bin/python3

# Open a file

fo = open("foo.txt", "w")

fo.write( "Python is a great language.\nYeah its great!!\n")

# Close opend file

fo.close()

93. read-file方法

#!/usr/bin/python3

# Open a file

fo = open("foo.txt", "r+")

str = fo.read(10)

print ("Read String is : ", str)

# Close opened file

fo.close()

94. tell()查詢文件位置

# Open a file

fo = open("foo.txt", "r+")

str = fo.read(10)

print ("Read String is : ", str)

# Check current position

position = fo.tell()

print ("Current file position : ", position)

# Reposition pointer at the beginning once again

position = fo.seek(0, 0)

str = fo.read(10)

print ("Again read String is : ", str)

# Close opened file

fo.close()

95. fileno()方法--

#!/usr/bin/python3

# Open a file

fo = open("foo.txt", "wb")

print ("Name of the file: ", fo.name)

fid = fo.fileno()

print ("File Descriptor: ", fid)

# Close opend file

fo.close()

96. isatty():如果文件連接(與終端設(shè)備相關(guān)聯(lián))到tty(類似)設(shè)備,則此方法返回true,否則返回false腿堤。

#!/usr/bin/python3

# Open a file

fo = open("foo.txt", "wb")

print ("Name of the file: ", fo.name)

ret = fo.isatty()

print ("Return value : ", ret)

# Close opend file

fo.close()

97. next()

#!/usr/bin/python3

# Open a file

fo = open("foo.txt", "r")

print ("Name of the file: ", fo.name)

for index in range(5):

line = next(fo)

print ("Line No %d - %s" % (index, line))

# Close opened file

fo.close()

98. readline函數(shù)

#!/usr/bin/python3

# Open a file

fo = open("foo.txt", "r+")

print ("Name of the file: ", fo.name)

line = fo.read(10)

print ("Read Line: %s" % (line))

# Close opened file

fo.close()

99. 另一個readline函數(shù):

#!/usr/bin/python3

# Open a file

fo = open("foo.txt", "r+")

print ("Name of the file: ", fo.name)

line = fo.readline()

print ("Read Line: %s" % (line))

line = fo.readline(5)

print ("Read Line: %s" % (line))

# Close opened file

fo.close()

100. 令另一個readline函數(shù):

#!/usr/bin/python3

# Open a file

fo = open("foo.txt", "r+")

print ("Name of the file: ", fo.name)

line = fo.readlines()

print ("Read Line: %s" % (line))

line = fo.readlines(2)

print ("Read Line: %s" % (line))

# Close opened file

fo.close()

101. access方法:

#!/usr/bin/python3

import os, sys

# Assuming /tmp/foo.txt exists and has read/write permissions.

ret = os.access("/tmp/foo.txt", os.F_OK)

print ("F_OK - return value %s"% ret)

ret = os.access("/tmp/foo.txt", os.R_OK)

print ("R_OK - return value %s"% ret)

102.?

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末阀坏,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子笆檀,更是在濱河造成了極大的恐慌忌堂,老刑警劉巖,帶你破解...
    沈念sama閱讀 206,126評論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件酗洒,死亡現(xiàn)場離奇詭異士修,居然都是意外死亡,警方通過查閱死者的電腦和手機寝蹈,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,254評論 2 382
  • 文/潘曉璐 我一進店門李命,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人箫老,你說我怎么就攤上這事封字。” “怎么了耍鬓?”我有些...
    開封第一講書人閱讀 152,445評論 0 341
  • 文/不壞的土叔 我叫張陵阔籽,是天一觀的道長。 經(jīng)常有香客問我牲蜀,道長笆制,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 55,185評論 1 278
  • 正文 為了忘掉前任涣达,我火速辦了婚禮在辆,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘度苔。我一直安慰自己匆篓,他們只是感情好,可當我...
    茶點故事閱讀 64,178評論 5 371
  • 文/花漫 我一把揭開白布寇窑。 她就那樣靜靜地躺著鸦概,像睡著了一般。 火紅的嫁衣襯著肌膚如雪甩骏。 梳的紋絲不亂的頭發(fā)上窗市,一...
    開封第一講書人閱讀 48,970評論 1 284
  • 那天,我揣著相機與錄音饮笛,去河邊找鬼咨察。 笑死,一個胖子當著我的面吹牛福青,可吹牛的內(nèi)容都是我干的扎拣。 我是一名探鬼主播,決...
    沈念sama閱讀 38,276評論 3 399
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼二蓝!你這毒婦竟也來了誉券?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 36,927評論 0 259
  • 序言:老撾萬榮一對情侶失蹤刊愚,失蹤者是張志新(化名)和其女友劉穎踊跟,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體鸥诽,經(jīng)...
    沈念sama閱讀 43,400評論 1 300
  • 正文 獨居荒郊野嶺守林人離奇死亡商玫,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 35,883評論 2 323
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了牡借。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片拳昌。...
    茶點故事閱讀 37,997評論 1 333
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖钠龙,靈堂內(nèi)的尸體忽然破棺而出炬藤,到底是詐尸還是另有隱情,我是刑警寧澤碴里,帶...
    沈念sama閱讀 33,646評論 4 322
  • 正文 年R本政府宣布沈矿,位于F島的核電站,受9級特大地震影響咬腋,放射性物質(zhì)發(fā)生泄漏羹膳。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 39,213評論 3 307
  • 文/蒙蒙 一根竿、第九天 我趴在偏房一處隱蔽的房頂上張望陵像。 院中可真熱鬧,春花似錦寇壳、人聲如沸蠢壹。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,204評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至蹂季,卻和暖如春冕广,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背偿洁。 一陣腳步聲響...
    開封第一講書人閱讀 31,423評論 1 260
  • 我被黑心中介騙來泰國打工撒汉, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人涕滋。 一個月前我還...
    沈念sama閱讀 45,423評論 2 352
  • 正文 我出身青樓睬辐,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子溯饵,可洞房花燭夜當晚...
    茶點故事閱讀 42,722評論 2 345

推薦閱讀更多精彩內(nèi)容

  • Python簡介 Python歷史 Python 是由 Guido van Rossum 在八十年代末和九十年代初...
    莫名其妙的一生閱讀 1,040評論 0 2
  • 基礎(chǔ)1.r''表示''內(nèi)部的字符串默認不轉(zhuǎn)義2.'''...'''表示多行內(nèi)容3. 布爾值:True侵俗、False(...
    neo已經(jīng)被使用閱讀 1,660評論 0 5
  • 1. 選教程 看到crossin的編程教室python教程還不錯。以這個為主要學習內(nèi)容丰刊。 python簡單實驗...
    青島大橋_Android到后端閱讀 563評論 0 0
  • 程序流程圖設(shè)計:先給出開始和結(jié)束框圖隘谣,在中間按照順序設(shè)計加入大致的程序流程框圖,然后再進行完善和補充(增刪和修改)...
    王詩翔閱讀 673評論 0 2
  • 夜靜悄悄的啄巧,只能聽到風吹過寻歧,菜葉子沙沙沙的響。 在這樣清爽的夜色里秩仆,籬笆架上的小豌豆花終于耐不住了寂寞码泛,輕輕地哼唱...
    一樹花開半樹林閱讀 686評論 0 1