Review of the basic programming structures in Python, their port to Javascript, and running JS in a webpage.
Now we have that we have an idea of how to build the content and style of a webpage, let’s dive into how to program it.
Class preparation
1. Watch at home the following video by Jake Wright (12 mins):
JS: Learn JavaScript in 12 Minutes
2. Watch at home the following video from Java Script Programming Teasers (13 mins):
JS: Do’s and Don’ts of Javascript
Class work
Topics for today
- Basic programming structures in Python
- Boolean, integer and string data types
- functions
- Variables
- Condtionals (if/else)
- Operators and comparators
- Conditional loops (for)
- Unconditional loops (while)
- Arrays
- Matrices
- Python to Javascript
Syntax of Python and Javascript
Python | Javascript | |||
Comment | # | # my comment | /* */ | /* same as C (multi-line) */ |
// | // same as C++ (single line) | |||
functions | def foo(): | # ends in colon | function foo() | // no colon |
bodies | indentation | # 4 spaces | { } | // curly braces |
statements | one per line | ; | // separated with semi-colon | |
comparisons | if a > b: | # end in colon | if (a > b) | // enclose in parentheses |
booleans | True and False | #uppercase | true and false | // lowercase |
boolean ops | not and or | # spell them out | ! && || | // same as in C |
concatenation | + | # "a"+"b" == "ab" | + | // same as Python |
cast to str | str() | # str(5) == "5" | String() | // String(5) == "5" |
cast to int | int() | # int("5") == 5 | parseInt() | // parseInt("5") == 5 |
output | print() | # output to console | console.log() | // output to console |
document.write() | // output to html doc | |||
for loops | for i in range(x): | for (i=0;i < x;i++) | // same as C |
Reeborg: Count to wall
From an unknown orientation, we have to orient Karel to the North and then have him count the steps to the goal line. We are given the program in Python. Please port it to Javascript.
Answer:
sound(True)
def left():
turn_left()
def face_north():
while not is_facing_north():
left()
def count_to_wall():
if not front_is_clear():
return 0
else:
move()
return count_to_wall() + 1
# main program
face_north()
steps = count_to_wall()
print( "steps = " + str(steps) )
sound(true);
function left() {
turn_left();
}
function face_north() {
while ( ! is_facing_north() ) {
left();
}
}
function count_to_wall() {
if ( ! front_is_clear() ) {
return 0;
}
else {
move();
return count_to_wall() + 1;
}
}
// main file
face_north();
var steps = count_to_wall();
write( "steps = " + String(steps) );
Reeborg: The tar pits
Our Python program to move the mammoth bones from the pits to the inside of the museum got sidetracked: the museum wants the procedure to be broadcasted worldwide via the internet and since Javascript is the language that all browsers handle natively, they have asked us to port the Python code to Javascript.
No sweat… most likely we can do this in 10-15 minutes.
Answer: show it to me
functions, while
Example: write a function that adds all the integers from a to b (with a <= b )
# Python
def my_sum(a, b):
total = 0
i = a
while i <= b:
total = total + i
i = i + 1
return total
print( my_sum(10,100) )
// Javascript
function my_sum(a, b) {
var total = 0; // var initialization
var i = a; // var initialization
while (i <= b) {
total = total + i;
i = i + 1;
}
return total;
}
console.log( my_sum(10, 100) );
for, boolean ops
Example: Fizzbuzz
Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.
# Python
def fizzbuzz( x ):
for i in range( 1, x+1 ):
div3 = ""
if ( i % 3 == 0 ):
div3 = "fizz"
div5 = ""
if ( i % 5 == 0 ):
div5 = "buzz"
n = ""
if ( div3 == "" and div5 == "" ):
n = str(i)
print( div3 + div5 + n )
fizzbuzz(100)
// javascript
function fizzbuzz( x ) {
var div3, div5, n; // var declaration
for ( var i = 1; i < x; i++ ) {
div3 = "";
if ( i % 3 === 0 ) {
div3 = "fizz";
}
div5 = "";
if ( i % 5 === 0 ) {
div5 = "buzz";
}
n = "";
if ( div3 === "" && div5 === "" ) {
n = String(i);
}
console.log( div3 + div5 + n )
}
}
fizzbuzz(100);
Mini-project (estimated time: 1 hour)
We should be starting to realize the difference between knowing how to program and knowing a particular programming language. If our program uses only the fundamental structures, then we should be able to port it to a lot of languages with ease and it will look remarkably similar, just like the Python and JS versions of fizzbuzz above.
Php anyone?
For example, let's port fizzbuzz to Php. Php is one of the most popular server-side languages. To port fizzbuzz, we do not need to master the language. Since we have been using mostly structures that are common to all the languages, all we need to do is to find how to write them in Php. Good places to search are the standards of the language, stackoverflow, and samples of code, e.g.,
Php | note | |
---|---|---|
Comment | /* */ | /* same as C (multi-line) */ |
// | // same as C++ (single line) | |
functions | function foo() | // like JS and C |
bodies | { } | // curly braces like JS and C |
statements | ; | // use semi-colons like JS and C |
variables | $ | // precede with $ like in $x |
for loops | for ($i = 0; $i < 10; $i++) | // like JS and C |
comparisons | if (a > b) | // enclose in parentheses |
booleans | True and False | // uppercase like Python |
boolean ops | not and or | // same as in Python |
! && || | // same as in C and JS | |
concatenation | . | // "a"."b" == "ab" |
cast to str | (string) | // (string)5 == "5" |
cast to int | intval() | // intval("5") == 5 |
output | print() | // like Python |
echo() | // like Bash |
// php
function fizzbuzz($x) {
for ( $i = 1; $i < $x+1; $i++ ) {
$div3 = "";
if ($i % 3 == 0) {
$div3 = "fizz";
}
$div5 = "";
if ($i % 5 == 0) {
$div5 = "buzz";
}
$n = "";
if ($div3 == "" && $div5 == "") {
$n = (string)$i;
}
print( $div3 . $div5 . $n . "'\n'" );
}
}
fizzbuzz(100);
Java anyone?
Let's try Java, one of the most popular languages today. Java's syntax is more closer to that of Javascript and C than of Python. Let's see a port of our fizzbuzz to Java and verify that we can easily understand the core concept; indeed, the Java version of fizzbuzz is almost identical to the Javascript version:
- we declared the variables using their type instead of var
- We changed the comparison operator from === to ==
- We changed the casting and printing functions
- We changed the function declaration
Php | note | |
---|---|---|
Comment | /* */ | /* same as C (multi-line) */ |
// | // same as C++ (single line) | |
functions | public static void foo() | //modifier: public, protected or private |
return type: int, String, void, etc. | ||
bodies | { } | // curly braces like JS and C |
statements | ; | // use semi-colons like JS and C |
variables | type | // e.g., int, String, etc., like C |
for loops | for (int i = 0; i < 10; i++) | // like C |
comparisons | if (a > b) | // enclose in parentheses |
booleans | true and false | // lowercase like Javascript |
boolean ops | ! && || | // same as in C and JS |
concatenation | + | // "a"+"b" == "ab" |
cast to str | String.valueOf() | // String.valueOf(5) == "5" |
cast to int | Integer.parseInt() | // Integer.parseInt("5") == 5 |
output | System.out.println() |
// java
class Main {
public static void fizzbuzz( int x ) {
String div3, div5, n; // var declaration
for ( int i = 1; i < x; i++ ) {
div3 = "";
if ( i % 3 == 0 ) {
div3 = "fizz";
}
div5 = "";
if ( i % 5 == 0 ) {
div5 = "buzz";
}
n = "";
if ( div3 == "" && div5 == "" ) {
n = String.valueOf(i);
}
System.out.println(div3 + div5 + n);
}
}
public static void main(String[] args) {
fizzbuzz(100);
}
}
Lua anyone?
Your homework is to port fizzbuzz to Lua. Lua is the scripting language of many games, e.g., "World of Warcraft". Look at any website that has the syntax of Lua and get what you need to do your porting. Possible places to look at are:
Give it a good try before you look at the answer. Imagine the confidence that you will get in programming if you can port fizzbuzz to a language other than Python and Javascript on your own and on a whim: Awesome!