Advertisement
here2share

Converting from Python to Javascript...

Nov 23rd, 2019
339
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.99 KB | None | 0 0
  1. # Converting from Python to Javascript...
  2. '''
  3. Converting simple Python programs into equivalent Javascript programs (or vice-versa) can often be done relatively easily. Below are two equivalent programs.
  4. '''
  5.  
  6. ''' Maze solution in Python:
  7.    a simple program. '''
  8.  
  9. def mark_starting_point_and_move():
  10.     put("token")
  11.     while not front_is_clear():
  12.         turn_left()
  13.     move()
  14.  
  15. def follow_right_wall():
  16.     if right_is_clear():
  17.         turn_right()
  18.         move()
  19.     elif front_is_clear():
  20.         move()
  21.     else:
  22.         turn_left()
  23.  
  24. #  Program execution below
  25.  
  26. while not at_goal():
  27.     follow_right_wall()
  28.  
  29. '''
  30.  
  31. /* Maze solution in Javascript:
  32.   a simple program.            */
  33.  
  34. function mark_starting_point_and_move() {
  35.    put("token");
  36.    while (!front_is_clear()) {
  37.        turn_left();
  38.    }
  39.    move();
  40. }
  41.  
  42. function follow_right_wall(){
  43.    if (right_is_clear()){
  44.        turn_right();
  45.        move();
  46.    } else if (front_is_clear()) {
  47.        move();
  48.        }
  49.    else {
  50.        turn_left();
  51.    }
  52.  
  53. // Program execution below
  54.  
  55. while (!at_goal()){
  56.    follow_right_wall();
  57. }
  58.  
  59. To convert such a simple program from Python to Javascript, one can follow the following steps. [Note that not all those steps mentioned below are applicable in the sample program listed above.]
  60.  
  61.    Replace the keyword def by function.
  62.    Replace the colon : that indicates the beginning of a code block by {.
  63.    Add } at the end of a code block.
  64.    Surround conditions/test in if and while statement by parentheses (...).
  65.    Add semi-colons ; at the end of each statement.
  66.    Replace the keyword not by the symbol !.
  67.    Replace the keyword and by the symbols &&.
  68.    Replace the keyword or (not present above) by the symbols ||.
  69.    Replace the keywords True and False by true and false.
  70.    Replace the keyword elif by else if.
  71.    Replace the single line comment symbol # by //
  72.    Replace triple quotes enclosing a multi-line comment ''' ... ''' by /* ... */.
  73.  
  74. '''
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement