python 學習第二天

1.程序交互模式:

raw_input("description")? ? ? ? ? -------------->引號中是可以輸出顯示的

2.格式化輸出相關內(nèi)容:

print "your name? is %s ,it is very smart"? % Name? ? ? ? ?(此處Name是一個變量)

%s? ?字符串? ? ? ? ?%d? 數(shù)字

3.條件判斷語句:

if age <= 6:

? ? print "child"

elif age <= 18:

? ? print "teenage"

elif age <=30:

? ? print "adult"

else :

? ? print "old"

根據(jù)不同的年齡段劃分不同的生命時間段

4.流程控制(判斷name是否為空如果為空繼續(xù)輸入,最多輸入三次,退出):

#n=0

#while? True:

for i in range(3):

? ?#n+=1

? ? name=raw_input("what is your name:").strip()

? ? if len(name) ==0:

? ? ? ? continue

? ? break

else :

? ? ? ?print? "loop is down"

循環(huán)控制for和while都是有else語句的,只有在執(zhí)行完循環(huán)結束之后會執(zhí)行else語句,如果for沒有執(zhí)行完是不執(zhí)行的。

5.range和xrange的區(qū)別:

range(start, stop[, step])? ? ? ? ? ?返回一個列表

range(2**2)? ? ? ? ? ?------------->? ?[0,1,2,3]

xrange(start, stop[, step])? ? ? ? ? ?一個生成器,大數(shù)據(jù)的時候會使用,在小數(shù)據(jù)時候和range相同?

xrange(2**2)? ? ? ? ? ? ? -------------->4? ? ? ? ? ? ? ?list(xrange(2**2)) ------------>? [0,1,2,3]?

6.文件操作

import os

f=file('/tmp/ceshi.txt','w')? ? --------->新建一個文件

f.write("ceshi1")? ? ? ? ? ? ?------------>文件中寫入ceshi1

f.close()? ? ? ? ? ? --------------->關閉文件

os.system("more /tmp/ceshi.txt")? ? ?---------------->查看文件內(nèi)容?

返回: ceshi1??

? ? ? ? ? ? ?0? ? ? ? ? ? ? ? ? ? ? ? ?------------------>通過os.system()調用shell命令

每次對文件操作完成之后就要關閉文件。

f1=file('/tmp/ceshi.txt','w')? ? ? ? ?------------>再次打開文件

f1.write("ceshi2")? ? ? ? ? ? ? -------------->再次寫入ceshi2

f1.close()

os.system("more /tmp/ceshi.txt")? ? ?---------------->查看文件內(nèi)容?

返回: ceshi2?

? ? ? ? ? ? ?0? ? ? ? ? ? ? ? ? -------------------->原先的內(nèi)容沒有了,原因打開文件的模式不對

文件打開模式:

w: 寫入? ? ? ? ? 如果存在此文件,覆蓋掉原先的內(nèi)容

a:? 追加模式? ?不存在的話會新建,存在的話會追加

r: 只讀模式? ? ? 對文件只有只讀權限

不使用os.system()調用shell命令讀取文件內(nèi)容

f2=file('/tmp/ceshi.txt')? ? ? ? ?------------>再次打開文件

f2.read()? ? ? ? ? ? ? --------------->查看文件中內(nèi)容

?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容