python IF 語句

2021-09-15 14:53 更新

練習(xí)29. IF 語句

下面是你要寫又一個(gè)python腳本,這節(jié)練習(xí)會(huì)向你介紹“if語句”。把這段代碼輸入腳本,讓它正常運(yùn)行,看看你有沒有什么收獲。

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."

你看到的結(jié)果

$ 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語句”是什么,它有什么用處。在做下一道習(xí)題前,試著自己回答下面的問題:

  1. 你認(rèn)為 if 對于它下一行的代碼做了什么?
  2. 為什么 if 語句的下一行需要縮進(jìn)?
  3. 如果不縮進(jìn),會(huì)怎樣?
  4. 把習(xí)題 27 中的其它布爾表達(dá)式放到if語句中能不能運(yùn)行呢?試一下。
  5. 如果把變量 people, cats, 和 dogs 的初始值改掉,會(huì)怎樣?

常見問題

Q: +=表示什么意思?

代碼x += 1x = x + 1 實(shí)現(xiàn)的是一樣的功能,但是可以少輸入一些字符。你可以稱之為“增量”操作符。-= 也是相同的,后面你會(huì)看到更多的相關(guān)解釋。

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號