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

NOTA NOT gate inverts the input so if A (the input) is equal to 1 then P (the output) will be 0. AP 01 10 150

ANDAn AND gate requires both inputs, A and B to be 1 in order for the output to be 1. If justone input is 1 and other is 0, the output will be 0. ABP 000 010 100 111 151

ORAn OR gate will output a 1 if either input, or both is 1. If both inputs are 0, the output willbe 0. ABP 000 011 101 111 152

XOR (Exclusive OR)An XOR gate will only output high if just one input is high. If both inputs 1, or neither inputis 1, an XOR gate will output 0. ABP 000 011 101 110 153

NANDA NAND gate is also known as an inverted AND. An AND gate requires both inputs to be 1in order to output a 1. A NAND gate is the opposite and will output a 1 if either input, or noinputs are 1. ABP 001 011 101 110 154

NORA NOR gate only outputs a 1 if both inputs are 0. ABP 001 010 110 110 155

SequencingComputer systems run programs, and programs are simply sequences of instructions. So,computers follow sequences of instructions, but there is often more than one way toaccomplish a task, and more than one factor influencing the running of the program.To get a new outfit you could:• Make one yourself• Go to a large shopping centre• Go to a local shop• Browse and purchase online 156

Each of these would options would involve different steps or instructions. Theseinstructions are called algorithms.The end result is the same; you end up with a new outfit.Mathematical AlgorithmsMathematicians are familiar with algorithms. In maths, the word algorithm refers to a set ofinstructions used to solve a problem.If we’re performing long division of 75 divided by 4 we would use the following algorithm:• How many times does 4 go in to 75?• The answer is 18• How many left over?• The answer is 3Ordering InstructionsWhen thinking about writing algorithms and computer programs it’s important to first thinkthrough what the program is trying to achieve, and in what order.Think about an everyday task such as making a cup of tea. What order would you putthese instructions in so that you ended up with a cup of tea? Remove bag, fill kettle, enjoy,add milk, add tea bag, pour hot water, stir, wait for kettle to boil. 157

The correct sequence would look like this: 158

If we move the ‘add tea bag’ instruction to the end - we don’t end up with a cup of tea; ifwe move the ‘wait for kettle to boil’ instruction to the end - we don’t end up with a cup oftea. Getting instructions in the correct order - precision - is crucial here.Similarly, think about a set of traffic lights that control the flow of traffic at a crossroads.The correct sequences of instructions is show below: red, red and amber, green.When everything is operating correctly, the traffic flowing from East to West and West toEast passes safely, while the North to South and South to North traffic waits at red lights.If this sequences of instructions wasn’t followed.......we’d end up with big problems. 159

Flowcharting The London Eye, also known as the Millennium Wheel is the tallest Ferris wheel in Europe. The 135 metre tall structure is a popular tourist attraction, and while we may not really think about it, the London Eye is fully controlled by computer systems.There are 32 capsules attached to the wheel, each able to hold 25 people. As thesecapsules are attached to the wheel, and the wheel is rotating, what is stopping thepassengers in the pods from being turned upside down as shown in the diagram below? 160

As the large wheel rotates in one direction, each of the pods rotates in the opposite direction at the same time in order to keep the floor perfectly level. There are sensors in each capsule that detect whether the floor is level and pass this information back to the computer system. If the computer detects that any capsule is not level, it will speed up or slow the motors as necessary in order to bring the floor back to normal.Before constructing the London Eye and developing the software used to control it, a lotof planning would have taken place. The developers would have produced structureddiagrams that illustrate how the program will work; a common method for visuallyrepresenting computer programs is to use flowcharts.The basic symbols used when drawing flowcharts are:To show how these symbols work, let’s look at the sort of flowchart that would have beendraw by the developers of the London Eye computer system to control the floor level. 161

When the system starts it will begin a process to monitor the level of each capsule. Based on the data collected, the computer system will need to make a decision about whether or not the floor is level. If the floor is level, then no action is necessary, and the process of monitoring the floor level can continue. If, however, the floor is not level, another decision is taken about whether the floor is tilted too much to the right. If so, the system will need to increase power to the motors of the capsule in order to rotate it and thus bring it level - this is classed as an output from the system.If the floor was not tilted to the right, a decision is taken as to whether the floor is tilted tothe left (and at this stage it must be) and the capsule is tilted back to the right byincreasing power to the opposite motor. 162

8 This language of 1s and 0s that the CPU understandsProgramming is called Machine Code

Programming LanguagesBefore we StartThroughout the next chapter you will see examples of programming code. We’ve usedPython in this textbook, but the concepts and constructs that you will see here in Pythoncan easily be applied to other programming languages you might use.Code will always be shown in a grey box, while the output, or result of running that codewill be shown in a blue box. Here’s an example: numLives = numLives + 3 13 164

The Language of Programming LanguagesProgramme is a UK spelling and we use it to refer to television programmes, a footballprogramme, a programme of events etc. It would never be correct in the UK to call it a‘football program’. The Americans, however, use the word program for everythingincluding television shows.Unlike the Americans, in the UK, we only use the word program when referring tocomputers both as a noun and a verb.We would say:• I can program that computer. [verb]• The computer program does not work. [noun]• Developing computer programs is really fun. [noun]We can also talking about programming, programmers and programmed as in: 165

I am a computer programmer, I am fairly good at programming and I have programmedseveral apps. Notice how we use a double ‘mm’ (but no ‘e’) here?Machine CodeNo matter the type of computer you are using be this a games console, a mobile device ora traditional PC, they all feature at their heart a CPU. The only type of data that the CPUcan understand and process is 1s and 0s.We know that computer systems operate on a base 2 or binary system with 1s and 0s -on and off. The first computers were programmed by literally turning switches on and offto input data into the system - we still do this today although we have streamlined theprocess a lot.No matter what programming language you might use to create games, apps or othertypes of software, this is all ultimately converted into 1s and 0s for the CPU.This language of 1s and 0s that the CPU understands is called Machine Code.It is possible to create programs directly in machine code but it would be enormously timeconsuming.We know that the Von Neumann architecture used in CPUs means that data andinstructions are both stored in the same place and fed to the CPU together. The fetch-decode-execute cycle then determines which parts are instructions and which are datavalues.The following example is an example of machine code. The first byte (remember, a byte isa sequence of 8 digits) shown here might be an instruction such as ADD; the secondbyte might actually be a data value. It is for the CPU to determine what is data and whatis an instruction. 01100101 001100100 166

Instruction SetsAlthough all CPUs process only binary numbers, the order in which they accept data andinstructions and the way in which instructions are converted into binary will vary betweendifferent types of CPU.The CPU used in Apple smartphones might recognise ‘00110101’ as the ADD instruction,and expect a data value to follow it, whereas the CPU used in some Sony laptops mightrecognise ‘00000011’ as the ADD instruction, and expect a data value to always comebefore it.Different CPUs expect programs written by developers to be converted into their ownparticular variant of machine language which they can understand. Each CPU has it’s owninstruction set - the dictionary used during the conversion into machine code in order toensure that the CPU will be able to understand the code.Assembly LanguageEarly programmers quickly tired of typing out so many 1s and 0s and thought there shouldbe a better, faster method.Mnemonics (substitutes or abbreviations) are used to speed up the process, so ratherthan writing out: 00000011 every time you wish to add something, 00000011 might besubstituted for ADD.Mnemonics make the language easier for humans to read and understand, and made itmuch quicker for early programmers.This language consisting of mnemonics is known as Assembly Language.While assembly language is great for programmers, the CPU can still only understandmachine code. Programs written in assembly language therefore need to be convertedinto machine code using an assembler (a special kind of program). In order to performthis conversion, the assembler will use a lookup table to find the mnemonic that can besubstituted for binary instructions. 167

An assembly language lookup table might look like this. Binary Mnemonic00000011 ADD10101010 MUL 1110111 MOVHigh-Level LanguagesEven though assembly language is a little more ‘friendly’ than machine code it would stilltake an incredibly long time to write complex software of the type we use today.Assembly languages have a one-to-one correspondence of mnemonic-to-binary, so whileit’s a little easier to understand, you still need to write the same number of commands.High-level languages are what we usually use today when developing software includinggames and apps.Key PointHigh-level means reading and writing is really easy and it looks a lot likeregular English! 168

Some high-level languages that you might have heard of or be familiar with include: Name Notes BASIC First created in 1964, BASIC was one of the first C# high-level languages that allowed non-computer Java scientists to start to program.Objective-C PHP A modern language developed by Microsoft in 2000. Often used to created computer games. Python Not to be confused with JavaScript. Java was created by Sun Microsystems in 1995 and later bought by Oracle. It is one of the most popular programming languages in use and allows programs to be compiled and ran on any computer. Developed by Apple in 1983. Although not a new language, it is the main language used by Apple for their desktop and mobile operating systems, OSX and iOS. A popular server-sided (web based) language used to drive many popular websites today including Facebook. Released in 1991, Python is as popular today as it has ever been. Programs written in Python are easy to follow and as such it makes a great first language to learn.These languages do not have a one-to-one correspondence between commands andmachine code; one short command in a high-level programming language may representmany machine level instructions.In a high level language such as Python, in order to work out the correct answer to 8multiplied by 8 we would write: 169

8*8 64If we wanted to perform the same calculation in assembly language, as most assemblylanguages don’t have a multiply function we would need to add 8 lots of 8 together. Itmight look like this: ADD 00010000 ADD 00010000 STORE answer ADD 00010000 STORE answer ADD 00010000 STORE answer ADD 00010000 STORE answer ADD 00010000 STORE answer ADD 00010000 STORE answer ADD 00010000 STORE answerThis is clearly a much more time consuming job and only works out 8 X 8. Imagine writinga mobile app using assembly language! 170

GenerationsWe’ve now looked at three generations of programming languages.High Level Language 3rd Generation Uses if (price > 150) { Statements discount = getDiscount()Assembly Language 2nd Generation price = price - discount UsesMachine Code 1st Generation Mnemonics } Uses Binary LOAD 14X3 SUB 14X4 14X3 MOVE 14X2 STORE 14X4 10110110111110100000000000000 0000000000000000000000000000 10101110101101110100101110101 171

TranslatorsThe CPU, of course, cannot directly run high-levellanguages; they need to be translated into machinecode. Remember, machine code is different fordifferent CPUs, so programs written in high-levellanguages need to be translated into the specificvariant of machine code needed by the CPU in thatcomputer system.We’ve already looked at one type of translator - anassembler - which translates assembly languageinto machine code.When it comes to high-level languages, there aretwo ways of performing this translation.CompliersCompilers take the whole program written in a high-level language and translate it all into machine codebefore it will run.When compiling code (which can take quite a while),if there are any errors or bugs these are all found atthe same time; the process of compiling will stop and the programmer can then gothrough and fix all of these errors.Once all of the errors are fixed, the program can be compiled again and will run error free -usually much quicker than an interpreted program as all of the translation happens beforethe program runs - not during it.Once programs have been complied, they don’t need to be complied again, so the originalsource code is not required. This makes it very difficult for individuals to reverse engineeror change the software (which is seen as an advantage to software developers). 172

Complied programs will only run on the computer system that they were designed for asthe process of compiling generates CPU specific machine code. If you compile a programto work on a particular CPU using a particular instruction set, it won’t run on other CPUswith different instruction sets.InterpretersInterpreters take one high-level line of code at a time, translate it into machine code andrun it before fetching and translating the next.Developers love interpreted languages as it’s much easier to find bugs when coding. Theycan keep running their programs and once an error is found, the developer can fix it andrun the program again to find the next bug.Interpreters need to translate programs line by line while the program is running which canslow down the running of a program and will take up more memory (RAM).As interpreted programs are translated at runtime (when you launch the program becauseyou want to use it - the translation happens), they are portable. No machine code iscreated in advance so the program can usually run on a range of different CPUs; theinterpreter will then translate the program using the correct instruction set while theprogram executes.Compiler InterpreterThe whole program is translated before execution Each line of code is translated one by one while the program runsThe compiled program does not need the original The program is not compiled before distribution orsource code so this prevents reverse engineering sale, therefore the source code is easier to reverse engineer.The program runs faster as memory and CPU power Translation happens as the program runs which canis not being used for translation make the program run slowerErrors for the entire program are generated at the Easier for developers during debugging as one line ofsame time making debugging harder code is executed at onceProgram is translated for a particular CPU, so once Can run on most computer systems as the programcompiled it will not work on other types of CPU. is translated each time for that particular CPU 173

The BasicsPrint StatementComputers are defined as being systems that take inputs, process the data and generateoutputs. We need outputs in order to understand what a computer system is doing sothat we can interact with it. In Python, the print statement is used to output data anddisplay this on the screen. The print statement does not send anything to your printer. 174

print(“Hello and welcome to Computing Academy”) Hello and welcome to Computing AcademyInput StatementIt is also often necessary to enter data into the computer system, for example whenplaying a computer game, using an app or browsing a webpage. In Python we can use theinput statement to prompt the user to enter information as follows: input(“Please enter your age”) Please enter your ageThis code will prompt the user to enter their age, but it will not store or remember what theuser types in. In order to store this information we will need to assign it to a variable likethis: age = input(“Please enter your age”)Now, when the user is prompted to enter their age, anything they type in is stored in thevariable age so that we can recall and use that data later.Let’s talk more now about variables. 175

Variables and ConstantsWhat are Variables?Variables are one of the most basic concepts in computer programming. Computers storedata whilst programs run, even when we haven’t specifically asked them to (by choosingFile -> Save As).Computer games record how many lives and points you have, and which level you are on;when switching between several applications, web browsers remember which website youare on and how far down the page you have scrolled; when typing an essay or report, aword processor remembers what you have typed when switching to your email and back.All this happens even though we haven’t performed a ‘File -> Save As’.Programmers use variables when writing programs to temporarily save this type of data. 176

Understanding Variables Picture a bank which has a vault full of safety deposit boxes. Customers of the bank can rent a safety deposit box and store anything they like within it such as money, jewellery and documents. Each box will have a number so that it can easily be identified. Customers can visit their safety deposit box whenever they like; add things into thebox, take things out of the box or change the contents of the box altogether. When thecustomers goes to the bank they will use the identifier (number) so that they get thecorrect box.You can think about variables a little like bank safety deposit boxes.Computer memory has lots of locations in which data (like lives or points in a game) canbe stored. During the course of play, the game will need to regularly access a location inmemory to store ‘lives’ and then access it again later to update ‘lives’ if the player gains orloses a life.Rather than using a number as an identifier (like a safety deposit box), we usually giveeach variable a meaningful name or identifier so that we can refer to it throughout aprogram. A computer game might do something like this:numLives = 10 177

This line of code stores or assigns the number 10 to a variable (a space in memory a littlebit like a safety deposit box) with the name or identifier numLives.Perhaps during the game a player would like to know how many lives they have left. print(numLives) 10This line of code simply reads the value of the variable numLives (by going to thatlocation in memory and fetching the value); it then uses print to display this on thescreen.During gameplay we might gain 3 lives. The computer would need to update the variableto reflect this.numLives already exists (we made it at the start of the game and assigned to it the value10. We now just want to increase the existing value of numLives by 3. numLives = numLives + 3 print(numLives) 13This line of code means “the new value of numLives should be equal to itself + an extra3”. numLives was 10 to start with, so now when we print numLives, we get 13. 178

Key Point Variables are called variables because the values which they store can change (vary) throughout the program.Websites, apps and computer games often want to personalise the experience that usershave. It’s very common therefore to save the users’ name. playerName = “Rachel”Here, we have created a new variable and given it the name (or identifier) playerName.We’ve then assigned the value “Rachel” to that variable. We could now go ahead anddisplay this back to the user, perhaps with a nice welcome message like this: playerName = “Rachel” print(“Hello, ” + playerName + “how are you?”) Hello, Rachel how are you?Notice how we write ‘Hello playername’, rather than ‘Hello Rachel’? This is because wewant to make use of the data that we have just stored into the variable calledplayerName. 179

ConstantsConstants are similar to variables, but the values that they store cannot vary...they stayconstant.Constants are used to store data whilst a computer program runs; like variables, they alsohave a name or identifier which can be used to refer to the constant.Variables can change during a program, for example if we gain additional lives, we’dupdate numLives to reflect this; constants cannot. Once a constant is declared at thestart of a program and a value is assigned to it, this cannot change.A timer program that needs to know how many minutes are in an hour, a day and a weekmight declare the constants hour, day and week. hour = 60 day = 1440 week = 10080These constants should not, and will not change during the program.A program used to calculate how much tax a company needs to pay on it’s profits mightdeclare the constant taxrate at the start of the program like this: profit = 5000 taxrate = 0.20Later, the constant taxrate might be used as follows: 180

taxdue = profit * taxrate print(taxdue) 1000In this example, we could have just used 0.20 in the place on the constant taxrate, butby declaring the constant at the beginning of the program and using it throughout aprogram, should the rate of tax change, we’d only need to modify the constant at thebeginning of the program rather than working through many lines of code looking for everyoccurrence of 0.20. 181

Data TypesWhat Are Datatypes?Data comes in many different varieties and the computer needs to know which type ofdata it is working with. This allows the computer to ensure enough space is reserved inmemory for the variable or constant you need to store.Python automatically recognises and assigns a datatype but some programminglanguages do not as you will see in the following examples. 182

IntegerIntegers are whole numbers like 5, 34, 0, 4, -32, and -7. In Python we candeclare a variable to hold an integer and assign a value to it as follows: age = 25Some programming languages require you to specify the datatype when declaring thevariable. In Java, to declare the same variable we would write: int age = 25;Real (Float)Real numbers (also known as floating point numbers) are those with decimals orfractions such as 3.45, 1.07, 5673.4, and -5.5. In Python we declare a variable tohold a float and assign a value to it as follows: price = 149.50In Java, this would be: float price = 149.50f 183

BooleanBoolean records the value True or False. In Python we declare a variable to hold aboolean value and assign a value to it as follows: answer = TrueNote here that Python requires the capitalisation of the T in True. False would alsorequire a capital FIn Java, this would be: boolean answer = true;Note here that Java requires the t in true and f in false do not have capital letters.StringA string can hold any sequence of alphanumeric characters including text, numbers andsymbols. In Python we a declare string as follows: name = “Rachel”In Java, this would be: String name = “Rachel”;Note here that Java requires the declaration of datatype String has a capital S. 184

In both Python and Java, notice that the string we wish to assign to the variable name isenclosed in speech marks. This differs to how we assign integers or real numbers to avariable where we do not need to use speech marks.When working with strings, even if we choose to store numbers within the string(remember, we can use any alphanumeric character including letters, numbers andsymbols within a string) we will not be able to perform any mathematical calculations onthose numbers. If for example we did the following: age = “20”As we have assigned a string to the variable age, we could not now do something like: age = age + 5Depending on the programming language being used, doing so would either result in anerror being displayed, or in the new value being ‘205’ rather than the intended result of 25as the two values have been concatenated (joined together) rather than added together. 185

OperatorsWe would not be able to create useful and engaging applications if the only thing we coulddo was assign values to variables. We need to be able to perform mathematicaloperations, comparative operations and logical operations.Mathematical OperatorsSome of the mathematical operations that you will need to use frequently whenprogramming include: addition (+), subtraction (-), multiplication (*), division (/), integerdivision (//) and modulo (%).Mathematical operations can only be performed on numerical data types such asintegers and real numbers. 186

The following would not work as “Rachel” is a string, so we cannot divide it by 2: name = “Rachel” newName = name / 2Add (+)Here is an example of addition using the + operator to work out a total price: price1 = 10 price2 = 15 totalprice = price1 + price2 print(totalprice) 25The + operator has been used to add together the values stored in the two variablesprice1 and price2 and store the result into another variable called totalprice.The value stored in the variable totalprice has then been displayed on screen usingprint. 187

Subtract (-)The subtract operator can be used to work out how much money you would have afterpaying tax. grosspay = 1000 tax = 100 wages = grosspay - tax print(wages) 900Multiply (*)The multiple operator can be used to calculate the revenue (money received) by selling acertain quantity of a product. price = 50 numSold = 10 revenue = price * numSold print(revenue) 500 188

Divide (/)The divide operator can be used to work out how much each person needs to pay whensplitting the bill in a restaurant. bill = 250 people = 4 each = bill / people print(each) 62.5Integer Divide (//)In the previous example, the result, 62.5, is a real number (not an integer or wholenumber). There may be times when you wish to perform a division operation andautomatically disregard any decimal place, returning the result as an integer. When bakingcupcakes, you might wish to calculate roughly how many cakes you’ll be able to makewith one bag of flour. Decimal places are irrelevant here as you can’t have 0.3 of a cake. flour = 1000 eachCake = 35 numCakes = flour // eachCake print(numCakes) 28 189

This code assigns the amount of flour used by one cupcake - 35g - to the variableeachCake, and the amount of flour in a bag - 1000g - to another variable flour.A standard divide operation: 1000 / 35 would give the result 28.57, but using integerdivision as shown in the code above results in 28 - the 0.57 has been discardedModulo (%)A cupcake business needs to be careful not to waste stock, so they might decide to workout what is left over after each batch. Modulo simply the remainder of a division. mix = 3000 eachCake = 55 numCakes = mix % eachCake print(numCakes) 30Here the result shows that if we had a cupcake mix of 3000g and each cupcake needed toweigh 55g, we would have 30g of mix left over. It does not show us how many cakes wecan make, it only shows us the remainder. 190

Comparison OperatorsWe often want to compare values and depending on the result of this comparison take acertain course of action. We can compare whether one value is equal to another (==), notequal to another (!=), greater than another (>), greater than or equal to another (>=), lessthan another (<) or less than or equal to another (<=). Key Point Note the difference between = and ==. The single = symbol is used for assignment; we use this when we wish to assign a value to a variable. The double == symbol is used for comparison between two values.Equal To (==)We are using the Internet more and more for a variety of different purposes includingsocialising, banking, shopping, work and school. It’s now more important than ever thatour online accounts are secure, and one measure that is in place to ensure our security isthe use of passwords.A secure system will need to check that the password entered by a user matches thepassword that has been previously saved. 191

userEntered = input(“Please enter your password”) actualPassword = “gh%yuN&” if userEntered == actualPassword: print(“Correct Password”) else: print(“Incorrect Password”)We create a variable called userEntered and then prompt the user to type in theirpassword using input. Anything that the user types in is stored into the userEnteredvariable.We also have a variable called actualPassword to which we assign the correctpassword.We then need to check whether the two passwords match. Has the user typed in thecorrect password?We use an if statement to compare the two passwords and the comparison operator== which means ‘equal to’. If the first password userEntered is equal to (==) the secondpassword, actualPassword, then we print a message saying Correct Password.If this is not the case and userEntered is not equal to actualPassword we move tothe else clause of our if statement and instead print the message IncorrectPassword. 192

This is what the output would look like if we were to type in the password incorrectly. Please enter your password 12345 Incorrect PasswordThis is what the output would look like if we were to type in the password correctly. Please enter your password gh%yuN& Correct PasswordNot Equal To (!=)We could have written code to perform the same password check using the not equal (!=)comparison operator instead like this. userEntered = input(“Please enter your password”) actualPassword = “gh%yuN&” if userEntered != actualPassword: print(“Incorrect Password”) else: print(“Correct Password”) 193

Notice that we are now using the != operator in the if statement, so if userEnteredis not equal to actualPassword we print the message Incorrect Password.If this is not the case and userEntered is equal to actualPassword we move to theelse clause of our if statement and instead print the message Correct Password.Greater Than (>)We can use the greater than (>) operator to compare two value; a bank system, forexample, might check to see if a customer has enough funds in their account to make apurchase. currentBalance = 50 purchasePrice = 200 if purchasePrice > currentBalance: print(“Not enough funds”) else: print(“You have enough funds”)Less Than (>) and Less Than or Equal To (>=)A company that buy second hand cars may only want to buy cars with less than 100,000miles left on the odometer. The following code could compare a car’s milage with this limit. 194

limit = 100000 carMileage = 75423 if carMileage <= limit: print(“OK, we’ll buy your car”) else: print(“Sorry, you car has done too many miles”)The code compares the two variables limit and carMileage. Note that here we haveused the <= operator rather than just the < operator.limit is set at 100,000. This means that as long as a car has not done more than100,000 miles, the company will buy it - so a car that has done exactly 100,000 is OK.Using the <= operator ensures that cars with exactly 100,000 miles are accepted.If we only use the < operator like this: if carMileage < limit.........then a car that has done 100,000 miles would be rejected, because carMilage =100000, and 100,000 is not less than the 100,000 limit - they are the same. 195

Logical OperatorsLogical operators can be used in conjunction with comparison operators to build morecomplex comparisons.ANDConsider a website that can be used by customers to search for new cars. Customers canspecify their requirements, for example, the colour must be red and the brand must beVolkswagen. if colour == “red” and brand == “volkswagen”: print(“We’ve found a car for you”) else: print(“Sorry, no cars match your search”)This code above uses the equal to (==) comparison operator to check whether thecolour of this car is equal to red. Another == is used to check whether the brand isequal to Volkswagen.If the customer wants both criteria to be met, the and logical operator can be used tospecify that both conditions must be met before we use the print statement to displaythe message We’ve found a car for you to the user.ORIf the customer was not able to find a red volkswagen then she may have to expandher search. Rather than searching for a red car, the customer instead wants to search forcars manufactured by Volkswagen or Audi. 196

if brand == “Audi” or brand == “volkswagen”: print(“We’ve found a car for you”) else: print(“Sorry, no cars match your search”)The code above used the or logical operator. If either of the conditions is met, the printstatement will display the message We’ve found a car for you. It is not necessaryfor both conditions to be met. It neither of the conditions are met, we move to the elseclause of the if statement and the second print statement displays the messageSorry, no cars match your search.NOTThe not logical operator inverts, or gives the opposite of an expression. age = 25 age == 25 TrueIn the code above, we first assigned the value 25 to a variable called age. We then usedthe expression age == 25 which checks to see whether the value assigned to thevariable age is equal to 25. In this case it is, so we see the output True. 197

age = 25 not age == 25 FalseIn the code above, the output should be True (because 25 is equal to the value assignedto age, but we have used the logical operator not, which inverts the result. 198

IF StatementsUsing IfPrograms need to make selections and decisions all the time; if statements can changethe path taken through a computer program and select a new path. The basic structure ofan if statement is as follows:if [this condition is met] then [do this]else [do this] 199


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