05 Constants and Variables Mark Dixon Page 1
05 – Constants and Variables Mark Dixon Page 1
Admin: Test (next week) • In class test – teaching week 6 • 50 mins • short answer (5 - 6 words max) • 50% of coursework mark Mark Dixon Page 2
Questions: Conditional Execution • What is the result of (txt. Fah. Value is 50): (txt. Fah. Value >= 40) true • What will txt. Tax be after the following code has executed (txt. Salary. Value is 4589): If txt. Salary. Value < 5035 Then txt. Tax. Value = 0 Else txt. Tax. Value = txt. Salary. Value * 0. 20 End If 0 Mark Dixon Page 3
Session Aims & Objectives • Aims – Introduce you to (invisible) data storage concepts, i. e. constants and variables • Objectives, by end of this week’s sessions, you should be able to: – declare and use constants – declare a variable – assign a value to a variable, • using combination of literal values, operators, functions, and identifiers – Determine whether a variable or procedure is in or out of scope at a given point in a piece of code – Select a variable’s scope in your own program Mark Dixon Page 4
Example: Moon Orbit – Analysis SPECIFICATION • User Requirements – need to keep children occupied/entertained, while learning about the moon's orbit • Software Requirements – Functional: – Orbit of moon around earth should be animated – Children should be able to control speed and direction – Non-functional should be easy and fun to use Mark Dixon Page 5
Problem solving: Pseudo-code • To solve problem – think about how you would solve it manually (without computer) – think of steps you would take • Moon position – increase angle – move moon • horizontal position • vertical position 1 2 3 • Convert to code Mark Dixon Page 6
Trigonometry: In general angle (ang) hypotenuse (H) adjacent (A) = Cos(ang) * H opposite (O) = Sin(ang) * H Mark Dixon Page 7
Trigonometry: Moon Orbit angle (ang) Cos(ang) * 150 Sin(ang) * 150 Mark Dixon Page 8
Example: Moon Orbit v 1 <html> <head> <title>Moon orbit</title> <script language=vbscript> Sub Window_On. Load() img. Moon. Style. Pixel. Left = img. Earth. style. pixelleft img. Moon. Style. Pixel. Top = img. Earth. style. pixeltop + 150 window. Set. Interval "Moon. Rotate", 50 End Sub Moon. Rotate() par. Angle. Inner. Text = par. Angle. Inner. Text + 0. 025 1 2 img. Moon. Style. Pixel. Left = img. Earth. style. Pixel. Left + (Sin(par. Angle. Inner. Text) * 150) 3 img. Moon. Style. Pixel. Top = img. Earth. style. Pixel. Top + (Cos(par. Angle. Inner. Text) * 150) End Sub </script> </head> <body bgcolor=black> <p id=par. Angle style="color: Yellow">0</p> <img id=img. Earth style="position: absolute; left: 200; top: 200; " src=Earth. gif> <img id=img. Moon style="position: absolute; " src=Moon. gif> </body> </html> Mark Dixon Page 9
Problem: Magic Numbers <html> <head> <title>Moon orbit</title> <script language=vbscript> Sub Window_On. Load() img. Moon. Style. Pixel. Left = img. Earth. style. pixelleft img. Moon. Style. Pixel. Top = img. Earth. style. pixeltop + 150 window. Set. Interval "Moon. Rotate", 50 End Sub • Some numbers represent the same thing – e. g. the orbit Sub Moon. Rotate() par. Angle. Inner. Text = par. Angle. Inner. Text + 0. 025 img. Moon. Style. Pixel. Left = img. Earth. style. Pixel. Left + (Sin(par. Angle. Inner. Text) * 150) img. Moon. Style. Pixel. Top = img. Earth. style. Pixel. Top + (Cos(par. Angle. Inner. Text) * 150) End Sub </script> </head> • changes – take time – could make mistake <body bgcolor=black> <p id=par. Angle style="color: Yellow">0</p> <img id=img. Earth style="position: absolute; left: 200; top: 200; " src=Earth. gif> <img id=img. Moon style="position: absolute; " src=Moon. gif> </body> </html> Mark Dixon Page 10
Constants (what and how) • name used to represent literal value Const name = expression • example: Const last = 5 • useful for removing 'magic numbers' • value can’t be changed last = 7 Mark Dixon Page 11
Example: Moon Orbit v 1. 1 <html> <head> <title>Moon orbit</title> <script language=vbscript> Declaration Const orbit = 150 of Constant • only need to change constant declaration Sub Window_On. Load() img. Moon. Style. Pixel. Left = img. Earth. style. pixelleft img. Moon. Style. Pixel. Top = img. Earth. style. pixeltop + orbit window. Set. Interval "Moon. Rotate", 50 End Sub Use of Constant Sub Moon. Rotate() par. Angle. Inner. Text = par. Angle. Inner. Text + 0. 025 img. Moon. Style. Pixel. Left = img. Earth. style. Pixel. Left + (Sin(par. Angle. Inner. Text) * orbit) img. Moon. Style. Pixel. Top = img. Earth. style. Pixel. Top + (Cos(par. Angle. Inner. Text) * orbit) End Sub </script> </head> J quicker J fewer mistakes J meaningful <body bgcolor=black> <p id=par. Angle style="color: Yellow">0</p> <img id=img. Earth style="position: absolute; left: 200; top: 200; " src=Earth. gif> <img id=img. Moon style="position: absolute; " src=Moon. gif> </body> </html> Mark Dixon Page 12
Constants: missing = <html> <head> <title>Errors with Constants</title> <script language=vbscript> Const hi = 4 Const low par. C. Inner. Text = "Hello" par. C. Inner. Text = 23 par. C. Inner. Text = hi hi = 6 </script> </head> <body> <p id=par. C></p> </body> </html> • Mark Dixon must give constant a value Page 13
Constants: Illegal assignment <html> <head> <title>Errors with Constants</title> <script language=vbscript> Const hi = 4 Const low = 1 par. C. Inner. Text = "Hello" par. C. Inner. Text = 23 par. C. Inner. Text = hi hi = 6 </script> </head> <body> <p id=par. C></p> </body> </html> • Mark Dixon cannot change value of constant Page 14
Questions: Constants • Consider the following code: Const Lives = 5 Const Players Lives = 7 document. title = Lives 2 • How many constants are in it? • Which lines are OK? first and last • Write a line of code that declares a constant for pi (3. 141592) Const pi = 3. 141592 Mark Dixon Page 15
Problem: Intermediate Results <html> <head> <title>Moon orbit</title> <script language=vbscript> Const orbit = 150 • Intermediate result (angle) stored in object property Sub Window_On. Load() (par. Angle. Inner. Text) img. Moon. Style. Pixel. Left = img. Earth. style. pixelleft img. Moon. Style. Pixel. Top = img. Earth. style. pixeltop + orbit window. Set. Interval "Moon. Rotate", 50 End Sub – verbose Sub Moon. Rotate() par. Angle. Inner. Text = par. Angle. Inner. Text + 0. 025 img. Moon. Style. Pixel. Left = img. Earth. style. Pixel. Left + (Sin(par. Angle. Inner. Text) * orbit) img. Moon. Style. Pixel. Top = img. Earth. style. Pixel. Top + (Cos(par. Angle. Inner. Text) * orbit) End Sub </script> </head> – visible <body bgcolor=black> <p id=par. Angle style="color: Yellow">0</p> <img id=img. Earth style="position: absolute; left: 200; top: 200; " src=Earth. gif> <img id=img. Moon style="position: absolute; " src=Moon. gif> </body> </html> Mark Dixon – takes lot of memory Page 16
Variables (why? ) • Variables useful for: – reducing memory use – speed up execution – storing information you don't want user to see – storing intermediate results of calculations temporarily: • makes code easier to understand, & • prevents need to re-calculate – making code easier to read (short variable name instead of long object. property names) Mark Dixon Page 17
Variables (what) • Variables have – Identifier (name) – you choose this, used to refer to (reference) variable – Value – you set/change this x 23 Name/Identifier Value Mark Dixon Memory Page 18
Variable declaration (how) • Variables must be declared, using the following syntax (grammar): Dim identifier e. g. Mark Dixon Dim Dim weight x s year represents the name of the variable Page 19
Variable assignment (how) • Variables are assigned values, using the following syntax: identifier = expression e. g. x weight name s = = 5 109. 45 "Bob" "Hello " Note: the data flows backwards (from right to left) Mark Dixon Page 20
Variables: Numeric Data Mark Dixon Page 21
Variables: String Data Mark Dixon Page 22
Example: Moon Orbit v 1. 2 <html> <head> <title>Moon orbit</title> <script language=vbscript> Const orbit = 150 Declaration Dim ang code J invisible to user of Variable Sub Window_On. Load() J memory efficient img. Moon. Style. Pixel. Left = img. Earth. style. pixelleft img. Moon. Style. Pixel. Top = img. Earth. style. pixeltop + orbit window. Set. Interval "Moon. Rotate", 50 J faster execution ang = 0 End Sub J shorter initial value Sub Moon. Rotate() change value ang = ang + 0. 025 img. Moon. Style. Pixel. Left = img. Earth. style. Pixel. Left + (Sin(ang) * orbit) img. Moon. Style. Pixel. Top = img. Earth. style. Pixel. Top + (Cos(ang) * orbit) Use of End Sub </script> Variable </head> <body bgcolor=black> <img id=img. Earth style="position: absolute; left: 200; top: 200; " src=Earth. gif> <img id=img. Moon style="position: absolute; " src=Moon. gif> </body> </html> Mark Dixon Page 23
Example: Moon Orbit v 1. 3 • How can we change the speed and direction of the moon? Mark Dixon Page 24
Option Explicit • Must be first line of script • Useful to force explicit variable declaration: • Undeclared variables produce error message: <script language=vbscript> Option Explicit Dim length = 6 age = 5 </script> Mark Dixon Page 25
Questions: Variable declaration • Write a line of code that: – Declares a variable called x Dim x – Declares a variable called y Dim y – Declares a variable called surname Dim surname – Declares a variable called age Dim age Mark Dixon Page 26
Questions: Variable assignment • Write a line of code that: – Assigns the value of 23 to the variable y y = 23 – Assigns the value of 14. 6 to the variable x x = 14. 6 – Assigns the value of ‘John’ to the variable surname = "John" Mark Dixon Page 27
Questions: Variable assignment 2 • Write a line of code that: – Increases the value of x by 2. 89 x = x + 2. 89 – Decreases the value of z by y z = z - y – Divides Km by 1. 6 and puts the result in Miles = Km / 1. 6 – Joins two strings Surname and Forenames together, putting the result in Long. Name = Surname & Forenames Mark Dixon Page 28
Example: Guess. Num – Analysis SPECIFICATION • User Requirements – need to keep children occupied/entertained, while learning about maths • Software Requirements – Functional: – computer picks a number between 0 and 10 – user enters a number – compare numbers and display appropriate message – Non-functional should be easy and fun to use Mark Dixon Page 29
Example: Guess. Num - Code <head> <script language="VBScript"> Option Explicit Dim Guess. Num Sub window_On. Load() Randomize Guess. Num = Int(Rnd() * 10) lbl. Result. inner. Text = Guess. Num End Sub Generate Random Number between 0 and 10 Temporary line (helps us test) Sub btn. Guess_On. Click() If CInt(txt. Guess. Num. Value) = Guess. Num Then lbl. Result. Inner. Text = "Correct" Else lbl. Result. Inner. Text = "Wrong, please try again" End If End Sub </script> </head> <body> <p>I am thinking of a number between 0 and 10 <input type=text id=txt. Guess. Num> <input type=button id=btn. Guess value=Guess> <p>Please guess the number <p id=lbl. Result> </body> Mark Dixon Page 30
Variables: Errors Option Explicit Dim z OK, explicit variable declaration OK Sub Dim Dim y z End OK OK OK Duplicate definition error. Variable not defined error. OK, as z is page level Mark Dixon Window_On. Click() s x x = 5 Sub Page 31
Variable Scope (what) • Scope – accessibility/visibility – Local (declared within procedure) – Page (general declarations) Mark Dixon Page 32
Variable Scope (How) Option Explicit Dim mv Sub btn. Calc_On. Click() Dim lv 1. . . End Sub • Page variables – general declarations (top) • Local variables: – in procedures Sub btn. Add_On. Click() Dim lv 2. . . End Sub Mark Dixon Page 33
Variables: Scope (How) Mark Dixon Page 34
Variable Scope (why) • In short – Robustness of code/software – Protection from accidental outside interference • One of many responses to code that is – Difficult to maintain, and – Unreliable – House of cards phenomenon • Prevent: – Uncontrolled and ad hoc interactions between code • Always define things at lowest level needed Mark Dixon Page 35
Variable Scope Errors • Spot the error in the following: Option Explicit Sub btn. Calc_On. Click() Dim x x = 0 lbl. Total. Inner. Text = "£" & x End Sub Variable not defined Sub btn. Quit_On. Click() error x = 0 lbl. Total. Inner. Text = "£" & x End Sub Mark Dixon Page 36
Example: Ball Char (v 2. 5) <html> <head> <title>Test</title> <script language="VBScript"> Sub Window_On. Load() Window. Set. Interval "Move. Ball. Right", 50 End Sub Move. Ball. Right() If (pic. Ball. hspace + 5) < (document. body. clientwidth - pic. Ball. W pic. Ball. hspace = pic. Ball. hspace + 5 Else Window. Set. Interval "Move. Ball. Left", 50 End If End Sub Move. Ball. Left() If (pic. Ball. hspace) > 0 Then pic. Ball. hspace = pic. Ball. hspace - 5 Else Window. Set. Interval "Move. Ball. Right", 50 End If End Sub </script> </head> <body bgcolor="#00 ff 00"> <p><img id=pic. Ball src="Ball. Char. jpg" hspace=0 vspace=11></p> </body> </html> Mark Dixon Page 37
Example: Ball Char (v 3) <html> <head> <title></title> <script language=VBScript> Dim h. Inc page variable Sub window_On. Load() window. set. Interval "Ball. Move", 50 h. Inc = 5 End Sub local variable Using variables: J shorter code J invisible to user J memory efficient J faster execution Mark Dixon Sub Ball. Move() Dim nxt = img. Ball. style. pixelleft + h. Inc If nxt >= 0 And nxt + img. Ball. width =< document. body. clientwid img. Ball. style. pixelleft = nxt Else h. Inc = -h. Inc End If End Sub </script> </head> <body style="margin-left: 0"> <img id=img. Ball src="BALLCHAR. gif" style="position: absolute" /> </body> </html> Page 38
Question: Variable Scope • Will this compile? Option Explicit Dim v Dim x … Sub Window_On. Load() Dim z x = 23 y = "there" z = 12 end Sub btn. Test_On. Click() Dim y y = "hello" x = 67 z = 53 End Sub Mark Dixon Is x in scope? Is y in scope? Is z in scope? Yes No Yes Is y in scope? Is x in scope? Is z in scope? Yes No Page 39
Tutorial Exercises: Moon Orbit • LEARNING OBJECTIVE: use constants and variables to simplify and make code more dynamic • Task 1: Get Moon Orbit examples working (v 1 to v 1. 2). The code is provided on the slides. • Task 2: Modify your page to allow the user to stop speed up and change the moon's direction (v 1. 3). Use the existing code as inspiration. • Task 3: Modify your page so that it makes a water noise when the mouse moves over the Earth, and the ohh noise over the moon. Use code from previous lectures as inspiration. • Task 4: Modify your page so that the diameter and mass of the Moon are displayed when the mouse moves over it. Do the same for the Earth. Go on-line to find the diameter and mass information. Mark Dixon Page 40
Tutorial Exercises: Guess Num • LEARNING OBJECTIVE: use constants and variables to simplify and make code more dynamic • Task 1: Get Guess. Num example working. • Task 2: Modify Guess. Num to tell the user whether their incorrect guess was higher of lower than the correct number. • Task 3: Modify Guess. Num to only allow 5 attempts before picking a new number. Mark Dixon Page 41
Tutorial Exercises: Ball Char • LEARNING OBJECTIVE: use constants and variables to simplify and make code more dynamic • Task 1: Get the Ball Char (v 3) example working. • Task 2: Add sound to the Ball Char (v 3) example. • Task 3: Get the Ball Char moving diagonally, bouncing off all four sides of the window. • Task 4: Modify your page so that it allows the user to control how fast the ball character moves. Mark Dixon Page 42
- Slides: 42