跳转到内容

面向非程序员的 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.'


华夏公益教科书