跳轉到內容

面向非程式設計師的 Python 2.6 教程/決策

來自華夏公益教科書,開放的書籍,開放的世界

if 語句

[編輯 | 編輯原始碼]

一如既往,我認為我應該用熱身打字練習來開始每一章,所以這裡有一個簡短的程式來計算一個數字的絕對值

n = int(input("Type in a number: "))
if n < 0:
   print('The absolute value of', int(n), 'is: ', abs(-n))
else:
   print('The absolute value of', int(n), 'is: ', abs(n))

以下是兩次執行該程式的輸出

Type in a number: -14
The absolute value of -14 is:  14
Type in a number: 24
The absolute value of 24 is:  24

那麼,當計算機看到這段程式碼時它做了什麼?首先,它使用語句 "n = input("Number? ")" 提示使用者輸入一個數字。然後,它讀取 "if n < 0:" 這行。如果 n 小於零,Python 就會執行 "print('The absolute value of', int(n), 'is: ', abs(-n))" 這行。否則,它將執行 "print('The absolute value of', int(n), 'is: ', abs(n))" 這行。

更正式地說,Python 會檢視表示式 n < 0 是真還是假。if 語句後面跟著一個縮排的,當表示式為真時,該塊中的語句會被執行。可選地,在 if 語句之後是 else 語句和另一個縮排的。如果表示式為假,則執行第二個語句塊。

表示式可以有許多不同的測試。以下是所有測試的表格

運算子 函式
< 小於
<= 小於或等於
> 大於
>= 大於或等於
== 等於
!= 不等於
<> 另一種表示不等於的方式(舊式,不推薦)

if 命令的另一個功能是 elif 語句。它代表 else if,意思是如果原始 if 語句為假,但 elif 部分為真,則執行 elif 部分。如果 ifelif 表示式都不為真,則執行 else 塊中的內容。以下是一個示例

a = 0
while a < 10:
    a = a + 1
    if a > 5:
        print a, ">", 5
    elif a <= 7:
        print a, "<=", 7
    else:
        print "Neither test was true"

以及輸出

1 <= 7
2 <= 7
3 <= 7
4 <= 7
5 <= 7
6 > 5
7 > 5
8 > 5
9 > 5
10 > 5

注意 elif a <= 7 只有在 if 語句不為真時才會被測試。可以有多個 elif 表示式,允許在一個 if 語句中進行多個測試。

# This Program Demonstrates the use of the == operator
# using numbers
print 5 == 6
# Using variables
x = 5
y = 8
print x == y

以及輸出

False
False

High_low.py

# Plays the guessing game higher or lower 

# This should actually be something that is semi random like the
# last digits of the time or something else, but that will have to
# wait till a later chapter.  (Extra Credit, modify it to be random
# after the Modules chapter)
number = 78
guess = 0

while guess != number: 
    guess = input("Guess a number: ")
    if guess > number:
        print "Too high"
    elif guess < number:
        print "Too low"

print "Just right"

示例執行

Guess a number: 100
Too high
Guess a number: 50
Too low
Guess a number: 75
Too low
Guess a number: 87
Too high
Guess a number: 81
Too high
Guess a number: 78
Just right

even.py

# Asks for a number.
# Prints if it is even or odd

number = input("Tell me a number: ")
if number % 2 == 0:
    print number, "is even."
elif number % 2 == 1:
    print number, "is odd."
else:
    print number, "is very strange."

示例執行

Tell me a number: 3
3 is odd.
Tell me a number: 2
2 is even.
Tell me a number: 3.14159
3.14159 is very strange.

average1.py

# keeps asking for numbers until 0 is entered.
# Prints the average value.

count = 0
sum = 0.0
number = 1 # set to something that will not exit the while loop immediately.

print "Enter 0 to exit the loop"

while number != 0:
    number = input("Enter a number: ")
    if number != 0:
        count = count + 1
        sum = sum + number

print "The average was:", sum / count

示例執行

Enter 0 to exit the loop
Enter a number: 3
Enter a number: 5
Enter a number: 0
The average was: 4.0
Enter 0 to exit the loop
Enter a number: 1
Enter a number: 4
Enter a number: 3
Enter a number: 0
The average was: 2.66666666667

average2.py

# keeps asking for numbers until count numbers have been entered.
# Prints the average value.

sum = 0.0

print "This program will take several numbers then average them"
count = input("How many numbers would you like to average: ")
current_count = 0

while current_count < count:
    current_count = current_count + 1
    print "Number", current_count
    number = input("Enter a number: ")
    sum = sum + number

print "The average was:", sum / count

示例執行

This program will take several numbers then average them
How many numbers would you like to average: 2
Number 1
Enter a number: 3
Number 2
Enter a number: 5
The average was: 4.0
This program will take several numbers then average them
How many numbers would you like to average: 3
Number 1
Enter a number: 1
Number 2
Enter a number: 4
Number 3
Enter a number: 3
The average was: 2.66666666667
  1. 修改本節中的高低程式,以跟蹤使用者輸入錯誤數字的次數。如果超過 3 次,列印 "That must have been complicated." 請注意,程式不必在猜測數字之前停止詢問數字,它只需要在猜測數字後列印這條資訊。
  2. 編寫一個程式,要求使用者輸入兩個數字。如果兩個數字的和大於 100,列印 "That is a big number."。
  3. 編寫一個程式,要求使用者輸入他們的名字,如果他們輸入你的名字,就說 "That is a nice name",如果他們輸入 "John Cleese" 或 "Michael Palin",告訴他們你對他們的感受 ;),否則就告訴他們 "You have a nice name."。
解決方案

修改本節中的高低程式,以跟蹤使用者輸入錯誤數字的次數。如果超過 3 次,列印 "That must have been complicated."。

number = 42
guess = 0
count = 0
while guess != number:
    count = count + 1
    guess = input('Guess a number: ')
    if guess > number:
        print 'Too high'
    elif guess < number:
        print 'Too low'
    else:
        print 'Just right'
        break
    if count > 2:
        print 'That must have been complicated.'
        break

編寫一個程式,要求使用者輸入兩個數字。如果兩個數字的和大於 100,列印 "That is a big number."。

number1 = input('1st number: ')
number2 = input('2nd number: ')
if number1 + number2 > 100:
    print 'That is a big number.'

編寫一個程式,要求使用者輸入他們的名字,如果他們輸入你的名字,就說 "That is a nice name",如果他們輸入 "John Cleese" 或 "Michael Palin",告訴他們你對他們的感受 ;),否則就告訴他們 "You have a nice name."。

name = raw_input('Your name: ')
if name == 'Ada':
    print 'That is a nice name.'
elif name == 'John Cleese' or name == 'Michael Palin':
    print '... some funny text.'
else:
    print 'You have a nice name.'


華夏公益教科書