What Is Programming? - We are teaching london computing
Session 1 Reference NotesGCSE Python RecapWhat Is Programming?Programming is:Creating a recipe or procedure for solving a problem in steps.Translating the recipe into a particular programming languageA recipe or procedure is also called an algorithm. Creating an algorithm to solve a problem is a form of problem solving; it does not depend on the choice of programming language.At first, writing a program in a particular language seems the main challenge. But this is misleading: once the basics of programming have been mastered, ‘creating recipe’ is the harder skill. Someone who has mastered the skill of ‘creating recipes’ can quickly learn an additional language. Exercise 1 Answer: Largest two items from a list.The following algorithm goes through the list once:largest max(first item, second item)nextLargest min(first item, second item)while more items in list item next item if item GT nextLargest if item GT largest nextLargest largest largest item else nextLargest itemA simpler approach is to find the largest twice, though this means going through the list twice:largest largest item of listremove largest from listsecond largest largest item of new listThe idea of computational thinking tries to express the essence of both aspects of programming, separately from the task of actually writing programs. Computational thinking is becoming an explicit part of some A level curricula.Look out for the CAS document “Developing computational thinking in the classroom: a framework”. This defines Computational Thinking, originally proposed by Professor Jeannette Wing, as:“... the thought processes involved in formulating problems and their solutions so that the solutions are represented in a form that can be effectively carried out by an information-processing agent” ... “these solutions can be carried out by any processing agent, whether human, computer, or a combination of bothand says that the following core concepts make up Computational Thinking:algorithmic thinking: developing stepsdecomposition: spotting the parts of a problemabstraction: ignoring unnecessary detailgeneralisation: making the specific more generalevaluation: how good is it?Note that other concepts may also be included (see for example the OCR exam board curriculum). A talk by Simon Peyton-Jones (Microsoft and CAS) motivates the idea. See: A description video Programming ConceptsBasic ConceptsThe following concepts are found in all (imperative) programming languages.ConceptsPython Example(s)Literal (Constant)'abc' "william" 42 3.14159Expression2**3**4 "he"+"llo" x > 5Assignmentarea = length * widthSequencex = 7y = x - 5Selectionif x > 5: Loopwhile x < 7:Function callprint("ans=", ans)Function definitiondef area(l, w):TypesValues belong to particular type. Unlike many languages, in Python types are determined ‘dynamically’, meaning that the type of a variable is decided as it is used and can change from one type to another. Simple types in Python are:IntegerStringFloating pointBooleanListMore types exist. The function type() can be used to find the type of an expression. Here are some examples:>>> type(123)<class 'int'>>>> type(1+ 3)<class 'int'>>>> type("hello" * 3)<class 'str'>>>> type("hello" - 'world')Traceback (most recent call last): File "<pyshell#5>", line 1, in <module> type("hello" - 'world')TypeError: unsupported operand type(s) for -: 'str' and 'str'ExpressionsThe expressions available depend on the type of values. Here is a table of common expressions:TypeOperatorsFunctions/MethodsNumbers+ - * ** / // %str() abs() pow()String+len() int().append() .remove() .split() .count()Boolean results== != > < >= <= Boolean operandsand or notListin not in [:]len() min() max()In most languages, including Python:Some operators are ‘overloaded’, meaning that they can be applied to operands of different types. The behaviour depends on the type.The set of operator is fixed but more functions or methods can be added. LibraryLearning the language is only the start! In fact, it can be hard to distinguish between the library and the programming language proper. For example, print() is usually presented to beginners as part of the language whereas it is really a built-in function from the library.The library is a large collection of functions, methods and module. E.g. the random module.The standard library is part of all Python installations.Other packages can be installed when needed; there are lots available.The library documentation is online: The documentation is usually available from within a development tool, such as IDLE.ScopeThe word ‘scope’ refers to the variables available at different places in a program. Python uses dynamic scoping: a variable is added by executing an assignment to it. In many other languages (e.g. Java, C++): i) variables must be declared (that is, introduced or announced before they are used and ii) scoping depends only on where in the program a variable is declared; it dos not depend on what happens when the program is run. In Python:Variable assigned in the top level of a file (i.e. not inside a function) are added to the global scope.Each function definition creates its own new scope, called the local scope. Assignments in functions are to local variable unless the global keyword is used.Parameters behave like local variables.A global variable can be referenced provided it is not changed. The following program illustrates the different possibilities.def function1(myParam): # function with parameter and return myLocal = myParam * 2 # both variables are local return myLocal # return a valuedef function2(): # function reading a global variable myLocal = glVar * 2 # local variable updated return myLocal # return a valuedef function3(): # function updating a global variable global glVar # name the global variables we can change glVar = glVar * 2 # update the global variableprint(function1(3)) # prints 6glVar = 4 # adds a new variable to the global scopeprint(function2()) # prints 8, but does not change glvarfunction3() # change glvar to 8print(glVar) # ... and prints it Exercise Answer:The following program illustrates Python scoping.def printX(): print("This is x:", x) y = int(input("Enter a num> "))if y % 2 == 0: x = yprintX()The program gives an error when an odd number (1, 3, 5 etc.) is entered.No errors are reported when the program is checked. The definition of the function printX() refers to a variable ‘x’; this variable is not assigned in the function so it is not local; instead, there must be a variable ‘x’ available when the function is called. This is only true if an even number is entered.This illustrates that in Python:Scoping is dynamic: names are matched to variables when the program is run.A function definition can refer to (i.e. read) a variable assigned outside the function.Learning ProgrammingAxes of LearningWe can distinguish different skills that need to be mastered to learn programming:Understanding programs. With understanding, you can predict the result of running a program. We can test this skill with example of programs and asking ‘what is the result?’. Writing programs. This skill is about choosing expressions and statements; it depends on some understanding but also requires some imagination. Finding bugs can come in here too. We can test this skill with short programs to implement or complete. Copying and adapting programs develops this skill a bit, but often does not lead to much understanding. Solving problem. This is the ability to devise a recipe to solve a problem. It is independent of details of a particular programming language but requires experience of programming. We can test this skill by setting more open problems (i.e. ones that are not specified in so much detail). These skills are not completely independent. But the distinction guides us to appropriate learning materials: after using a programming construct in a few examples (writing skill), a pupil may still need to explore it meaning (understanding skill). Deepening Understanding: Mental ModelsNot everything is understood all at once!A learner may have an initial understanding that is useful even though it is only partially correct. We can call the understanding at any stage a ‘mental model’. The mental model can explain some programs but not others.The understanding is deepened by challenging the initial understanding with progressively more demanding examples, so that a learner finds they need to refine their mental model.Example: Mental Models of AssignmentMental model 1: assignment as naming values. At first, assignment can be understood as giving a name to an expression, so that the variable can be used in the place of the expression. This understanding is sufficient to explain these programs:width = 10height = 17area = height * widthprint(area)width = 10height = 17area = height * widthvolume = area * heightprint(volume)However, this understanding does not make clear that the expression is evaluated and the value (not the expression) assigned to the variable. Here is a program that cannot be understood in this way: numA = ...numB = ...if numA < num B: numB = numA numA = numBprint("Variable numA has the larger number")Understanding this program requires us to understand that assignments are done in order. Dry running a program to show the sequence of values of each variable makes this clear.StepnumAnumBCode15numA = ...215numB = ...35numB = numA45numA = numBMental model 2: Assignment as Updating Variables. Now assignment is understood as updating a variable – which is a location in the memory – with a value. This understanding improves on the first understanding and correctly explains more programs.This understanding can be extended to programs with arrays (or lists in Python):lst = [1,3,5,7]lst[3] = lst[1]lst[0] = lst[0] + lst[1]print(lst) This program adds the idea that the left hand side of the assignment may be a part of a larger structure.Now consider the following program, with a supposed explanation on the right hand side.myFriends = ["John", "Jo"]yourFriends = myFriendsmyFriends.remove("Jo")yourFriends.append("Jane")print(myFriends)My friends are John and JoYour friends are the same as mineJo is not my friend any longerJane is your friendWhat is printed by this program? You might expect that my (only) friend is John, while your friends are John, Jo and Jane. But this is not how the program behaves, as there is only a single list of friends containing John and Jane.The problem is the assignment statement:yourFriends = myFriendsThis does not copy the list as mental model 2 would predict. Instead, the two variables refer to the same list. These variables contain “references” and the references are copied, rather than the values they refer to. So an assignment updates a variable, which is a location in memory. The memory location may contain a value or a reference to a value, depending on the type of the value. Problem SolvingTo solve a problem, it is vital to understand it. Try out some examples to check this. Another useful idea is to simplify the problem: make progress by solving a simpler problem at first.Before writing a program, we need to specify precisely what behaviour is expected. Then we need ‘stepping stones’ towards the solution. Techniques from GCSE for this include pseudo code and flowcharts.Software DevelopmentMany people have tried to describe the way that programs are written. These descriptions (or ‘lifecycle models’) are not exact!Analyse: understand the problem. Write a specification.Design: plan the software.Implement: write the softwareTest: … and test it.The dotted loop expresses the idea that the process may run in stages. What Are Programmers Like?Programmers need to be logical (or analytical), resilient (or determined) and imaginative (or creative). ................
................
In order to avoid copyright disputes, this page is only a partial summary.
To fulfill the demand for quickly locating and searching documents.
It is intelligent file search solution for home and business.
Related download
- dynamic programming introduction weighted interval
- deconstructing dynamic symbolic execution
- the python guide for beginners
- object oriented design with python
- introduction to python university of pennsylvania
- static and dynamic method unboxing for python
- functions in python
- terms university of delaware
- what is programming we are teaching london computing
- assignment no