下面是你要寫(xiě)又一個(gè) python 腳本,這節(jié)練習(xí)會(huì)向你介紹“if 語(yǔ)句”。把這段代碼輸入腳本,讓它正常運(yùn)行,看看你有沒(méi)有什么收獲。
people = 20
cats = 30
dogs = 15
if people < cats:
print "Too many cats! The world is doomed!"
if people > cats:
print "Not many cats! The world is saved!"
if people < dogs:
print "The world is drooled on!"
if people > dogs:
print "The world is dry!"
dogs += 5
if people >= dogs:
print "People are greater than or equal to dogs."
if people <= dogs:
print "People are less than or equal to dogs."
if people == dogs:
print "People are dogs."
$ python ex29.py
Too many cats! The world is doomed!
The world is dry!
People are greater than or equal to dogs.
People are less than or equal to dogs.
People are dogs.
猜猜“if 語(yǔ)句”是什么,它有什么用處。在做下一道習(xí)題前,試著自己回答下面的問(wèn)題:
1.你認(rèn)為 if 對(duì)于它下一行的代碼做了什么? 2.為什么 if 語(yǔ)句的下一行需要縮進(jìn)? 3.如果不縮進(jìn),會(huì)怎樣? 4.把習(xí)題 27 中的其它布爾表達(dá)式放到 if 語(yǔ)句中能不能運(yùn)行呢?試一下。 5.如果把變量 people, cats, 和 dogs 的初始值改掉,會(huì)怎樣?
代碼 x += 1 和 x = x + 1 實(shí)現(xiàn)的是一樣的功能,但是可以少輸入一些字符。你可以稱(chēng)之為“增量”操作符。-= 也是相同的,后面你會(huì)看到更多的相關(guān)解釋。