User:Eleanorg/Prototyping Yr 1 Timester 1/Cookbook: Percentages: Difference between revisions

From XPUB & Lens-Based wiki
(Created page with "Here are some examples of cool things you can do by grabbing numbers from the internet, and converting them into percentages. Once you've converted your number into a percentage,...")
 
No edit summary
Line 29: Line 29:


===Using % value in CSS Styling===
===Using % value in CSS Styling===
Here, we use our % value to determine the size of a <div> in an html document:
<source lang=python>
print "Content-Type: text/html"
print
print """
  <html>
    <body>
      <div style="width:""" + percentstr + """%; height:""" + percentstr + """%; background-color: #ddd;">
        <p>""" + percentstr + """</p>
      </div>
    </body>
  </html>""
</source>
Here, we use the % value to change the opacity of an image:
(coming soon)

Revision as of 17:38, 30 November 2011

Here are some examples of cool things you can do by grabbing numbers from the internet, and converting them into percentages. Once you've converted your number into a percentage, you can make it do all kinds of fun tricks - for example, using it to determine CSS styles. (Conversion to % also has the added benefit of making your randomly scraped data seem "scientific".)

Grabbing a number

Here is a basic way to extract a number live from a website - in this case, the current longitudinal position of a ship.

(coming soon)

Converting to a % value

In this example, I convert the ship's current position into a % distance from its destination. First, establish the ship's starting point (001.2528), and its destination (004.1285). These will act as 0% and 100% respectively. The percentage is worked out based on the ship's current position within this range.

import re
 
### convert longitude into 5 digit integer
longitude = str(001.2528) 			# must be a string for regex to work
longint = int(re.sub("\.", "", longitude)) 	# removes decimal point and converts back to an integer
 
### convert integer into percentage of given range
# converts longitude into a percentage, where 001.2528 = 0% and 004.1285 = 100%
# range between numbers is 28703, so 1% of range is 28703/100 ---> 287.03. Longitude equivalent to 1% will be 12528 + (28703/100)
# thus to convert longitude to percentage, work out its distance from 12528 and divide this distance by 287.03.
percent = int((longint - 12528) / 287.03)       # convert to int to avoid nasty decimals
percentstr = str(percent)                       # now convert to a string, for use in html etc.

Using % value in CSS Styling

Here, we use our % value to determine the size of a

in an html document:
print "Content-Type: text/html"
print
print """
  <html>
    <body>
       <div style="width:""" + percentstr + """%; height:""" + percentstr + """%; background-color: #ddd;">
         <p>""" + percentstr + """</p>
       </div>
    </body>
  </html>""

Here, we use the % value to change the opacity of an image:

(coming soon)