Saturday, March 18, 2017

Start Python programming: How Python 3 works for websites

We test codes on this website: https://repl.it/languages/python3

Here we will learn how we can control HTML document with the server-side script "Python". You might think it would be difficult but actually it is not so difficult.

Please write:
print("Hello World")
By the way, print("") is used to display some words. See the result below.

click to expand


Then click "Run". You will see "Hello World" will appear on the console. ("Console" means the black window next to the editor window)
click to expand


Yes, "Hello World" is displayed... but you would wonder like this "yes, hello world appeared on the console... but so what?" This seems like a small step but actually this is a very big leap for your web programming.

Write this way now:
print("<h1>Welcome to my website</h1>")

click to expand

Look at the console. You can see it is displaying "<h1>Welcome to my website</h1>". If this is executed on a server, this "<h1>Welcome to my website</h1>" is shown to each browser that accessed to your website.

But the browser will see it as a HTML page as long as it has HTML structure. <h1></h1> is HTML tag to make big letters. So the result on each browser will be as follows:



This means you can dynamically adjust and control HTML document before it is rendered in each browser. See an example below:
code:
print("<h1>Welcome to my website</h1>") 
amount = 100.0 
if amount < 100:
  discount = amount * 0.05
elif amount < 500:
  discount = amount * 0.10
else:
  discount = amount * 0.15 
print ("<p>Your amount: ",amount,"</p>")
print ("<p>Discount: ",discount, "</p>")
print ("<p>Net payable: ",amount-discount,"</p>")



And the result of this code will be 

If this is rendered as HTML document in a browser, this would be shown as:



You can see that this HTML document will vary depending on the amount value. If the "amount" value is changed to "120" from "100", then the result is:

So HTML content shown in a browser is also changed:
You can see each value is changed

This is how server-side programming (or server-side scripting) is done.