String Manipulation

o    Throughout your use of JavaScript in a production environment, you will often use it to read values from variables, and alter a behaviour based on what it finds.

o   We have already seen some basic string reading in the section on comparisons where we test for equality. However, this allor-nothing approach is often not subtle enough for our purposes.

o   Take the case where we want to check a user’s name against a list of known users. If the user enters their name as “Karen”, for example, that will be fine if and only if they spell the name precisely as we have it recorded, including capitalisation etc. If the user decides to type in her full name, say “Karen Aaronofsky”, the code will not recognise her.

o   In this case, we want to see if the text “Karen” appears at all in the string. We call this substring searching, and it can be incredibly useful.

o   One of the simplest substring searches is done by using the indexOf method. Every string-type variable has this method associated with it. Consider this code:

      var_1 = “Deepika Sharma”;

      var_2 = var_1.indexOf(“Deepika”);

In this case, the value of var_2 will be 0 – remembering that JavaScript begins counting at 0!

o   If we were to search for a surname here: 

      var_1 = “Deepika Sharma”;

      var_2 = var_1.indexOf(“Sharma”);

      var_2 will have a value of 6.

o   Finally, if the search were to “fail”, so say we searched for the name “Anisa” as a substring, the value of var_2 would then be -1.

o   Note that this is more flexible, but still presents an issue if the user forgets to capitalise any of the substrings that we are searching for – in JavaScript, “Karen” does not equal “karen”.

o   In order to get around this, we might want to ensure that capitalisation is not taken into account. A simple way to achieve this is to force strings into lowercase before the check is performed:

    real_name = “Deepika”; name = prompt(“Your name?”,””);

   real_name = real_name.toLowerCase(); try_name = try_name.toLowerCase();

   if ( try_name.indexOf(real_name) > -1 )

     alert(“Hello Deepika!”);

} else

{

// note we use the original,  // non-lower-cased name here  alert(“Welcome “ + name); }

o   There are a number of string methods we can use to perform “value checks” on strings. A few are printed in the following table:

MethodBehaviour
String.indexOf(“str”)

Returns the numerical position of the first character of the substring “str” in the String

String.charAt(x)

Returns the character at position x in the string – the opposite of indexOf

String.toLowerCase()

Returns a copy of the string with all capital letters replaced by their lowercase counterparts

String.toUpperCase()

Returns a copy of the string with all lowercase letters replaced by their capital counterparts

String.match(/exp/)

Returns true or false based on a regular expression search of the string

o   The final method here deserves some comment. What is a regular expression?

o   A regular expression is a standard way of writing down a “pattern” of characters that is easily recognisable. For example, consider a typical email address:

                   jonathan@relativesanity.com

o   An email address follows a “pattern” which makes it instantly recognisable as an email address to a human. Wouldn’t it be handy if we could define that pattern in JavaScript for a browser to use? Regular expressions allow us to do just that.

o   Let’s look at our email address again. We can break it down to a “prototype” email address as follows:

                           [some letters]@[some more letters].[a few more letters]

o   Of course, it’s slightly more complex than that – there are some characters which aren’t allowed to be in certain parts of the email address (no spaces, for example), but this lets you see the idea of breaking this string up into required “chunks”.

o   Now, to convert this to a regular expression. Just as we use quote marks to denote (or “delimit”) string values in JavaScript, to signify a regular expression, we use forward slashes: /. Our email address regular expression might look like this:

            /^.+@.+..+$/

o   This warrants some discussion. Let’s look at this a character at a time:

o   / denotes the start of the regular expression

o   ^ denotes that we want this regular expression to be found at the very beginning of the string we are searching.

o   .+ the dot symbol is used to stand in for any character. The plus signifies we want to find at least one of those. So this is equivalent to our plain-English phrase [some letters].

o   @ this is simply a character – it has no special meaning other than to say we want to find an @ character after at least one character from the beginning of the string.

o   .+ the same as before – at least one more character after the @.

o   . This is interesting. We know that the dot symbol has a special meaning in a regular expression – it means “match any character”. However, here we want to find an actual dot. Unlike @, which has no special meaning, we have to tell JavaScript to ignore the dots special meaning. We do this by preceding it with a backslash, which tells JavaScript to treat the character immediately following it as though it has no special meaning. This is a convention you will come across many times while programming. The net result here is that we want to match a dot after a series of characters.

o   .+ and again, at least one more character after the dot.

o   $ this is the mirror of the ^ at the beginning – this matches the end of the tested string.

o   / tells JavaScript we are at the end of the regular expression..

o   Phew! Lots to consider here. Regular expressions are an arcane art at the best of times, so don’t worry too much if the above code is indecipherable. The important thing to realise at the moment is that we can perform some quite sophisticated pattern recognition in JavaScript without having to resort to checking each individual character of a string multiple times.

The following code checks a variable to see if it looks like an email address:

     var_1 = prompt(“Your email?”, “”);

     if ( var_1.match(/^.+@.+..+$/) )

{

     alert(“valid email address”);

} else {

     alert(“are you sure?”); }

o   There are a few problems with this code at the moment – for example, it will pass the string “-@-.-“ quite happily, which is clearly wrong. We will look at ways around this later on in the course.

Project 

    o   Open your previous project file, and save it under the name chapter_18.html. o Clear all JavaScript code from your script tags.

    o   Use a prompt box to capture some user input to a variable called check_string.

    o   Use a document.write statement to output the results of each of the various string methods when applied to the user input.

         o   Check the user input to see if it’s an email address, and alter your output accordingly to either “That’s an email address” or “That doesn’t look like an email address to me!”

    o   In the latter case, output the failed string as well so that the user can see their input and modify it next time, if appropriate.

Read More

Python Casting

27Aug  Admin

Casting is when you convert a variable value from one type to another. This is, in Python, done with functions such as int() or float() or str()

Python is an object-orientated language, and as such it uses classes to define data types, including its primitive types.

Casting in python is therefore done using constructor functions:

  • int()

This Python cast function is used to construct any integral number with the help of an integral literal, a string literal (obtained by rounding down the previous whole number), or a float literal (a whole number is represented by providing a string).

Example

x = int(2)
y = int(4.8)
z = int(“8”)
print(x)
print(y)
print(z)

Output

2

4

8

  • float()

This construction function helps in the construction of any float number with the help of a float literal, an integral literal, or a string literal (if a float or an integer is represented by a string).

Example

x = float(4)
y = float(7.8)
z = float(“5”)
w = float(“2.4”)
print(x)
print(y)
print(z)
print(w)

Output

4.0
7.8
5.0
2.4

  • str()

This construction function helps in the construction of any string with the help of a lot of different data types.

Example

x = str(“s2”)
y = str(9)
z = str(5.0)
print(x)
print(y)
print(z)


Output

s2
9
5.0

Read More

Javascript Array Types

There are four types of array in javascript:

  • Homogeneous arrays
  • Heterogeneous arrays
  • Multidimensional arrays
  • Jagged arrays

Homogeneous Arrays

As the name may suggest a homogeneous array is an array that stores a single data type(string, int or Boolean values).

var array = ["Yamini", "Aman", "Yuvraj"];
var array = [21, 25, 27];
var array = [true, false, true];

Heterogeneous Arrays

A heterogeneous array is the opposite to a homogeneous array. Meaning it can store mixed data types.

var array = ["Yamini", 21, true];

Multidimensional Arrays

Also known as an array of arrays, multidimensional arrays allow you to store arrays within arrays, a kind of “array-ception”.

var array = [["Yamini", "21"], ["Aman", "25"], ["Yuvraj", "27"]];

Jagged Arrays

Jagged arrays are similar to multidimensional array with the exception being that a jagged array does not require a uniform set of data.

var array = [
    ["Yamini", "21", "Developer"],
    ["Aman", "25"],
    ["Yuvraj"]
];
Read More

Python Numbers

 27 Aug  Admin

Three numeric types in python:

  • int- Integers are whole numbers. They can be positive or negative. They must be without decimal values.
  • float- A floating point number contain decimal points. It can be positive or negative
  • complex- A complex number contains two part – real and imaginary. The imaginary part is written with the “j” suffix.

Example-

a = 4
b = 8.6
c = 2j 
print(type(a))
print(type(b))
print(type(c))
Output-

<class ‘int’>
<class ‘float’>
<class ‘complex’>

Read More

Arrays

o      In many cases, variables will completely satisfy our data storage needs in JavaScript. However, in a large number of cases, we may wish to “group” variables into a collection of related items.

o      Take, for example, days of the week. In each day we perform a number of tasks, so we could want to record each task as a separate item under a group called, say, Monday’s Tasks.

o       In JavaScript, to achieve this we would store each task in a separate variable, and then group those variables together into an array.

o       An array is a special type of JavaScript object that can store multiple data values – unlike a variable, which can only store one data value at a time.

o       It could be helpful to think of an array as a row of mail boxes in an office, just as you might think of a variable as a single, solitary mail box.

o       The boxes in an array are numbered upwards, starting at box number 0 – note that counting begins at 0 here, just as we discussed in the previous chapter. The number assigned to each box is known as its index.

In order to use an array in JavaScript, you must first create it. There are a number of ways to create arrays in JavaScript. The simplest follows:

           arrDays = new Array();

This statement creates a new, empty array called arrDays. We can call arrays just like we can variables, but with a few minor adjustments.

o       If you already know how many elements a given array will have, you can declare this explicitly: 

 arrDays = new Array(7);

This modification creates an array with 7 empty boxes. However, arrays will expand and contract to the required size in JavaScript, so the cases where you will need to state the size of the array are rare.

o        More useful, however, is the ability to “fill” the boxes of an array when you create it. For example: 

 arrDays = new Array(“Monday”,”Tuesday”);

We now have an array with two elements. The first (element 0) has a value of “Monday”, while the second (element 1) has a value of “Tuesday”. We need not restrict ourselves to string values in arrays – Boolean, numerical and string values are allowed, as in arrays. It is even possible to assign other arrays to array elements – more on this later.

o       The most often-used way of creating an array is to use “square bracket” notation. Square brackets play a large role in the use of arrays, so this is often the easiest method to remember: 

 arrDays = [“Monday”,”Tuesday”];

This is identical to the previous example.

To access an array’s elements, we first call the array’s name, and then specify the number of the element in square brackets, like so: 

 alert(arrDays[0]);

Note the lack of quotes around the 0 here. This line of code is equivalent to:

 alert(“Monday”);

assuming the array is defined as in the previous examples.

o       Not only can we access the value of an array element using this notation, but we can also assign the value as we

arrDays[2] = “Tuesday”; arrDays[3] = “Wednesday”;

o   If you wish to add an element to an array without knowing the index of the last element, you can use the following code:

arrDays[] = “some other day”;

o       As we will see, arrays are actually just special JavaScript objects, and have properties and methods associated with them. The most important property that every array has is its length property:

how_many_days = arrDays.length;

o       As well as properties, arrays have very useful methods. If you wished to sort your array alphanumerically, you could use the array’s sort method thus:

         arrDays.sort();

Note that the sort method works on the actual array itself, overwriting the current values. So, if you had an array with each day of the week as an element, calling its sort method would mean that arrDays[0] was then equal to “Friday”, not “Monday”.

Project

o   Open your previous project file, and save it under the name chapter_15.html.

Clear all JavaScript code from your script tags.

o   Write a few JavaScript statements that will present the months of the year on the page in alphabetical order. You should use the following technique to achieve this:

o   Store the names of the months of the year in an array.

Use an array method to sort the array elements alphanumericall

o   Use a for loop to iterate through each array element in turn, and print the value of the element to the screen (hint, consider the use of array[i], where i is the for loop’s counter).

o   The above method (the use of a for loop to iterate through a series of array elements) is one of the first common programming techniques we have discussed in this course. Its usefulness cannot be overstated, as it allows us to perform repetitive tasks on a series of related elements without necessarily knowing what those elements might be when we wrote the code. It can be applied to form elements, cookies, page elements, pages, windows, and just about any other collection of object that you might wish to manipulate with JavaScript.

o   To reinforce this generalism, if you have not used the array.length value in your loop, consider its use now. To prove that you have created a more generic loop, try the code with an array of days instead of an array of months, and see if you have to change any of the looping code.

Read More

Looping

o   The letters ij and k are traditionally used by programmers to name variables that are used as counters. For example, at different stages of the program, i may contain the numbers 1, 2, 3 etc.

o   In order to achieve a “counting” effect, you will need to increment or decrement the value of your counting variable by a set value. Here are some examples:

i = i + 1; 

i = i – 1; 

i = i + 35; 

incr = 10 i = i + incr;

o To keep things concise, we can use the following shortcuts:

i++;  // equivalent to i = i + 1;

i–; // equivalent to i = i + 1;

o   Counting in JavaScript, like many other programming languages, often begins at zero

In many cases, this makes a lot of sense, as we will see. However, it can often cause confusion. Consider starting at 0 and counting up to 10. In that case, we may have actually counted 11 items:

 0                               (1)

1                               (2)

2                               (3)

3                               (4)

4                               (5)

5                               (6)

6                               (7)

7                               (8)

8                               (9)

10               (11!)

o   If you wanted to give an instruction to someone to perform a repetitive action, you might say that you wanted them to continue the action for a certain number of times. If someone were performing an action 300 times, for example, they might do something like the following to ensure that their count was accurate:

o   Write the number 1 on a bit of paper.

o   After each action, erase the number on the bit of paper and increment it by 1.

o   Before each action, check the number on the bit of paper. If it is less than or equal to 300, perform the action.

o   Alternatively, they might decide to start counting at 0. In this case, the procedure would be identical, but the check before each action would be to make sure that the number was strictly less than 300.

o   In JavaScript, we say almost the same thing. The following code will display the numbers 1 to 100 on the page:

 for( i = 1; i <= 100; i++ )

  {

  document.write(“<p>” + i “ </p>”);

  }

   The for statement tells the browser that we are about to perform a loop. The layout here is very similar to a conditional statement, but in this case we have much more information in the brackets. Where our conditional had one JavaScript statement to describe its action, a for loop has three:

o  An initialiser – this sets up the initial counting condition, in this case i = 1.

o     A conditional – this is identical to our conditional statements earlier, and must return true or false. If it returns true, the loop continues, otherwise it exits.

o     An incrementer – this defines the action to be performed at the end of each loop. In this case, i is incremented by a value of 1.

o      The key difference between a conditional and a for loop is that the condition is constantly being changed and re-evaluated. It is possible to create an infinite loop by making the conditional non-reliant on the count value – for example:

for(i=0; 5 > 4; i++ )

 will always perform the script in the braces, and will probably cause errors in the browser.

o     Note too that it is very common to start counting at zero in JavaScript. The reason for this is that it is often desirable to count how many times an operation has been performed.

Consider the following: 

for(i=1; 1 < 2; i++ )

o   In this case, the loop will run once, but the value of i will be 2, as after the first run, i will be incremented to 2, and will then fail the test and so the loop will exit. If we use the following: 

 for(i=0; 1 < 1; i++ )

 Then the loop will run once, and the value of i afterwards will be 1, as we might hope.

Project 

o   Open your previous project file, and save it under the name chapter_14.html. o Clear all JavaScript code from your script tags.

Write a series of statements to produce a multiplication table as follows:

o   The following exercise is more of an HTML example, but demonstrates an important facet of using JavaScript (or, indeed, any programming language) to produce well-formatted text.

o   Modify your previous code to make your page’s content appear in the centre of the page. Put your multiplication table in an HTML table to make sure that the equals signs, multiplication signs and so forth line up in neat columns:

o   The following exercise is more of an HTML example, but demonstrates an important facet of using JavaScript (or, indeed, any programming language) to produce well-formatted text.

o   Modify your previous code to make your page’s content appear in the centre of the page. Put your multiplication table in an HTML table to make sure that the equals signs, multiplication signs and so forth line up in neat columns:

o   The following exercise is more of an HTML example, but demonstrates an important facet of using JavaScript (or, indeed, any programming language) to produce well-formatted text.

o   Modify your previous code to make your page’s content appear in the centre of the page. Put your multiplication table in an HTML table to make sure that the equals signs, multiplication signs and so forth line up in neat columns:

Read More

Conditionals

o       Up until now, our JavaScript projects have been unable to alter their behaviour spontaneously. When a page loads with our JavaScript embedded within, it is unable to do anything other than what we expect, time and again.

o       The only difference we have seen is in the use of a prompt box to alter what is shown on a page. However, the page essentially does the same thing with the text provided, regardless of what text is typed in.

o       What would be really handy would be to give JavaScript a mechanism to make decisions. For example, if we provided a prompt box asking the visitor for their name, it might be nice to have a list of “known names” that could be greeted differently from any other visitors to the site.

o      Conditional statements give us that ability, and are key to working with JavaScript.

o     A conditional statement consists of three parts:

o     A test (often with a comparison operator, or comparator) to see if a given condition is true or false.

o     A block of code that is performed if and only if the condition is true.

o     An optional block of code that is performed if and only if the condition is false.

These three parts are represented in JavaScript as follows:

  if ( conditional_test )

  {

  JavaScript statement;

  JavaScript statement;

  JavaScript statement;

  …   } else

  {

  JavaScript statement;

  JavaScript statement;

  JavaScript statement;

  …

  }

o     Everything from the first closing curly bracket (or brace) is optional, so the following is also a valid conditional prototype: 

 if ( conditional_test )

  {

  JavaScript statement;

  JavaScript statement;

  JavaScript statement;

  …   }

o     In this case, if the conditional_test does not return true, nothing happens.

o   An example of  complete conditional statement is as follows:

 if ( var_1 > var_2 )

  {

  alert(“Variable 1 is greater”);

  } else   {

  alert(“Variable 2 is greater”);

 }

  Note that the above condition is not necessarily always correct. Consider the case where var_1 is equal to var_2.

In that case, the above code will produce the message that “Variable 2 is greater”, since var_1 > var_2 returns false. In this case, we want to add an additional condition to the else branch of code: 

if ( var_1 > var_2 )

  {

  alert(“Variable 1 is greater”);

  } else

if ( var_1 < var_2 )

  {

  alert(“Variable 2 is greater”);

 }

o In this case, equality will produce no output, as neither of the conditions will return true. For completeness, we could add a final else branch to the statement:

 if ( var_1 > var_2 )

  {

  alert(“Variable 1 is greater”);

  }  else

if ( var_1 < var_2 )

  {

  alert(“Variable 2 is greater”);

 }

else   {

  alert(“The variables are equal”);

 }

o      Note that in this case, we don’t have to check for equality in the final branch, as if var_1 is neither greater than nor less than   var_2, then – numerically at least – the two must be equal.

o     We can continue adding as many else if statements as required to this stack.

If you only have one statement following your conditional test, the braces may be omitted:

 if ( var_1 > var_2 )

  alert(“Variable 2 is greater”);

However, if you later want to add further statements to this conditional branch, you will have to add braces around the block, and this can lead to confusion. It is recommended that you use braces to enclose all blocks of conditional code. o Consider the following block of code:

 if ( var_1 > 4 )   {

  var_2 = var_1;

 }

else   {   var_2 = 4;   }

o     This code is rather long, but achieves comparatively little – var_2 is equal to var_1 or 4, whichever is greater. o A more compact way of writing this could be:

Read More

Alert, Prompt and Confirm

o    So far, we have seen brief examples of alertprompt and confirm dialogue boxes to request a response from the user, and to pause all code in the background until the request is satisfied.

o    All of these boxes are the result of methods of the window object. This object is the highest level object that JavaScript can deal with in a browser. As such, all other objects on a page (with a few exceptions) are actually properties of the window object.

o     Because of this ubiquity, its presence is assumed even if it is omitted. Thus, where we technically should write:

 window.document.write(“…”);

 it is equally valid to write:

 document.write(“…”);

 as we have been doing.

o     Similarly, instead of writing:

 window.alert(“…”);

we can happily write:

 alert(“…”);

o    The prototypes of the three methods are:

        window.alert( message ); window.confirm( message ); window.prompt( message, default_response );

o    Alert will always return a value of “true” when it is cleared by clicking “ok”.

o    Confirm will return either “true” or “false” depending on the response chosen to clear the box.

o    Prompt will return either the value typed in, “null” if nothing is typed in, and “false” if the box is cancelled.

Project

o   Open your previous project file, and save it under the name chapter_10.html.

o   Clear the previous redirection code, and ensure that the script tags have been returned to the head section of the document.

o   Add a new statement to the script on the page that will display the following message before the rest of the page is shown:

 Welcome to my website! Click OK to continue.

o Check your page in your browser.

 o   We will use alertconfirm, and prompt throughout this course. Take a moment to try each of them in turn on this page, each time stopping to review your changes.

 o   Use the write method of the document object to check the return values of each method. For example:

          document.write(alert(“hello world”));

Read More

About Comments

o   Repeat after me : Comments are important. Comments are importantComments are important.

o   Adding comments to your code is always good practice. As the complexity of your scripts grows, comments help you (and others) understand their structure when you come to view the code at a later date.

o   A lot of code created quickly is said to be “write only” code, as it suffers from an inherent lack of structure or commenting. Debugging such code, or reusing it months later, becomes maddeningly impossible as you try to remember what a certain line was supposed to do, or why using certain values seems to stop your code from working.

o   Comments are completely ignored by JavaScript and have no effect on the speed at which your scripts run, provided they are properly formed.

o   Comments can slow the loading of your page, however – many coders keep a “development” copy of their code fully commented for editing, and remove all comments from their code when they finally publish it.

o   There are two types of comment in JavaScript – single line comments, and multi-line comments.

o   Single line comments begin with two forward-slash characters (//), and end with a new line:

// this is a comment

 alert(“hello”); // so is this

o   Single line comments in JavaScript can also use the HTML comment format that you may be familiar with:

 <!– this is a comment

 alert(“hello”);

o   Note two things: firstly, this use of the HTML comment format does not require a closing –> tag. Secondly, this is only a one line comment, unlike its use in HTML, which comments all lines until the closing comment tag.

o   You can add multiple-line comments by enclosing the comment block between /* and */. For example:

/* all of this text is going to be ignored by JavaScript. This allows us to write larger comments without worrying about having to individually “comment out” each line */ 

alert(“Hello World”);

/* a one line, “mult-line” comment */

o   As well as adding narrative to your script, you can use comments to remove code from your pages without having to delete the code. For example:

// this was the old message

// alert(“Hello World”); // and this is the new message alert(“Hello everyone!”);

o   This can be very useful if you are trying to track down an error in your code – you can “comment out” each suspect line in turn until you manage to get your code working again.

Project

o   Open your previous project file, and save it under the name chapter_7.html

o   Add the single line comment

This is my first comment

to the beginning of your script.

Add a multi-line comment to your script, replacing your previous single line comment. The multi-line comment should describe what your script does at present. 

Read More