Python入門經典實例(二)

5 字符串

比起C/C++,Python處理字符串的方式實在太讓人感動了.把字符串當列表來用吧.

#! /usr/bin/python

word="abcdefg"

a=word[2]

print ("a is: "+a)

b=word[1:3]

print ("b is: "+b)

# index 1 and 2 elements of word.

c=word[:2]

print ("c is: "+c)

# index 0 and 1 elements of word.

d=word[0:]

print ("d is: "+d)

# All elements of word.

Python入門經典實例(二)

e=word[:2]+word[2:]

print ("e is: "+e) # All elements of word.

f=word[-1]

print ("f is: "+f) # The last elements of word.

g=word[-4:-2]

print ("g is: "+g) # index 3 and 4 elements of word.

h=word[-2:]

print ("h is: "+h) # The last two elements.

i=word[:-2]

print ("i is: "+i) # Everything except the last two characters

l=len(word)

print ("Length of word is: "+ str(l))

Python入門經典實例(二)

中文和英文的字符串長度是否一樣?

#! /usr/bin/python

# -*- coding: utf8 -*-

s=input("輸入你的中文名,按回車繼續");

print ("你的名字是 : " +s)

l=len(s)

print ("你中文名字的長度是:"+str(l

'''知識點:

· 類似Java,在python3裡所有字符串都是unicode,所以長度一致.

'''

Python入門經典實例(二)

6 條件和循環語句

#! /usr/bin/python

#條件和循環語句

x=int(input("Please enter an integer:"))

if x<0:

x=0

print ("Negative changed to zero")

elif x==0:

print ("Zero")

else:

print ("More")

# Loops List

a = ['cat', 'window', 'defenestrate']

for x in a:

print (x, len(x))

Python入門經典實例(二)

#知識點:

# * 條件和循環語句

# * 如何得到控制檯輸入

7 函數

#! /usr/bin/python

# -*- coding: utf8 -*-

def sum(a,b):

return a+b

func = sum

r = func(5,6)

print (r)

Python入門經典實例(二)

# 提供默認值

def add(a,b=2):

return a+b

r=add(1)

print (r)

r=add(1,5)

print (r)

Python入門經典實例(二)

#一個好用的函數

#! /usr/bin/python

# -*- coding: utf8 -*-

# The range() function

a =range (1,10)

for i in a:

print (i)

a = range(-2,-11,-3) # The 3rd parameter stands for step

for i in a:

print (i)


Python入門經典實例(二)

知識點:

· Python 不用{}來控制程序結構,他強迫你用縮進來寫程序,使代碼清晰.

· 定義函數方便簡單

· 方便好用的range函數

8 異常處理

#! /usr/bin/python

s=input("Input your age:")

if s =="":

raise Exception("Input must no be empty."

try:

i=int(s)

except Exception as err:

print(err)

finally: # Clean up action

print("Goodbye!")

Python入門經典實例(二)

9 文件處理

對比Java,python的文本處理再次讓人感動

#! /usr/bin/python

spath="D:/download/baa.txt"

f=open(spath,"w") # Opens file for writing.Creates this file doesn't exist.

f.write("First line 1.\n")

f.writelines("First line 2.")

f.close()

f=open(spath,"r") # Opens file for reading

for line in f:

print("每一行的數據是:%s"%line)

f.close()

Python入門經典實例(二)

知識點:

· open的參數:r表示讀,w寫數據,在寫之前先清空文件內容,a打開並附加內容.

· 打開文件之後記得關閉


分享到:


相關文章: