程式設計基礎:選擇
程式設計的一個重要部分是使用選擇,即在滿足特定條件時執行某些操作的能力。這可能像在電腦遊戲中,如果你吃了一根雞腿,就增加你的血條,或者如果溫度超過某個值,就把冷卻棒插入核反應堆中。

最常見的選擇語句是 **IF 語句**,其理念是將一個值與某些條件進行比較,**IF** 該值和條件匹配,則以某種方式繼續,否則執行其他操作。例如
If It is the queen Then Salute her Else Treat them like a commoner End
| VB.NET | Python |
|---|---|
If name = "Queen" Then
console.writeline("Hello your Majesty")
Else
console.writeline("Get to the back of the queue!")
End If
|
if name == "Queen":
print ("Hello your Majesty")
else:
print ("Get to the back of the queue!")
|
Else 部分是可選的,您可以直接忽略該公共者!(並丟棄 Else)
| VB.NET | Python |
|---|---|
If name = "Queen" Then
console.writeline("Hello your Majesty")
End If
|
if name == "Queen":
print ("Hello your Majesty")
|
您可能還希望在 If 語句中測試多個內容。例如
| VB.NET |
|---|
If name = "Queen" And age >= 18 Then
console.writeline("Hello your Majesty, I can serve you beer")
Else
console.writeline("Get out of my bar!")
End If
|
| Python |
if name == "Queen" and age >= 18:
print ("Hello your Majesty, I can serve you beer")
else:
print ("Get out of my bar!")
|
我們經常希望編寫執行某種比較或測試的 IF 語句。我們在上面的示例中恰好完成了這一點,使用 age >= 18 測試 age 變數的值是否大於或等於 18。
您會從數學學習中識別出大多數這些運算子,但一些在計算中略有不同。以下運算子很簡單
| 運算子 | 意義 |
|---|---|
> |
大於 |
< |
小於 |
>= |
大於或等於 |
<= |
小於或等於 |
在計算中不同的最重要的運算子是您可能已經多次使用過,甚至沒有注意到,那就是 = 運算子。在大多數程式語言中,= 運算子用於 **賦值**,例如,如果我們想將值 "bunny" 賦值給名為 animal 的變數,我們編寫 animal = "bunny",這在 VB.NET 和 Python 中是一樣的。這兩種語言在 **等於** 方面有所不同,我們在上面的示例中看到了這一點,測試 name 變數的值是否等於 "Queen"。在 VB.NET 中,等於運算子只是 =,而 Python 則使用 ==。這在編寫 Python 時會導致一個非常常見的程式設計錯誤 - 如果我們嘗試編寫使用 = 的 IF 語句,就會出錯
if name = "Queen" and age >= 18:
print("Hello your Majesty, I can serve you beer")
我們會收到類似於此的錯誤訊息
Traceback (most recent call last)
File "python", line 4
if name = "Queen" and age >= 18 then
^
SyntaxError: invalid syntax
最後,我們需要一個用於 **不等於** 的運算子。在 VB.NET 中,我們使用 <>,而在 Python 中,我們使用 !=。下面是一個非常糟糕的遊戲的例子
| VB.NET | Python |
|---|---|
Dim secret_word, your_guess As String
secret_word = "unlikely"
console.WriteLine("Try to guess the secret word:")
your_guess = console.ReadLine()
If your_guess <> secret_word Then
console.WriteLine("You lose")
End If
|
secret_word = "unlikely"
print("Try to guess the secret word:")
your_guess = input()
if your_guess != secret_word:
print("You lose")
|
|
練習:IF 語句 為以下內容編寫一個 IF 語句 詢問使用者的眼睛顏色,如果他們說是綠色,就稱他們為“地精”,否則他們一定是另一種型別的怪物 或者 答案 dim eyes as string
console.writeline("What eyes have thee?")
eyes = console.readline()
If eyes = "Green" Then
console.writeline("Thou art a Goblin?")
Else
console.writeline("Pray tell, be thou another form of beast?")
End If
透過輸入“綠色”來嘗試程式碼。它不起作用!我們需要調整 IF 語句:如果眼睛 = “綠色”或眼睛 = “綠色”,那麼 'Or 部分確保它能夠識別大小寫字母 ' '或者我們可以使用 UCase(),我們將在後面瞭解更多關於此的資訊 如果 UCase(眼睛) = "GREEN" 那麼 'UCase 將整個輸入轉換為大寫 </syntaxhighlight>
答案 dim age as single
console.writeline("How old are you:")
age = console.readline()
If age >= 11 And age < 17 Then
console.writeline("You're probably at secondary school")
Else
console.writeline("You're not at secondary school")
End If
現在來看一些非常簡單的 AI 在所有其他情況下,程式應該說:“對不起,我不知道該如何幫助”。使用一個 IF 語句編寫程式碼來處理上述情況 答案 dim feel as string
dim exercise as string
console.writeline("How do you feel today: Happy or Sad?")
feel = console.readline()
console.writeline("Have you had some exercise: Yes or No?")
exercise = console.readline()
If feel = "Sad" AND exercise = "No" Then
console.writeline("Go for a walk, you might feel better")
Else
console.writeline("Sorry I don't know how to help")
End If
|
|
示例:多個 If 與巢狀 If 有時,當我們試圖編寫複雜的程式碼時,我們需要使用 If 的組合。在上面的示例中,我們可能仍然希望以尊重的方式對待未成年的女王,以輕蔑的態度對待未成年的平民,以尊重的方式對待 18 歲以上的女王,並以普通禮貌的方式對待 18 歲以上的平民。事實上,我們似乎需要 4 個不同的 IF 語句。我們可以這樣解決 VB.NET
If name = "Queen" And age >= 18 Then
console.writeline("Hello your Majesty, may one serve you beer?")
End If
If name = "Queen" And age < 18 Then
console.writeline("I'm sorry your Majesty, you are too young to buy beer")
End If
If name <> "Queen" And age >= 18 Then '<> means not equal (so does !=)
console.writeline("Hello mate, can I serve you beer?")
End If
If name <> "Queen" And age < 18 Then
console.writeline("Get out of my pub, you are too young to buy beer")
End If
Python 3
if name == "Queen" and age >= 18:
print ("Hello your Majesty, may one serve you beer?")
elif name == "Queen" and age <18:
print ("I'm sorry your Majesty, you are too young to buy beer")
elif name != "Queen" and age >= 18:
print ("Hello mate, can I serve you beer?")
elif name != "Queen" and age <18:
print ("Get out of my pub, you are too young to buy beer")
這似乎很麻煩,我們現在將研究一種更優雅的解決方法,即使用巢狀 IF。首先,巢狀意味著將一個東西放在另一個東西里面,所以我們要將一個 IF 放在另一個 IF 裡面。 VB.NET
If name = "Queen" Then
If age < 18 Then
console.writeline("I'm sorry your Majesty, you are too young to buy beer")
Else
console.writeline("Hello your Majesty, may one serve you beer?")
End If
Else
If age >= 18 Then
console.writeline("Hello mate, can I serve you beer?")
Else
console.writeline("Get out of my pub, you are too young to buy beer")
End If
End If
Python 3
if name == "Queen":
if age < 18:
print ("I'm sorry your Majesty, you are too young to buy beer")
else:
print ("Hello your Majesty, may one serve you beer?")
else:
if age >= 18:
print ("Hello mate, can I serve you beer?")
else:
print ("Get out of my pub, you are too young to buy beer")
使用以下資料嘗試上面的示例,兩種解決方案都應該提供相同的答案 1. The name is Queen and the age is 18 2. The name is Quentin and the age is 28 3. The name is Queen and the age is 17 4. The name is Aashia and the age is 15 |
|
練習:巢狀 IF 語句 為以下內容編寫 IF 語句巢狀 當一個人超過 21 歲且沒有醉酒時,就可以租車。 它還應該處理 答案 dim age as integer
dim drinking as string
console.writeline("How old are you?")
age = console.readline()
if age >= 21 then
console.writeline("Good, that's old enough. Have you been drinking?")
drinking = console.readline()
if drinking = "Yes" then
console.writeline("Come back tomorrow")
else
console.writeline("Your carriage awaits")
end if
else
console.writeline("You're too young I'm afraid. Come back in a few years")
end if
建立一個登入螢幕來執行以下操作 如果他們輸入錯誤的使用者名稱,它應該立即將他們踢出,並且不詢問密碼。如果他們輸入錯誤的密碼,它應該將他們踢出。 答案 dim name as string
dim password as string
console.writeline("Enter username:")
name = console.readline()
if name = "Jonny5" then
console.writeline("RECOGNISED! Enter password:")
password = console.readline()
if password = "Alive" then
console.writeline("Please enter " & name)
else
console.writeline("INCORRECT! Get out!")
end if
else
console.writeline("Username not recognised. Get out!")
end if
|
|
擴充套件:單行 IF 語句 正如您現在應該意識到的那樣,許多程式設計都是儘可能快地完成事情。您可能已經厭倦了編寫冗長的 if 語句,不得不一直按回車鍵來建立新行。有一種更快的編碼方式:單行 IF 語句。
這是一種更短的編寫方式
但要小心,這種程式碼通常更難閱讀,因此更難除錯。一旦它通過了直譯器/編譯器,它幾乎肯定不會執行得更快,它只是為了讓你節省一點空間。對於考試,請堅持使用較長的版本。 |

另一種型別是 **Case 語句**,它可以用多個 if 語句來概括,其中將值與多個條件進行比較,並執行第一個匹配的條件的操作,否則執行預設操作。
Case Enter Restaurant and pick up menu If Egg and Chips available Then Order Egg and Chips End If If Pie and Chips available Then Order Pie and Chips End If If Curry and Chips available Then Order Curry and Chips End If If Pizza and Chips available Then Order Pizza and Chips End If Default Leave hungry End
但是,大多數程式語言都會提供一種縮短的實現 case 語句的方法,而無需編寫所有這些 if 語句。例如,在 VB.NET 中,我們使用 select case
Dim number As Integer = 5
Select Case number
Case 1, 2, 3
Console.WriteLine("Between 1, 2, 3 inclusive")
Case 4 to 8
Console.WriteLine("Between 4 and up to 8")
'This is the only case that is true
Case 9
Console.WriteLine("Equal to 9")
Case 10
Console.WriteLine("Equal to 10")
Case Else
Console.WriteLine("Not between 1 and up to 10")
End Select
|
練習:Case 語句 建立一個程式,讓人們輸入動物的名稱,它會輸出該動物發出的聲音。它應該處理的動物有
嘗試只使用 5 個 case 語句完成此任務。 答案 Dim animal As string
animal = console.readline()
Select Case animal
Case "Pig"
Console.WriteLine("Oink")
Case "Cow"
Console.WriteLine("Moo")
Case "Bear", "Tiger"
Console.WriteLine("Grr")
Case "Sheep"
Console.WriteLine("Baa")
Case Else
Console.WriteLine("Meow")
End Select
您現在將使用 case 語句建立一個電子鋼琴。
在下面的程式碼中建立一個 case 語句,它將播放上面寫的音符。while true 迴圈意味著程式碼將永遠不會結束,並且將永遠繼續。為了獲得額外的分數,請嘗試讓程式碼接受大小寫輸入 'instruction statement here
While True
'input and case statements here
While End
記住,要發出聲音,請使用 console.beep(2000,500) 'beep at 2000Hz for 0.5 seconds
答案 dim note as char
console.writeline("please insert a musical note:")
While True
note = Console.ReadKey().KeyChar
'note = Console.Readline() 'also works, but it less fun
Select Case UCase(note)
Case "A"
Console.Beep(220,50)
Case "B"
Console.Beep(247,50)
Case "C"
Console.Beep(262,50)
Case "D"
Console.Beep(294,50)
Case "E"
Console.Beep(330,50)
Case "F"
Console.Beep(349,50)
Case "G"
Console.Beep(392,50)
End Select
End While
|
