Fundamentals of Programming: Selection
An important part of programming is the use of selection, that is the ability to do something if certain criteria is met. This may be as simple as increasing your health bar in a computer game if you eat a chicken drumstick or inserting the cooling rods into the nuclear reactor if the temperature exceeds a certain value.
IF Statement
[edit | edit source]The most common selection statement is the IF statement, the idea is that you compare a value to some criteria, IF the value and criteria match then you proceed in a certain way, otherwise you do something else. For example:
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!")
|
The Else part is optional, you can just ignore the commoner! (and dump the Else)
VB.NET | Python |
---|---|
If name = "Queen" Then
console.writeline("Hello your Majesty")
End If
|
if name == "Queen":
print ("Hello your Majesty")
|
You might also want to test multiple things in the If statement. For example:
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!")
|
Relational operators
[edit | edit source]We often want to write IF statements that do some kind of comparison or test. We just did exactly that in the example above with age >= 18
which tests if the value of the age variable is greater or equal to 18.
Most of these operators you will recognise from learning maths but some are slightly different in computing. The following operators are straightforward:
Operator | Meaning |
---|---|
> |
Greater than |
< |
Less than |
>= |
Greater than or equal to |
<= |
Less than or equal to |
The most important operator that is different in computing is one that you have already used many, many times probably without even noticing, which is the =
operator. In most programming languages the =
operator is used for assignment, for example if we want to assign the value "bunny"
to a variable called animal
we write animal = "bunny"
which is the same in both VB.NET and Python. These two languages are different when it comes to equals which we saw in the example above testing if the value of the name
variable was equal to "Queen"
. In VB.NET the equals operator is just =
whereas Python uses ==
instead. This can lead to a very common programming mistake when writing Python - if we try to write an IF statement which uses =
by mistake:
if name = "Queen" and age >= 18:
print("Hello your Majesty, I can serve you beer")
we will get an error message similar to this:
Traceback (most recent call last):
File "python", line 4
if name = "Queen" and age >= 18 then:
^
SyntaxError: invalid syntax
Finally we need an operator for not equals. In VB.NET we use <>
whereas in Python we use !=
. Here's an example in the form of a really quite rubbish game:
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")
|
Exercise: IF statements Write a single IF statement for the following: Ask a user for their eye colour, if they say green call them a "Goblin", else they must be a different type of monster:
Code Output
What eyes have thee? Alternatively:
Code Output
What eyes have thee? Answer: 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
Try the code by inputting "green". It doesn't work! We need to adjust the IF statement: If eyes = "Green" or eyes = "green" Then 'the Or part makes sure it picks up upper and lower case letters ' 'alternatively we could use UCase() we'll find out more about this later If UCase(eyes) = "GREEN" Then 'UCase converts the entire input into capitals </syntaxhighlight>
Code Output
How old are you:
Code Output
How old are you:
Code Output
How old are you:
Answer: 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
Now for some very simple AI:
Code Output
How do you feel today: Happy or Sad? In all other situations the program should say: "Sorry I don't know how to help". Using one IF statement write code to handle the above: Answer: 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
|
Example: Multiple Ifs versus Nested Ifs Sometimes when we are trying to write complex code we will need to use a combination of IFs. In the example above we might want to still treat an under-age queen with respect, an under-age commoner with contempt, serve an 18+ queen with respect, and serve an 18+ commoner with common manners. In fact it seems as if we need 4 different IF statements. We could solve it like this: 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")
This seems awfully cumbersome and we will now look a more elegant way of solving this, using Nested IF's. First of all, nested means placing one thing inside another, so we are going to place an IF inside another. 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")
Try the examples above with the following data, both solutions should provide the same answer: 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 |
Exercise: Nested IF statements Write nests of IF statements for the following: A car can be hired when a person is over 21 and not intoxicated.
Code Output
How old are you? It should also handle:
Code Output
console.writeline("How old are you?") Answer: 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
Create a login screen to do the following:
Code Output
Enter username If they get the username wrong it should immediately kick them out and not ask for the password. If they get the password wrong it should kick them out. Answer: 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
|
Extension: Single line IF statements As you should be aware by now a lot of programming is doing things as quickly as possible. You might be fed up with writing long if statements, having to keep hitting that enter key to make new lines. There is a faster way to code: single line IF statements.
This is a much shorter way of writing:
But be careful, code like this can often be harder to read and therefore debug. Once it has been through the interpreter / compiler it almost certainly won't be running any faster either, it's just there for you to save a little space. For the exam keep to the longer version. |
Case Statement
[edit | edit source]The other type is the Case statement, this can be summarised by several if statements where the value is compared to several criteria and the action of first criteria matched is performed, otherwise a default action may be performed.
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
However, most programming languages will give you a shortened way of implementing a case statement without the need to write all of these if statements. For example in VB.NET we use the 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
Between 4 and up to 8
Exercise: Case statements Create a program where someone types in the name of an animal and it outputs the sound the animal makes. The animals it should handle are:
Try and complete this task by only using 5 case statements. Answer: 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
You are now going to use a case statement to create an electronic piano.
Create a case statement in the code below, that will play the notes written above. The while true loop means that the code will never end and will continue for ever. For bonus points try and get the code to accept both upper and lower case inputs 'instruction statement here
While True
'input and case statements here
While End
Remember to make sound you use: console.beep(2000,500) 'beep at 2000Hz for 0.5 seconds
Answer: 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
|