Python Tuples

28 Aug  Admin

A tuple is an immutable sequence of Python objects. Tuples are sequences, just like lists. The differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parentheses (or round bracket), whereas lists use square brackets.

Example

atuple = (“rabbit”, “lion”, “cow”)
print(atuple)

 Output

(‘rabbit’, ‘lion’, ‘cow’)

Read More

Python Operators

12 Apr Admin

Operators are special symbols in Python that carry out arithmetic or logical computation. The value that the operator operates on is called the operand.

 Example:

8+6 = 14

Here, + is the operator that performs addition. 8 and 6 are the operands and 5 is the output of the operation.

There are different type of operators use in python:

  • Arithmetic operators
  • Assignment operators
  • Comparison operators
  • Logical operators
  • Identity operators
  • Membership operators
  • Bitwise operators

Python Arithmetic Operators

Arithmetic operators are used with numeric values to perform common mathematical operations:

OperatorNameExample 
+Additionx + y 
Subtractionx – y 
*Multiplicationx * y 
/Divisionx / y 
%Modulusx % y 
**Exponentiation- left operand raised to the power of rightx ** y(x to the power y) 
//Floor division- division that results into whole number adjusted to the left in the number linex // y 

Python Assignment Operators

Assignment operators are used to assign values to variables:

OperatorExampleSame As 
=x = 5x = 5 
+=x += 3x = x + 3 
-=x -= 3x = x – 3 
*=x *= 3x = x * 3 
/=x /= 3x = x / 3 
%=x %= 3x = x % 3 
//=x //= 3x = x // 3 
**=x **= 3x = x ** 3 
&=x &= 3x = x & 3 
|=x |= 3x = x | 3 
^=x ^= 3x = x ^ 3 
>>=x >>= 3x = x >> 3 
<<=x <<= 3x = x << 3

Python Comparison Operators

Comparison operators are used to compare values. It returns either True or False according to the condition.

OperatorNameExample 
>Greater thanx > y 
<Less thanx < y 
==Equal tox == y 
!=Not equal tox != y 
>=Greater than or equal tox >= y 
<=Less than or equal tox <= y

Python Logical Operators

Logical operators are used to combine conditional statements:

OperatorMeaningExample 
and True if both the operands are truex < 5 and  x < 10 
orTrue if either of the operands is truex < 5 or x < 4 
notTrue if operand is false (complements the operand)not(x < 5 and x < 10)

Python Identity Operators

Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location:

OperatorDescriptionExample 
is Returns True if both variables are the same objectx  is y 
is notReturns True if both variables are not the same objectx is not y 

Python  Membership Operators

Membership operators are used to test if a sequence is presented in an object:

OperatorDescriptionExample 
in Returns True if a sequence with the specified value is present in the objectx in y 
not inReturns True if a sequence with the specified value is not present in the objectx not in y

Python  Bitwise Operators

Bitwise operators are used to compare (binary) numbers:

OperatorNameDescription
ANDSets each bit to 1 if both bits are 1
|ORSets each bit to 1 if one of two bits is 1
 ^XORSets each bit to 1 if only one of two bits is 1
NOTInverts all the bits
<<Zero fill left shiftShift left by pushing zeros in from the right and let the leftmost bits fall off
>>Signed right shiftShift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off

Read More

Python Data Types

28   Admin

Data types are the classification or categorization of data items.Data types represent a kind of value which determines what operations can be performed on that data. Numeric, non-numeric and Boolean (true/false) data are the most used data types.

Python has the following standard or built-in data types:

Text Type:str
Numeric Types:intfloatcomplex
Sequence Types:listtuplerange
Mapping Type:dict
Set Types:setfrozenset
Boolean Type:bool
Binary Types:bytesbytearraymemoryview

In Python, the data type is set when you assign a value to a variable:

ExampleData Type 
x = “Welcome”str 
x = 14int 
x = 21.5float 
x = 4jcomplex 
x = [“monkey”, “dog”, “cow”]list 
x = (“orange”, “mango”, “apple”)tuple 
x = range(8)range 
x = {“name” : “Mohan”, “age” : 27}dict 
x = {“mango”, “apple”, “banana”}set 
x = frozenset({“sparrow”, “parrot”, “hen”}) frozenset 
x = Truebool 
x = b”Welcome”bytes 
x = bytearray(6)bytearray 
x = memoryview(bytes(6))memoryview 
Read More

Python Variables

28Aug   Admin

A variable can have a short name (like x and y). In Python:

  • A variable name must start with a letter or the underscore character
  • A variable name cannot start with a number
  • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
  • Variable names are case-sensitive (age, Age and AGE are three different variables)

          Example-     mvar = “Mohan”

Read More

Introduction

27Aug Admin

Python is a programming language.

Python can be used on a server to create web applications.

It is used for:

  • web development (server-side),
  • software development,
  • mathematics,
  • system scripting.
Read More

Positioning Browser Windows

o      The screen object provides you with access to properties of the user’s computer display screen within your JavaScript applications.

o   Some of the available properties are:

Property

Description

availHeight

The pixel height of the user’s screen minus the toolbar and any other permanent objects (eg the Windows Taskbar)

availWidth

As availHeight, but dealing with horizontal space

colorDepth

The maximum number of colours the user’s screen can display (in bit format, eg 24 bit, 16 bit etc)

heightThe true pixel height of the user’s display

width

The true pixel width of the user’s display

o      The left and top parameters of the open() method enable you to specify the position of a window on screen by specifying the number of pixels from the left and top of the screen respectively.

o     If you need to use a variable to specify the value of a parameter in the open() method, you would do so as follows:

window.open(“index.html”, “window_name”,“width=200,height=200,left=”+var_left+“top=”+var_top);

                       Where var_left and var_top are the appropriate variables.

o       Note the use of the + operator to ensure that the third parameter in the open() method remains as one string when variables are added.

o       In order to centre the window on the user’s screen, a little simple geometry is required. The centre of the screen is obviously the point found when we take the width of the screen divided by two, and take the height of the screen divided by two. However, if we set the window’s top and left values to these coordinates, the top left corner of the window will be centred, not the window itself.

o      In order to centre the window, we need to subtract half of the window’s height from our top value, and half of the window’s width from our left value. A simple script to accomplish this is as follows:

         win_width = 200; win_height = 200;

    win_left = (screen.availWidth/2)– (win_width/2);

    win_top = (screen.availHeight/2)– (win_height/2);

o       By using this script, the values of win_left and win_top will be set correctly for any window using win_width and win_height appropriately to be centred on the screen.

Project

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

o     Modify your existing code to ensure that the logo appears centred on the user’s screen. If possible, do not modify your original function by doing anything more than two new functions – get_win_left( width ) and get_win_top( height ).

Read More

Working with Browser Windows

o      Using standard HTML links, we can open new browser windows:

           <a href=”#” target=”_new”>link</a>

o       The amount of control this method affords us over the resultant image, however, is nil. We cannot control the size, shape,   location on the screen or anything else about that window with this method.

o      JavaScript allows us much finer control, as we may expect:

         window.open( page_url, name, parameters );

o       As we can see from the above prototype, there are only three arguments that this method can take. However, the parameters argument is actually more complex than we might assume:

        ”param1,param2,param3,param4…”

                    since we can use it to add many parameters to the method. Note there are no spaces in the parameter list.

o       name is used to give the window an HTML name – so we can use that name to open links into the new window using the “target” method above.

o       The return value from the open method is an object variable referring to the newly opened window. In other words, if we open a new window like so:

        win = window.open(“page.html”, “”, “”);

we can use the object variable win to alter the new window through JavaScript.

o       A practical example – let’s say we want to open a new window 300 pixels high by 400 pixels wide, and display the BBC news page in it. The following code would suffice:

  window.open(“http://news.bbc.co.uk/”,“bbc”, “width=300,height=300”);

o      Some available parameters are given in the table below:

ParameterValueFunction
locationYes/NoSpecifies whether or not the location (address) bar is displayed
menubarYes/NoSpecifies whether the menu bar is displayed
status Yes/NoSpecifies whether the status bar is displayed
widthPixels Specifies the width of the new window
heightPixelsSpecifies the height of the new window
resizableYes/NoAllow or disallow window resizing
scrollbarsYes/NoAllow or disallow window scrolling

o      If no parameters are set, then the value of each parameter is set to “yes” where appropriate. For example:

       window.open(“http://www.bbc.co.uk/”,“bbc”, “”);

is equivalent to:

      <a href=”http://www.bbc.co.uk/” target=”bbc”>

o      However, if any parameter is set, all others default to “no”. So if you wanted to have a scrollbar but nothing else, the following would suffice:

   window.open(“http://www.bbc.co.uk/”,“bbc”, “scrollbars=yes”);

Project

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

                  o     Remove all functions and HTML from your previous file, leaving only the logo image and the link.

                  o      Create a function in the head area script element called view_new_logo. This function should:

§  Open a new window 200 pixels square.

§  Load the image rocollogo.jpg from the images folder.

§  Be called RocolLogo

§  Be stored in an object variable called objNewLogo.

§  Have no scrollbars, be of a fixed size, and have no other features where possible.

o Remove all event handlers from the link, and add a new one to run the function above when the link is clicked.

o   Once you have verified that a window pops up as required when the link is clicked, test each parameter from the table above in the function.

Read More

Object Instantiation and Better Rollovers

o      So far we have seen a very simple example of an image rollover. It is functional and works as desired, but it is lacking in a few finer details.

o      Specifically, when we use JavaScript to change the src attribute of an <img> tag, the browser has to load this image from scratch. On our local machine, this will not cause an appreciable delay, but when dealing with a remote server (as we will be on the Internet), this delay can lead to a noticeable “lag”, which can destroy the feeling of a dynamic interface.

o      Ideally, we would like to instruct the browser to load any alternate images when it loads the page. This will allow us to ensure that the new images are sitting on the user’s computer, ready to be swapped in and out instantly.

o      To do this, we need to look at object variables and object instantiation (or creation). In particular, we need to look at the Image object.

o       Each <img> tag on the page has a corresponding Image object in JavaScript. We have looked at ways of manipulating this directly, and have an idea of some of the properties an Image object can have.

o       However, we can create Image objects directly in JavaScript, without the need for a corresponding <img> tag on the page. When we create such an object, and set its src property, the browser will load the appropriate file into memory, but will not display the image on the page. 

o       In other words, we can create “virtual” images that exist within JavaScript, and use these Image objects to store the alternate images for our “real” images.

o     To create an Image object (in fact, to create any object), we need to use the following code:

             virtual_image = new Image();

o       We have seen this sort of syntax before – the use of the new keyword when we created our Arrays. new tells JavaScript that we are creating a new object. The virtual_image part of the assignment is just a variable name. In this case, the variable is an Object Variable, since it contains an object.

o        To use this variable to preload our images, we take advantage of the fact that it has the same properties and methods as any other image:

          virtual_image.src = “contactsover.jpg”;

o      The browser will now preload our image, ready to be swapped in at a later time.

Project

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

o      Starting with your previous code, create a new function called preload_images in the head area script element of your page.

o       Use this function to create seven new image objects, and use each objects corresponding object variable to preload your “over” image variations.

o      Check your work in your browser to ensure that the image swapping still works as expected.

o       Add your preload_images function to the body tag of your page to ensure that it runs when the page has finished loading. Use the following syntax:

       <body onload=”preload_images();”>

o       Once you have verified that the image swapping still works as expected, expand your preload_images function to define an array of images to preload, and then use a for loop to move through the array and assign each image to the src property of an object variable. Hint: an object variable can be anything that can store information – for example an array element.

                      Check your work in your browser.

Read More

Simple Image Rollovers

o      A simple image rollover is an effect which happens when the mouse appears over an image (usually a linked button) on the page. The original image is replaced by another of equal size, usually giving the effect that the button is highlighted in some way.

o      With what we have learned so far, we already have the ability to create a simple image rollover effect. All that remains is to clarify the particulars of the process:

o      The page is loaded and the original image appears on the page as specified by the <img> tag’s src attribute.

o     The mouse moves offer the image and the alternative image is loaded into place.

o     The mouse leaves the image and the original image is loaded back.

o      As you may have realised, we are going to use JavaScript to alter the src attribute of the image tag. The best way to think of this is to picture the <img> tag as simply a space on the page into which an image file can be loaded. The src attribute tells the browser which image to load into the space, and so if we change that value, the image will be changed.

o      In other words, the id attribute of the <img> tag is naming the “space”, not the image.

o       Now, in order to alter the src attribute with JavaScript, we need to tell JavaScript which image “space” we want to alter. We use the id attribute along with the getElementById() method from the last chapter to do this:

 button_img =document.getElementById(“button”);

           button_img.src = “new_image.jpg”;

      o   We can directly insert this code into the image’s event handler:

 <img src=”old.jpg” id=”button” onmouseover=”document.getElementById(‘button’).src’new.jpg’;”>

  Note that this code is suddenly very convoluted. There are two immediate potential solutions. The first is to define a function:

            function swap_image( id, new_image )

          {

           img = document.getElementById(id); 

           img.src = new_image;

          }

            

           <img src=”old.jpg” id=”button” onmouseover=”swap_image(‘button’, ‘new.jpg’);”>

o       This is a much cleaner solution, and more importantly we can use this for any images on the page, simply by changing the arguments of our function call. We can also use the function to achieve the “swap back” functionality: 

            … 

      <img src=”old.jpg” id=”button” onmouseover= ”swap_image(‘button’, ‘new.jpg’);”onmouseout=”swap_image(‘button’, ‘old.jpg’);”>

o       We can go even further in “cleaning up” our code, though. Because the event handler is being used to alter the object which is experiencing the event (ie, the mouse is moving over the image tag that we are trying to change), we can use the “automagic” JavaScript object this to perform the operation: 

     function swap_image( img, new_image )

  {

    img.src = new_image;

  }

   … 

   <img src=”old.jpg” id=”button” onmouseover=”swap_image(this, ‘new.jpg’);”>

o       Note a couple of things. Firstly, this has no quotes around it – we are using it like a variable name. Secondly, our function now uses the first argument directly, instead of using it to get the relevant object from the page. We can do that because this is actually an object – it’s an object that takes on the properties and methods of whatever object it is called from, in this case, it becomes equivalent to

      document.getElementById(‘button’), although is obviously much shorter!

o      Using this has some limitations. For example, if we wanted to change the src attribute of any other image on the page when the mouse moved over “button”, we would be unable to use this, and hence would have to define another function that could take an id as its argument and get the relevant object that way.

Project

o      Copy the folder called buttons from the network drive to your project folder. o Open your previous project file, and save it under the name chapter_23.html. o Clear all JavaScript code from your script tags.

o     Ensure that you have a script element in the head area of your document, and none in the body area.

o      Within the body area of your page, create a paragraph containing six image elements. Set the src attributes of the images to load the following files in your copied buttons folder, and give each a sensible id:

o     contacts.jpg o   home.jpg o   people.jpg o   products.jpg o  quotes.jpg o  whatsnew.jpg

o      Create a JavaScript function in the head area script element that takes two arguments – an id and a file name. It should alter the src property of the appropriate image object to the file name given.

o     Use this function to swap the src attribute of the contacts button to contactsover.jpg when the mouse moves over the image.

o   Once you have this working, update the remaining five images with event handlers to swap their src attributes to their appropriate “over” image.

o      Add event handlers to all six images to ensure that they return to their original state when the mouse is moved away from them. Check your work in your browser

o     Add a new paragraph above the previous one, and add an <img> tag to it to containing the file rocollogo.jpg from the images folder.

o      Add a text link to a new paragraph between the two paragraphs. The link should be a “dummy” link (ie use “#” as its href attribute value), but when the mouse moves over it, the image above it should change to show rocollogo.gif.

o      Moving the mouse away from the text link should return the logo to its previous state.

o     Check your work in your browser.

Read More