国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python中的if、else、elif語句用法簡明講解

2020-01-04 17:38:13
字體:
來源:轉載
供稿:網友
這篇文章主要介紹了Python中的if、else、elif語句的用法講解,條件判斷語句是程序中流程控制的基礎辦法之一,需要的朋友可以參考下
 

下面我們學習if語句,輸入下面的代碼,確保能夠正確運行。

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


運行結果

root@he-desktop:~/mystuff# 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語句的作用,用自己的話回答下面的問題。
1. 你認為if對它下面的代碼做了什么?
判斷為True就執行它下面的代碼,否則不執行。

2. 為什么if下面的代碼要縮進4個空格?
為了表示這些代碼屬于if判斷下包括的代碼。

3. 如果不縮進會發生什么?
會提示一個縮進錯誤。

4. 你可以從第27節中拿一些布爾表達式來做if判斷嗎?

5. 改變people,dogs,cats變量的值,看看會發生什么?

答案:
1. if語句下面的代碼是if的一個分支。就像書里的一個章節,你選擇了這章就會跳到這里閱讀。這個if語句就像是說:“如果布爾判斷為True,就執行下面的代碼,否則跳過這些代碼”。

2. 用冒號結束一個語句就是要告訴python,我要開始一個新的代碼段了。縮進4個空格就是說,這些代碼是包含在這個代碼段中的,和函數的使用一樣。

3. 不縮進會報錯,python規定冒號后面語句必須有縮進。

4. 可以,而且可以是復雜的語句。

5. 修改變量的值后,判斷語句就會相應的變True或者False,然后輸出不同的語句。

比較我的答案和你自己的答案,確保你能理解代碼塊這個概念,因為這個對于下面的練習非常重要。

輸入下面的代碼,運行它:

people = 30 cars = 40 buses = 15   if cars > people:   print "We should take the cars." elif cars < people:   print "We should not take the cars." else:   print "We can't dicide."   if buses > cars:   print "That's too many buses." elif buses < cars:   print "Maybe we could take the buses." else:   print "We still can't decide."   if people > buses:   print "Alright, let's just take the buses." else:   print "Fine, let's stay home then." 


運行結果

root@he-desktop:~/mystuff# python ex30.py 
We should take the cars.Maybe we could take the buses.Alright, let's just take the buses.

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 仁化县| 紫金县| 额敏县| 太谷县| 上蔡县| 孟连| 克什克腾旗| 灵台县| 南乐县| 江口县| 富川| 呼伦贝尔市| 夹江县| 嘉兴市| 洮南市| 安新县| 且末县| 清水县| 胶南市| 时尚| 建水县| 吐鲁番市| 高青县| 海宁市| 克山县| 日土县| 滦平县| 布尔津县| 太湖县| 如东县| 梓潼县| 湖南省| 澄江县| 贡山| 思茅市| 晋城| 禹城市| 漳州市| 罗平县| 犍为县| 卫辉市|