Python 程式設計/條件語句
一個決策是指當一個程式根據變數的值有多個行動選擇時。想象一個交通燈。當它是綠色的,我們繼續開車。當我們看到燈變黃,我們減速,當它是紅色的,我們停下。這些是基於交通燈的值的邏輯決策。幸運的是,Python 有一種決策語句,當我們的應用程式需要為使用者做出這樣的決策時,它可以幫助我們。
這是一個熱身練習 - 一個簡短的程式來計算一個數字的絕對值
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 語句中進行多個測試。
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 sanrubik@gmail.com
示例執行
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
- 編寫一個密碼猜測程式,跟蹤使用者輸入錯誤密碼的次數。如果超過 3 次,則列印您已被拒絕訪問。並終止程式。如果密碼正確,則列印您已成功登入。並終止程式。
- 編寫一個程式,要求使用者輸入兩個數字。如果兩個數字的總和大於 100,則列印這是一個大數字並終止程式。
- 編寫一個程式,詢問使用者他們的姓名。如果他們輸入你的姓名,則說 "這是一個好名字"。如果他們輸入 "John Cleese" 或 "Michael Palin",則告訴他們你對他們的感覺;),否則告訴他們 "你有一個好名字"。
- 要求使用者輸入密碼。如果密碼正確,則列印 "您已成功登入" 並退出程式。如果密碼錯誤,則列印 "對不起,密碼錯誤" 並要求使用者輸入 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的更多資訊,請參閱函式部分中的匿名函式。