Python條件控制

來源:互聯網
上載者:User

標籤:big   dog   大於   計算   關鍵字   組成   描述   print   The   

 if 語句

Python中if語句的一般形式如下所示:

if condition_1:   statement_block_1 elif condition_2:   statement_block_2 else:   statement_block_3

如果 "condition_1" 為 True 將執行 "statement_block_1" 塊語句,如果 "condition_1" 為False,將判斷 "condition_2",如果"condition_2" 為 True 將執行 "statement_block_2" 塊語句,如果 "condition_2" 為False,將執行"statement_block_3"塊語句。

Python中用elif代替了else if,所以if語句的關鍵字為:if – elif – else。

注意:

1、每個條件後面要使用冒號(:),表示接下來是滿足條件後要執行的語句塊。

2、使用縮排來劃分語句塊,相同縮排數的語句在一起組成一個語句塊。

3、在Python中沒有switch – case語句。

以下執行個體示範了狗的年齡計算判斷:

age = int(input("Age of the dog: ")) print() if age < 0:   print("This can hardly be true!") elif age == 1:   print("about 14 human years") elif age == 2:   print("about 22 human years") elif age > 2:   human = 22 + (age -2)*5   print("Human years: ", human) ### input(‘press Return>‘)

將以上指令碼儲存在dog.py檔案中,並執行該指令碼:

python dog.py Age of the dog: 1 about 14 human years

以下為if中常用的操作運算子:

操作符                     描述<                                小於<=                              小於或等於>                                 大於>=                               大於或等於==                               等於,比較對象是否相等!=                               不等於 # 程式示範了 == 操作符 # 使用數字 print(5 == 6) # 使用變數 x = 5y = 8print(x == y)  
以上執行個體輸出結果:

FalseFalse

high_low.py檔案:

#!/usr/bin/python3# 該執行個體示範了數字猜謎遊戲number = 7 guess = -1 print("Guess the number!")while guess != number:   guess = int(input("Is it... ")) if guess == number:   print("Hooray! You guessed it right!") elif guess < number:   print("It‘s bigger...") elif guess > number:   print("It‘s not so big.")

Python條件控制

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.