Important Announcement
PubHTML5 Scheduled Server Maintenance on (GMT) Sunday, June 26th, 2:00 am - 8:00 am.
PubHTML5 site will be inoperative during the times indicated!

Home Explore Computing Academy GCSE Computer Science

Computing Academy GCSE Computer Science

Published by chye, 2018-02-23 04:50:22

Description: GCSE

Search

Read the Text Version

The syntax of an if statement will vary between languages but here are some examples.The following example written in Python uses an if statement to compare two numbers, 5and 6. if 5 < 6: print(“It is less.”) else: print(“It is not less.”) It is less.if 5 is less than (<) 6 then the first print statement will run: print(“It is less.”).If 5 is not less than 6 then the first print statement would be ignored, and we wouldskip to the else clause and execute the second print statement: print(“It is notless.”)Notice in Python that we do not use curly brackets { }, and rather than writing then wejust use a colon : 200

In Java, the same code would look like this: if (5 < 6) { System.out.println(\"It is less.\"); } else { System.out.println(\"It is not less\"); }So far, the if statements that we have seen just have two options: what to do if thecondition is true and what to do if the condition is false.Consider a shopping website that personalises content depending on whether thecustomer is male or female. gender = “Female” if gender == “Male”: print(“Taking you to the mens’ section...”) elif gender == “Female”: print(“Taking you to the womens’ section...”) Taking you to the womens’ section... 201

The code above allows us to check several expressions and then execute some actionsonce one of the expressions is found to be true.In this example, gender = “Female”. The first expression gender == “Male”therefore evaluates as false, so the first print statement is ignored. The programcontinues to the elif statement which now introduces a second expression forevaluation: gender == “Female”. This expression evaluates as true, therefore theprint statement: print(“Taking you to the womens’ section...”) executes. Key Point Note that in some programming languages we write an else if clause. using ‘elseif’. In Python this is written ‘elif’.In the next example, we have four expressions and only one will evaluate to true.Customers of the shopping website can be a ‘Man’, ‘Woman’, ‘Boy’ or ‘Girl’,and each type of customer will be shown a message intended for them. 202

type = “Boy” if type == “Man”: print(“Taking you to the mens’ section...”) elif type == “Woman”: print(“Taking you to the womens’ section...”) elif type == “Boy”: print(“Taking you to the boys’ section...”) elif type == “Girl”: print(“Taking you to the girls’ section...”) Taking you to the boys’ section...The first two expressions evaluate as false so the program skips to the third expression:type == “Boy” which evaluates as true. 203

Nested If StatementsIt is often necessary to ensure several expressions are true before executing some code.We’ve seen already that we can do this with the logical operator and, as in: if colour == “red” and brand == “volkswagen”: print(“We’ve found a car for you”) else: print(“Sorry, no cars match your search”)Sometimes, however, we need even more control. The code above demands that the caris red and a Volkswagen. We might want to take a different course of action if just a redcar was found, or if just a Volkswagen was found. if colour == “red”: if brand == “volkswagen”: print(“We’ve found a red volkswagen for you”) else: print(“We’ve found a red car for you”) else: print(“Sorry, no cars match your search”) 204

So, this code uses nested if statements. If the first expression evaluates as false (thecolour is not red), the program skips right to the bottom and executes the else clause: theprint statement displays: Sorry, no cars match your searchIf the first expression evaluates as true (the car is red), a second expression is thenimmediately evaluated: brand == “volkswagen”. If this expression also evaluates astrue the print statement displays: We’ve found a red volkswagen for youIf, however, brand == “volkswagen” evaluates as false, the program skips to thefirst else clause and the print statement displays: We’ve found a red car for youThe indentation helps us to keep track of which part of the program is running: noticehow one if..else... block is indented within another if..else... block asindicated by the red and orange lines? 205

LoopsWe often need to repeat a process when writing programs. Rather than copying andpasting the same chunk of code several times, it is much more efficient to use a loop.Let’s say that we simply want to print the numbers 0 - 100 on the screen. count = 1 while (count <= 100): print(count) count = count + 1 206

This code first sets the count to 1. We then use a while loop to tell the computer that wewant to continue to repeat or iterate through this code while (count = <= 100).When count becomes 100, the loop will stop.The first time through the loop, count = 1, therefore the print(count) statementdisplays 1 on the screen. 1The last line of code increases the value of count by 1. There will then be a second passover the loop. count is now equal to 2 (which is less than 100 so the program willcontinue). The print(count) statement displays 2 on the screen. 1 2This loop will continue to iterate while (count <= 100). 207

Lists / ArraysWe know that variables can be used to store data. Consider a travel agency who have acomputer system with a list of destinations. We could use a variable destination tostore the first destination. destination = “Alicante”The problem would be, that when we wish to store the second destination: 208

destination = “Berlin”The original value stored in the variable is overwritten. The value of destination is now“Berlin” and “Alicante” has been lost.We could of course create multiple variables: destination1 = “Alicante” destination2 = “Berlin” destination3 = “Calais”...but this method takes up quite a lot of memory and makes is harder to use thisinformation later. The way in which we should store a list of items such as this is by usinga one-dimensional array. destinations = [“Alicante”, “Berlin”, “Calais”, “Dijon”, “Espinosa”]Here we have declared a new variable called destinations which is an array. In orderto access elements within the array we can now just use the position of that elementwithin the array: print(destinations[1]) Berlin 209

Note that the first location is an array is 0, so in the previous example, in order to print“Berlin”, we accessed destinations[1] which is actually the second element in thearray.Arrays can be used effectively with loops. Imagine that we now wanted to print a list ofthese destinations. We could write: print(destinations[0]) print(destinations[1]) print(destinations[2]) print(destinations[3]) print(destinations[4])...but this code is not efficient as we have essentially written the same thing five times.The follow code iterates through a loop, accessing and printing each element. Only oneprint statement is used and we would need no additional code for an array containingthousands of destinations. This makes it much more efficient. arraySize = 4 count = 0 while (count < arraySize): print(destinations[count]) count = count + 1AlicanteBerlinCalaisDijonEspinosa 210

Documenting CodeEven simple computer programs consist of thousands of lines of code. Often, it can takemonths or even years to write complex computer programs such as console games, andthese games may be developed by several people.Furthermore, developers might not work for the same company forever, so someone newwill need to come in and continue to develop the game.It is standard practice to document or comment your code in order to ensure that youcan look back at your code in several days, months or years and understand what youhave done and why. Comments are written in plain English by the programmer.Comments are ignored by interpreters and compilers and so do not affect the running of aprogram. 211

Using comments significantly improves the readability of your code and helps when itcomes to debugging code. //prompt the user to enter their password //save it to a new variable called userEntered userEntered = input(“Please enter your password”) //store actual password to a new variable actualPassword = “gh%yuN&” //compare password entered by user to actual if userEntered != actualPassword: //if passwords do not match print(“Incorrect Password”) else: //if passwords do match print(“Correct Password”)Here is some code we saw earlier for checking passwords. It has now has commentsadded to it so that it is clear what each line of the code does. 212

ccxiii


Like this book? You can publish your book online for free in a few minutes!
Create your own flipbook