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

Hiding Scripts from Older Browsers

    • Very old browsers don’t understand JavaScript. There are very few such browsers in use today, but two factors force us to continue to consider environments that may not be able to cope with our JavaScript code.
    • Firstly, all modern browsers allow users to control whether JavaScript code will be run. In many cases, users will not have any say over their company policy, and may not even know that their work machine has had JavaScript disabled.
    • Secondly, not all of your visitors will be using browsers that can make any use of JavaScript. Braille displays, screen readers and other non-visual browsers have little use for many JavaScript tricks. In addition, search engines like Google will ignore any JavaScript you use on your pages, potentially hiding important content and causing your pages to remain unindexed.
    • Browsers that don’t support JavaScript are supposed to ignore anything between the opening and closing script tags. However, many break this rule and will attempt to render your code as HTML, with potentially embarrassing consequences.
    • However, we can use the fact that <!– denotes a single line comment in JavaScript but a multi-line comment in HTML to ensure that our code is seen by a JavaScript-savvy browser, but ignored as commented-out HTML by anything else:

               <script>

      <!– hide  from older browsers

     … your code

     // stop hiding code –> </script>

o   This prevents older browsers from displaying the code, but what if we want to replace this with some comment. For example, let’s say we had a bit of code that displayed the time of day and greeted our user by name. Without JavaScript and using the method above, there would simply be a blank on the page where the greeting should have been.

o   We can use the <noscript> tag to cause our code to “fail gracefully” where JavaScript has been disabled or is unavailable. The contents of this element will be ignored where JavaScript is understood, and displayed anywhere else.

For example:

<noscript>

    <h1>Welcome to our site!</h1>

</noscript>

<script>

<!– hide  from older browsers

… code to customise header

// stop hiding code –>

</script>

Project 

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

o   Add two lines to your code to ensure that it will not confuse older browsers or browsers where the user has disabled JavaScript.

o   Add a noscript element to explain what your JavaScript does.

    It is generally considered “bad form” to instruct your user to “upgrade to a better browser”, as this can insult many people

   who use assistive devices – consider this form of advice to be similar to the advice that tells a blind person “to get some

    glasses”.

o   Instead where possible you should use the noscript element to provide content that adequately replaces the scripted content

    with a suitable replacement. For example, if you use your JavaScript to build a navigation panel on your page, the noscript element should contain a plain HTML list that does the same job.

Read More

Python Strings

27Aug  Admin

Strings are amongst the most popular types in Python. We can create them simply by enclosing characters in quotes. Python treats single quotes the same as double quotes. Creating strings is as simple as assigning a value to a variable. For example −

a = 'Hello World!'

You can display a string  with the print() function:

x = “Welcome”    #Assigning a string to a variable
print(x)

Output– Welcome

Read More

Automatically Redirecting the User

o   We have already briefly seen the use of browser redirection in chapter 4.

o   To formulate the idea more completely, in order to redirect the user to a different page, you set the location property of the document objects.

o   As we saw in chapter 6, we can use the assignment operator here. For example:

 document.location = “http://www.bbc.co.uk/”; document.location = “chapter_4.html”;

Project

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

o   Save another copy of the file, this time called chapter_9.html.

o   Make sure both files are saved in the same folder, and that you have chapter_9.html open in your editor.

o   Remove all script from between the script tags, except for your browser hiding lines. Make sure that the script tags are still in the head section of the page.

o   Now, add a single statement to this script that will automatically redirect the user to the page

chapter_9_redirect.html as soon as the page is loaded into a browser.

o   Finally, add a header tag to the body section of the page containing the text “You can’t see me!”.

o   Close this page, don’t check it in a browser yet, and open the page chapter_9_redirect.html in your editor.

o   Remove all JavaScript from this page (including your script tags) and ensure that only HTML remains on the page.

o   Add a header tag to the body section of the page containing the text “But you can see ME!”.

o   Save this page, and load the page chapter_9.html into your browser.

                Experiment with various positions for the script tags on chapter_9.html to see if you can make the header appear before the    redirection.

Read More