跳转到内容

Python 编程/条件语句

来自维基教科书,开放的书籍,开放的世界


一个决策是指当一个程序根据变量的值有多个行动选择时。想象一个交通灯。当它是绿色的,我们继续开车。当我们看到灯变黄,我们减速,当它是红色的,我们停下。这些是基于交通灯的值的逻辑决策。幸运的是,Python 有一种决策语句,当我们的应用程序需要为用户做出这样的决策时,它可以帮助我们。

If 语句

[编辑 | 编辑源代码]

这是一个热身练习 - 一个简短的程序来计算一个数字的绝对值
absoval.py

n = input("Integer? ")#Pick an integer. And remember, if raw_input is not supported by your OS, use input()
n = int(n)#Defines n as the integer you chose. (Alternatively, you can define n yourself)
if n < 0:
    print ("The absolute value of",n,"is",-n)
else:
    print ("The absolute value of",n,"is",n)

这是我两次运行这个程序的输出

Integer? -34
The absolute value of -34 is 34

Integer? 1
The absolute value of 1 is 1

当计算机看到这段代码时,它会做什么?首先,它使用语句 "n = input("Integer? ")" 提示用户输入一个数字。接下来,它读取行 "if n < 0"。如果n小于零,Python 运行行 "print ("The absolute value of",n,"is",-n)"。否则,Python 运行行 "print ("The absolute value of",n,"is",n)".

更正式地说,Python 检查表达式n < 0是真还是假。一个if语句后面跟着一个缩进的语句,当表达式为真时,这些语句将被执行。在if语句之后是一个可选的else语句以及另一个缩进的语句。如果表达式为假,则执行此第二个语句块。

表达式可以以多种不同的方式进行测试。这里有一个所有方式的表格

运算符 函数
< 小于
<= 小于或等于
> 大于
>= 大于或等于
== 等于
!= 不等于


的另一个特点if命令是elif语句。它代表 "else if",意思是如果原始的if语句为假且elif语句为真,则执行elif语句后的代码块。这里有一个示例
ifloop.py

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 语句中进行多个测试。

If 示例

[编辑 | 编辑源代码]

High_low.py

# Plays the guessing game higher or lower
# (originally written by Josh Cogliati, improved by Quique, now improved
# by Sanjith, further improved by VorDd, with continued improvement from
# the various Wikibooks contributors.)
 
# 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)
 
# This is for demonstration purposes only.
# It is not written to handle invalid input like a full program would.
 
answer = 23
question = 'What number am I thinking of?  '
print ('Let\'s play the guessing game!')

while True:
    guess = int(input(question))

    if guess < answer:
        print ('Little higher')
    elif guess > answer:
        print ('Little lower')
    else: # guess == answer
        print ('MINDREADER!!!')
        break

示例运行

Let's play the guessing game!
What number am I thinking of?  22
Little higher
What number am I thinking of?  25
Little Lower
What number am I thinking of?  23
MINDREADER!!!

正如它的注释中所说,这段代码没有准备处理无效输入(,字符串而不是数字)。如果你想知道如何在 Python 中实现这样的功能,请参阅本书的错误章节,在那里你将学习关于错误处理。对于上面的代码,你可以尝试对while循环进行以下细微修改

while True:
	inp = input(question)
	try:
		guess = int(inp)
	except ValueError:
		print('Your guess should be a number')
	else:
		if guess < answer:
			print ('Little higher')
		elif guess > answer:
			print ('Little lower')
		else: # guess == answer
			print ('MINDREADER!!!')
			break

even.py

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

print ("Input [x] for exit.")

while True:
	inp = input("Tell me a number: ")
	if inp == 'x':
		break
	# catch any resulting ValueError during the conversion to float
	try:
		number = float(inp)
	except ValueError:
		print('I said: Tell me a NUMBER!')
	else:
		test = number % 2
		if test == 0:
			print (int(number),"is even.")
		elif test == 1:
			print (int(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

#Prints the average value.
 
print ("Welcome to the average calculator program")
print ("NOTE- THIS PROGRAM ONLY CALCULATES AVERAGES FOR 3 NUMBERS")
x = int(input("Please enter the first number "))
y = int(input("Please enter the second number "))
z = int(input("Please enter the third number "))
str = x+y+z
print (float (str/3.0))
#MADE BY SANJITH [email protected]

示例运行

Welcome to the average calculator program
NOTE- THIS PROGRAM ONLY CALCULATES AVERAGES FOR 3 NUMBERS
Please enter the first number 7
Please enter the second number 6
Please enter the third number 4
5.66666666667

average2.py

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

sum = 0.0

print ("This program will take several numbers, then average them.")
count = int(input("How many numbers would you like to sum:  "))
current_count = 0
 
while current_count < count:
	print ("Number",current_count)
	number = float(input("Enter a number:  "))
	sum = sum + number
	current_count += 1
 
print("The average was:",sum/count)

示例运行

This program will take several numbers, then average them.
How many numbers would you like to sum:  2
Number 0
Enter a number:  3
Number 1
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 sum:  3
Number 0
Enter a number:  1
Number 1
Enter a number:  4
Number 2
Enter a number:  3
The average was: 2.66666666667

average3.py

#Continuously updates the average as new numbers are entered.

print ("Welcome to the Average Calculator, please insert a number")
currentaverage = 0
numofnums = 0
while True:
    newnumber = int(input("New number "))
    numofnums = numofnums + 1
    currentaverage = (round((((currentaverage * (numofnums - 1)) + newnumber) / numofnums), 3))
    print ("The current average is " + str((round(currentaverage, 3))))

示例运行

Welcome to the Average Calculator, please insert a number
New number 1
The current average is 1.0
New number 3
The current average is 2.0
New number 6
The current average is 3.333
New number 6
The current average is 4.0
New number


If 练习

[编辑 | 编辑源代码]
  1. 编写一个密码猜测程序,跟踪用户输入错误密码的次数。如果超过 3 次,则打印您已被拒绝访问。并终止程序。如果密码正确,则打印您已成功登录。并终止程序。
  2. 编写一个程序,要求用户输入两个数字。如果两个数字的总和大于 100,则打印这是一个大数字并终止程序。
  3. 编写一个程序,询问用户他们的姓名。如果他们输入你的姓名,则说 "这是一个好名字"。如果他们输入 "John Cleese" 或 "Michael Palin",则告诉他们你对他们的感觉;),否则告诉他们 "你有一个好名字"。
  4. 要求用户输入密码。如果密码正确,则打印 "您已成功登录" 并退出程序。如果密码错误,则打印 "对不起,密码错误" 并要求用户输入 3 次密码。如果密码错误,则打印 "您已被拒绝访问" 并退出程序。
##   Password guessing program using if statement and while statement only
###  source by zain


guess_count = 0

correct_pass = 'dee234'

while True:
	pass_guess = input("Please enter your password: ")

	guess_count += 1

	if pass_guess == correct_pass:
		print ('You have successfully logged in.')
		break

	elif pass_guess != correct_pass:
		if guess_count >= 3:
			print ("You have been denied access.")
			break
def mard():
    for i in range(1,4):
        a = input("enter a password:  ") # to ask password
        b = "sefinew" # the password
        if a == b: # if the password entered and the password are the same to print.
            print("You have successfully logged in")
            exit()# to terminate the program.  Using 'break' instead of 'exit()' will allow your shell or idle to dump the block and continue to run.
        else: # if the password entered and the password are not the same to print.
            print("Sorry the password is wrong ")
            if i == 3:
                print("You have been denied access")
                exit() # to terminate the program

mard()


#Source by Vanchi
import time
import getpass

password = getpass.getpass("Please enter your password")

print ("Waiting for 3 seconds")
time.sleep(3)
got_it_right = False
for number_of_tries in range(1,4):
    reenter_password = getpass.getpass("Please reenter your password")
    if password == reenter_password:
        print ("You are Logged in! Welcome User :)")
        got_it_right = True
        break

if not got_it_right:
    print ("Access Denied!!")

条件语句

[编辑 | 编辑源代码]

许多语言(如 Java 和 PHP)都有单行条件(称为三元运算符)的概念,通常用于简化有条件地访问值。例如(在 Java 中)

int in= ; // read from program input

// a normal conditional assignment
int res;
if(number < 0)
  res = -number;
else
  res = number;

多年来,Python 本身没有相同的结构,但是你可以通过构建一个结果元组并调用测试作为元组的索引来复制它,如下所示

number = int(input("Enter a number to get its absolute value:"))
res = (-number, number)[number > 0]

需要注意的是,与内置条件语句不同,真假分支在返回之前都会被评估,这会导致意外的结果,如果不小心,还会导致执行速度变慢。为了解决这个问题,以及作为一种更好的实践,将你放在元组中的任何东西包装在匿名函数调用(lambda 符号)中,以防止它们在调用所需分支之前被评估

number = int(input("Enter a number to get its absolute value:"))
res = (lambda: number, lambda: -number)[number < 0]()

然而,从 Python 2.5 开始,已经存在一个等效于三元运算符的运算符(虽然没有这样命名,而且语法完全不同)

number = int(input("Enter a number to get its absolute value:"))
res = -number if number < 0 else number

switch 是大多数计算机编程语言中存在的一种控制语句,用于最小化大量的 If - elif 语句。switch case 功能在 Python 3.10 中添加,使用了一种新的语法,称为 match case。在 3.10 版本之前,switch 没有得到官方支持。switch 语句可以通过巧妙地使用数组或字典来重新创建。

x = 1

def hello():
  print ("Hello")

def bye():
  print ("Bye")

def hola():
  print ("Hola is Spanish for Hello")

def adios():
  print ("Adios is Spanish for Bye")

# Notice that our switch statement is a regular variable, only that we added the function's name inside
# and there are no quotes
menu = [hello,bye,hola,adios]

# To call our switch statement, we simply make reference to the array with a pair of parentheses
# at the end to call the function
menu[3]()   # calls the adios function since is number 3 in our array.

menu[0]()   # Calls the hello function being our first element in our array.

menu[x]()   # Calls the bye function as is the second element on the array x = 1

这是因为 Python 在其特定索引处存储了函数的引用,通过添加一对括号,我们实际上是在调用该函数。这里最后一行等效于

另一种方式。通过用户输入使用函数

[编辑 | 编辑源代码]
go = "y"
x = 0
def hello():
  print ("Hello")
 
def bye():
  print ("Bye")
 
def hola():
  print ("Hola is Spanish for Hello")
 
def adios():
  print ("Adios is Spanish for Bye")

menu = [hello, bye, hola, adios]
 

while x < len(menu) :
    print ("function", menu[x].__name__, ", press " , "[" + str(x) + "]")
    x += 1
    
while go != "n":
    c = int(input("Select Function: "))
    menu[c]()
    go = input("Try again? [y/n]: ")

print ("\nBye!")
   

#end

另一种方式

[编辑 | 编辑源代码]
if x == 0:
    hello()
elif x == 1:
    bye()
elif x == 2:
    hola()
else:
    adios()

另一种方式

[编辑 | 编辑源代码]

另一种方法是使用 lambda 表达式。以下代码已获得许可,可供复制粘贴。1

result = {
  'a': lambda x: x * 5,
  'b': lambda x: x + 7,
  'c': lambda x: x - 2
}[value](x)

有关lambda的更多信息,请参阅函数部分中的匿名函数

华夏公益教科书