Python Syntax Flashcards
Python is a
dynamic programming language
Python is a powerful, flexible programming language you can use in web/Internet development, to write desktop graphical user interfaces (GUIs), create games, and much more. Python is:
- High-level, meaning reading and writing Python is really easy—it looks a lot like regular English!
- Interpreted, meaning you don’t need a compiler to write and run Python! You can write it here at Codecademy or even on your own computer (many are shipped with the Python interpreter built in—we’ll get to the interpreter later in this lesson).
- Object-oriented, meaning it allows users to manipulate data structures called objects in order to build and execute programs. We’ll learn more about objects later.
- Fun to use. Python is named after Monty Python’s Flying Circus, and example code and tutorials often refer to the show and include jokes in order to make learning the language more interesting.
This course assumes no previous knowledge of Python in particular or programming/computer science in general.
One of the most basic concepts in computer programming is the variable
A variable is a word/identifier that hangs onto a single value. For example, let’s say you needed the number 5
for your program, but you’re not going to use it immediately. You can set a variable, say spam
, to grab the value 5
and hang onto it for later use, like this:
spam = 5
Declaring variables in Python is easy; you just write out a name/identifier, like spam
, and use =
to assign it a value, and you’re done
Data Types
In this case, the data type of my_variable
is an integer (a positive or negative whole number). There are three data types in Python that are of interest to us at the moment: integers (int in Python language), floats (fractional numbers written with a decimal point, like 1.970
), and booleans (which can be True
or False
).
Computer programs, in large part, are created to manipulate data. Therefore, it’s important to understand the different types of data (or “datatypes”) that we can incorporate into our programs.
Never use quotation marks ('
or "
) with booleans, and always capitalize the first letter! Python is case-sensitive (it cares about capitalization). We’ll use quotation marks when we get to strings, which we’ll cover in the next unit.
Python and set them to different values, and you’ve learned about three different types of values: integers, floats, and booleans.
You can reassign a variable at any point. If you first set my_int
to 7
but later want to change it to 3
, all you have to do is tell Python my_int = 3
, and it’ll change the value of my_int
for you.
What’s a Statement?
You can think of a Python statement as being similar to a sentence in English: it’s the smallest unit of the language that makes sense by itself
Just like “I,” “like,” and “Spam” aren’t sentences by themselves, but “I like Spam” is, variables and data types aren’t statements in Python, but they are the building blocks that form them.
To continue the sentence analogy, it’s clear that we also need a kind of punctuation to make it obvious where one statement ends and another begins. If you’re familiar with JavaScript, you know that statements end with a semicolon (;
). In Python, statements are separated by whitespace. Just like you can’t toss around semicolons wherever you want in JS, you can’t throw whitespace around in Python.
This may take some getting used to, especially if you’re coming from a programming language where whitespace doesn’t matter.
Whitespace Means Right Space
IndentationError: expected an indented block
You’ll get this error whenever your Python whitespace is out of whack. (If you’ve studied JavaScript, think of improper whitespace as improper use of ;
or {}
.) When your punctuation’s off, your meaning can change entirely:
> The peasant said, “The witch turned me into a newt!”“The peasant,” said the witch, “turned me into a newt!”
See what we mean?
A Matter of Interpretation
In the introduction to this unit, we mentioned that Python is an interpreted language (meaning it runs using an interpreter). In the context of Codecademy, the interpreter is the console/output window in the top right corner of the page.
For now, think of the interpreter as a program that takes the code you write, checks it for syntax errors, and executes the statements in that code, line by line. It works as a go-between for you and the computer and lets you know the result of your instructions to the machine.
Single Line Comments
You may have noticed the instructions in the editor that begin with a #
(pound or hash) symbol.
These lines of code are called comments, and they aren’t read by the interpreter—they don’t affect the code at all. They’re plain English comments written by the programmer to provide instructions or explain how a particular part of the program works.
Since this improves the readability of your code tremendously (and will help you debug programs more quickly, since you’ll be able to tell at a glance what each part of the program is supposed to do), we encourage you to comment on your code whenever its purpose isn’t immediately obvious.
Multi-Line Comments
Sometimes you have to write a really long comment. #
will only work across a single line, and while you could write a multi-line comment and start each line with #
, that can be a pain.””
f you want to write a comment across multiple lines, you can include the whole block in a set of triple quotation marks, like so:
"""I'm a lumberjack and I'm okay I sleep all night and I work all day!"""
Arithmetic Operators
Python’s statements aren’t limited to simple expressions of assignment like spam = 3
; they can also include mathematical expressions using arithmetic operators.
There are six arithmetic operators we’re going to focus on:
- Addition (
+
) - Subtraction (
-
) - Multiplication (
*
) - Division (
/
) - Exponentiation (
**
) - Modulo (
%
)
Syntax
class ClassName(SuperClass): //same as above //use 'super' keyword to get from above
Example
class RaceHorse(Horse): """A faster horse that inherits from Horse""" def movement(self): return "run" def movement_slow(self): super(Horse,self).movement() def \_\_repr\_\_(self): return "%s race horse weighing %f and wild status is %b" (self.color,self.weight,self.wild) >> horse3 = RaceHorse("white",200) >> print horse3.movement_slow() "walk" >> print horse3.movement() "run"
Syntax
class ClassName(object): """This is a class""" class_variable def \_\_init\_\_(self,*args): self.args = args def \_\_repr\_\_(self): return "Something to represent the object as a string" def other_method(self,*args): //do something else
Example
class Horse(object): """Horse represents a Horse""" species = "Equus ferus caballus" def \_\_init\_\_(self,color,weight,wild=False): self.color = color self.weight = weight self.wild = wild def \_\_repr\_\_(self): return "%s horse weighing %f and wild status is %b" (self.color,self.weight,self.wild) def make_sound(self): print("neighhhh") def movement(self): return "walk"
Dictionaries
Dictionaries are Python’s built-in associative data type. A dictionary is made of key-value pairs where each key corresponds to a value. Like sets, dictionaries are unordered. A few notes about keys and values: * The key must be immutable and hashable while the value can be of any type. Common examples of keys are tuples, strings and numbers. * A single dictionary can contain keys of varying types and values of varying types.
Syntax
dict() #creates new empty dictionary {} #creates new empty dictionary
Example
>> my_dict = {} >> content_of_value1 = "abcd" >> content_of_value2 = "wxyz" >> my_dict.update({"key_name1":content_of_value1}) >> my_dict.update({"key_name2":content_of_value2}) >> my_dict {'key_name1':"abcd", 'key_name2':"wxyz"} >> my_dict.get("key_name2") "wxyz"
Syntax
{key1:value1,key2:value2}
Example
>> my_dict = {"key1":[1,2,3],"key2":"I am a string",123:456} >> my_dict["key1"] #[1,2,3] >> my_dict[123] #456 >> my_dict["new key"] = "New value" >> print my_dict {"key2":"I am a string", "new key":"New value", "key1":[1,2,3],123:456}
Syntax
def function_name(parameters): # Some code here
Example
def add_two(a, b): c = a + b return c
# or without the interim assignment to c
def add_two(a, b):
return a + b
~~~
```
Syntax
def function_name(parameters, named_default_parameter=value): # Some code here
Example
def shout(exclamation="Hey!"): print exclamation shout() # Displays "Hey!" shout("Watch Out!") # Displays "Watch Out!"
Function Objects
Python functions are first-class objects, which means that they can be stored in variables and lists and can even be returned by other functions.
Python functions are first-class objects, which means that they can be stored in variables and lists and can even be returned by other functions.
Example
# Returning functions from functions
# A simple function
def say_hello(greeter, greeted):
return “Hello, “ + greeted + “, I’m “ + greeter + “.”
~~~
# We can use it like this: print say_hello("Alice", "Bob") # Displays "Hello, Bob, I'm Alice."
# We can also use it in a function: def produce_greeting_from_alice(greeted): return say_hello("Alice", greeted)
print produce_greeting_from_alice(“Bob”) # Displays “Hello, Bob, I’m Alice.”
# We can also return a function from a function by nesting them: def produce_greeting_from(greeter): def greet(greeted): return say_hello(greeter, greeted) return greet
# Here we create a greeting function for Eve: produce_greeting_from_eve = produce_greeting_from("Eve") # 'produce_greeting_from_eve' is now a function: print produce_greeting_from_eve("Alice") # Displays "Hello, Alice, I'm Eve."
# You can also invoke the function directly if you want: print produce_greeting_from("Bob")("Eve") # Displays "Hello, Eve, I'm Bob."
```
Example
# Storing function objects in variables:
def say_hello(name):
return “Hello, “ + name
~~~
foo = say_hello("Alice") # Now the value of 'foo' is "Hello, Alice"
fun = say_hello # Now the value of 'fun' is a function object we can use like the original function: bar = fun("Bob") # Now the value of 'bar' is "Hello, Bob"
```
Example
# Using functions in a dictionary instead of long if statements: # Let's say we have a variable called 'current_action' and we want stuff to happen based on its value: if current_action == 'PAUSE': pause() elif current_action == 'RESTART': restart() elif current_action == 'RESUME': resume()
# This can get long and complicated if there are many values.
# Instead, we can use a dictionary:
~~~
response_dict = {
‘PAUSE’: pause,
‘RESTART’: restart,
‘RESUME’: resume
}
response_dictcurrent_action # Gets the correct function from response_dict and calls it
~~~
Syntax
len(iterable)
Example
>> my_list = [0,4,5,2,3,4,5] >> len(my_list) 7 >> my_string = 'abcdef' >> len(my_string) 6
Syntax
[variable for variable in iterable condition] [variable for variable in iterable]
Example
>> x_list = [1,2,3,4,5,6,7] >> even_list = [num for num in x_list if (num % 2 == 0)] >> even_list [2,4,6] >> m_list = ['AB', 'AC', 'DA', 'FG', 'LB'] >> A_list = [duo for duo in m_list if ('A' in duo)] >> A_list ['AB', 'AC', 'DA']
Lists
Example
>> x = [1, 2, 3, 4] >> y = ['spam', 'eggs'] >> x [1, 2, 3, 4] >> y ['spam','eggs'] >> y.append('mash') >> y ['spam', 'eggs', 'mash'] >> y += ['beans'] >> y ['spam', 'eggs', 'mash', 'beans']
Loops
loop permits code to execute repeatedly until a certain condition is met.
A While loop permits code to execute repeatedly until a certain condition is met. This is useful if the number of iterations required to complete a task is unknown prior to flow entering the loop.
Syntax
while condition: //do something
Example
>> looping_needed = True >> >> while looping_needed: >> # some operation on data >> if condition: >> looping_needed = False
For Loops
Python provides a clean iteration syntax. Note the colon and indentation.
Example
>> for i in range(0, 3): >> print(i*2) 0 2 4 >> m_list = ["Sir", "Lancelot", "Coconuts"] >> for item in m_list: >> print(item) Sir Lancelot Coconuts >> w_string = "Swift" >> for letter in w_string: >> print(letter) S w i f t
range()
The range() function returns a list of integers, the sequence of which is defined by the arguments passed to it.
The range() function returns a list of integers, the sequence of which is defined by the arguments passed to it.
Syntax
argument variations: range(terminal) range(start, terminal) range(start, terminal, step_size)
Example
>> range(4) [0, 1, 2, 3] >> range(2, 8) [2, 3, 4, 5, 6, 7] >> range(2, 13, 3) [2, 5, 8, 11]
Sets
Example
>> new_set = {1, 2, 3, 4, 4, 4,'A', 'B', 'B', 'C'} >> new_set {'A', 1, 'C', 3, 4, 2, 'B'} >> dup_list = [1,1,2,2,2,3,4,55,5,5,6,7,8,8] >> set_from_list = set(dup_list) >> set_from_list {1, 2, 3, 4, 5, 6, 7, 8, 55}
A Pythonic way of extracting “slices” of a list using a special bracket notation that specifies the start and end of the section of the list you wish to extract. Leaving the beginning value blank indicates you wish to start at the beginning of the list, leaving the ending value blank indicates you wish to go to the end of the list. Using a negative value references the end of the list (so that in a list of 4 elements, -1 means the 4th element). Slicing always yields another list, even when extracting a single value.
Slice
Example
>> # Specifying a beginning and end: >> x = [1, 2, 3, 4] >> x[2:3] [3] >> # Specifying start at the beginning and end at the second element >> x[:2] [1, 2] >> # Specifying start at the next to last element and go to the end >> x[-2:] [3, 4] >> # Specifying start at the beginning and go to the next to last element >> x[:-1] [1, 2, 3] >> # Specifying a step argument returns every n-th item >> y = [1, 2, 3, 4, 5, 6, 7, 8] >> y[::2] [1, 3, 5, 7] >> # Return a reversed version of the list ( or string ) >> x[::-1] [4, 3, 2, 1] >> # String reverse >> my_string = "Aloha" >> my_string[::-1] "aholA"
Using the str() function allows you to represent the content of a variable as a string, provided that the data type of the variable provides a neat way to do so. str() does not change the variable in place, it returns a ‘stringified’ version of it. On a more technical note, str()
calls the special \_\_str\_\_
method of the object passed to it.
Syntax
str(object)
Example
>> # such features can be useful for concatenating strings >> my_var = 123 >> my_var 123 >> str(my_var) '123' >> my_booking = "DB Airlines Flight " + str(my_var) >> my_booking 'DB Airlines Flight 123'
Example
>> my_string1 = "this is a valid string" >> my_string2 = 'this is also a valid string' >> my_string3 = 'this is' + ' ' + 'also' + ' ' + 'a string' >> my_string3 "this is also a string"
Tuples
Example
>> x = (1, 2, 3, 4) >> y = ('spam', 'eggs') >> my_list = [1,2,3,4] >> my_tuple = tuple(my_list) >> my_tuple (1, 2, 3, 4)
Tuple Assignment
Tuples can be expanded into variables easily.
Example
name, age = ("Alice", 19) # Now name has the value "Alice" and age has the value 19
# You can also omit the parentheses:
name, age = “Alice”, 19
~~~
~~~
Arrays
Booleans
Code Comments
console
Functions
If statement
Loops
Math
Numbers
Objects
OOP
Popup boxes
Strings
Switch statements
Ternary Operator
Variables
Arrays
Array literals
You can create arrays in two different ways. The most common of which is to list values in a pair of square brackets. JavaScript arrays can contain any types of values and they can be of mixed types.
Syntax
var arrayName = [element0, element1, …, elementN]
Example
var primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37];
var junk = [10, “Hello”, Math, console, { lots: “of different types” }];
Read more
https: //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/Array http: //www.javascripter.net/faq/creatingarrays.htm
Accessing array elements
You can get elements out of arrays if you know their index. Array elements’ indexes start at 0 and increment by 1, so the first element’s index is 0, the second element’s index is 1, the third element’s is 2, etc.
Syntax
array[index]
Example
var primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37];
primes[0]; // 2
primes[3]; // 7
primes[150]; // undefined
Array contructor
You can also create an array using the array constructor.
Example
var myArray = new Array( 45 , "Hello World!" , true , 3.2 , undefined); console.log(myArray);
//Output : [45, ‘Hello World!’, true, 3.2, undefined]
Example
var things = new Array();
stuff[0] = 34;
stuff[4] = 20;
stuff // [34, undefined, undefined, undefined, 20]
Read more
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/Array#Example.3A\_Creating\_an\_array
Multi-dimensional Arrays
A two-dimensional array is an array within an array. If you fill this array with another array you get a three-dimensional array and so on.
Example
var multidimensionalArray = [[1,2,3],[4,5,6],[7,8,9]] // two dimensions, 3x3
Accessing nested array elements
Accessing multi dimensional array elements is quite similar to one-dimension arrays . They are accessed by using [index][index]….. (number of them depends upon the number of arrays deep you want to go inside).
Syntax
array[index][index]….
Example
var myMultiArray = [
[1,2,3,4,5, [1,2,3,4,5] ],
[6,7,8,9,10 , [1,2,3,4,6] ],
[11,12,13,14,15 , [1,2,3,4,5] ],
[16,17,18,19,20, [1,2,3,4,5] ]
];
console.log( myMultiArray[1][5][4] ); //Outputs 6 , the value in the last element of the last element of the second element of myMultiArray.
Booleans
Boolean literals
Syntax
true
false
Boolean logical operators
Syntax
expression1 && expression2 //returns true if both the expressions evaluate to true
expression3 || expression4 // return true if either one of the expression evaluates to true
!expression5 // returns the opposite boolean value of the expression
Example
if ( true && false )alert("Not executed!"); //because the second expression is false
if( false || true )alert("Executed!"); //because any one of the expression is true
if( !false )alert("Executed!"); // because !false evaluates to true
!!true // remains true
Example
if(!false && ( false || (false && true) ))alert(“Guess what…”);
/* not executed because
!false && ( false || (false && true) ) - becomes
!false && ( false || false) - becomes
true && false , which is false.*/
Example
/* An important thing to note here is the Operator Precedence - which determines the order in which operators are evaluated. Operators with higher precedence are evaluated first. Thus among the four - () , && , || , ! */
// Brackets - have the highest precedence // ! - lower than Brackets // && - lower than ! // || - the lowest
if(true && !!false || true)alert(“Guess again ??”);
/* Executed , here is the evaluation process-
true && !!false || true - becomes
true && false || true - (no brackets present , so ! evaluated ) becomes
false || true - (then && evaluated) which becomes true */
Example
/* Next important thing is the Associativity - which determines the order in which operators of the same precedence are processed. For example, consider an expression: a * b * c . Left-associativity (left-to-right) means that it is processed as (a * b) * c, while right-associativity (right-to-left) means it is interpreted as a * (b * c). */
// Brackets , && , || have left to right associativity // ! has right to left associativity // So ,
!false && !!false //false // evaluated in the manner - !false && false - true && false - false
Comparison operators
Syntax
x === y // returns true if two things are equal
x !== y // returns true if two things are not equal
x <= y // returns true if x is less than or equal to y
x >= y // returns true if x is greater than or equal to y
x < y // returns true if x is less than y
x > y // returns true if x is greater than y
Note:
An important thing to note here is that not only Boolean literals (true and false) assert truth or false , but there are some other ways too to derive true or false.Have a look at the examples.
Example
if(1)console.log(“True!”); // output True! , since any non-zero number is considered to be true
if(0)console.log(“I doubt if this gets executed”); // not executed , since 0 is considered to be false
if(“Hello”)alert(“So, any non-empty String is also true.”); //Gets executed
if(““)alert(“Hence , an empty String is false”); // Not executed
Read more
http://www.sitepoint.com/javascript-truthy-falsy/
== vs. ===
A simple explanation would be that == does just value checking ( no type checking ) , whereas , === does both value checking and type checking . Seeing the examples may make it all clear. It is always advisable that you never use == , because == often produces unwanted results
Syntax
expression == expression
expression === expression
Example
‘1’ == 1 //true (same value)
‘1’ === 1 // false (not the same type)
true == 1 // true (because 1 stands for true ,though it’s not the same type)
true === 1 // false (not the same type)
Code Comments
Definition
Code comments are used for increasing the readability of the code.If you write 100 lines of code and then forget what each function did , it’s not useful at all. Comments are like notes , suggestions , warnings ,etc. that you can put for yourself. Code comments are not executed
Single Line Comment
Anything on the line following // will be a comment while anything before will still be code.
Syntax
console.log(“This code will be run”)
//console.log(“Because this line is in a comment, this code will not be run.”)
Syntax
// This is a single line comment.
Multi-Line Comment
Anything between /* and */ will be a comment.
Syntax
/* This is
a multi-line
comment!
*/
Example
/*
alert(“Hello,I won’t be executed.”);
console.log(“Hello ,I also will not be executed”);
*/
console
console.log
Prints text to the console. Useful for debugging.
Example
console. log(‘Poker night!’);
console. time
This function starts a timer which is useful for tracking how long an operation takes to happen.You give each timer a unique name, and may have up to 10,000 timers running on a given page.When you call console.timeEnd() with the same name, the browser will output the time, in milliseconds, that elapsed since the timer was started.
Syntax
console.time(timerName);
Example
console.time(“My Math”);
var x = 5 + 5;
console.log(x);
console.timeEnd(“My Math”);
console.log(“Done the math.”);
/* Output:
10
My Math: (time taken)
Done the math.
Read more
https: //developer.mozilla.org/en-US/docs/Web/API/console.time https: //developer.mozilla.org/en-US/docs/Web/API/console.timeEnd
console.timeEnd
Stops a timer that was previously started by calling console.time().
Syntax
console.timeEnd(timerName);
Example
console.time(“My Math”);
var x = 5 + 5;
console.log(x);
console.timeEnd(“My Math”);
/* Output :
10
My Math: (time taken)
Read more
https://developer.mozilla.org/en-US/docs/Web/API/console.timeEnd
Functions
Function definition
A function is a JavaScript procedure—a set of statements that performs a task or calculates a value.It is like a reusable piece of code. Imagine , having 20 for loops ,and then having a single function to handle it all . To use a function, you must define it somewhere in the scope from which you wish to call it. A function definition (also called a function declaration) consists of the function keyword, followed by the name of the function, a list of arguments to the function, enclosed in parentheses and separated by commas, the JavaScript statements that define the function, enclosed in curly braces, { }.
Syntax
function name(argument1 , argument2 …. argumentN){
statement1;
statement2;
..
..
statementN;
}
Example
function greet(name) { return "Hello" + name + "!"; }
Read more
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions
Function calling
Syntax
functionName(argument1, argument2, …, argumentN);
Example
greet("Anonymous"); // Hello Anonymous!
Function hoisting
The two ways of declaring functions produce different results. Declaring a function one way “hoists” it to the top of the call, and makes it available before it’s actually defined.
Example
hoistedFunction(); // Hello! I am defined immediately!
notHoistedFunction(); // ReferenceError: notHoistedFunction is not defined
function hoistedFunction () { console.log('Hello! I am defined immediately!'); }
var notHoistedFunction = function () { console.log('I am not defined immediately.'); }
Read more
http://jamesallardice.com/explaining-function-and-variable-hoisting-in-javascript/
If statement
if
It simply states that if this condition is true , do this , else do something else ( or nothing ) . It occurs in varied forms.
Syntax
// Form : Single If if (condition) { // code that runs if the condition is true }
Example
if (answer === 42) {
console.log(‘Told you so!’);
}
else
A fallback to an if statement. This will only get executed if the previous statement did not.
Syntax
// If the condition is true, statement1 will be executed. // Otherwise, statement2 will be executed.
if (condition) { // statement1: code that runs if condition is true } else { // statement2: code that runs if condition is false }
Example
if (gender == “male”) {
console.log(“Hello, sir!”);
} else {
console.log(“Hello, ma’am!”);
}
else if
This is like an else statement, but with its own condition. It will only run if its condition is true, and the previous statement’s condition was false.
Syntax
// Form : else if . If the condition is true, statement1 will be executed. Otherwise, condition2 is checked . if it is true , then statement2 is executed. Else , if nothing is true , statement3 is executed.
if (condition1) {
statement1;
} else if (condition2) {
statement2;
} else {
statement3;
}
Example
if (someNumber > 10) {
console.log(“Numbers larger than 10 are not allowed.”);
} else if (someNumber < 0) {
console.log(“Negative numbers are not allowed.”);
} else {
console.log(“Nice number!”);
}
Loops
For Loops
You use for loops, if you know how often you’ll loop. The most often used varName in loops is “i”.
Syntax
for ([var i = startValue];[i \< endValue]; [i+=stepValue]) { // Your code here }
Example
for (var i = 0; i \< 5; i++) { console.log(i); // Prints the numbers from 0 to 4 }
Example
var i; // “outsourcing” the definition
for (i = 10; i >= 1; i–) {
console.log(i); // Prints the numbers from 10 to 1
}
Example
/* Note that all of the three statements are optional, i.e. , */
var i = 9;
for(;;){
if(i === 0)break;
console.log(i);
i–;
}
//This loop is perfectly valid.
While Loops
You use while loops, if you don’t know how often you’ll loop.
Syntax
while (condition) { // Your code here }
Example
var x = 0; while (x \< 5) { console.log(x); // Prints numbers from 0 to 4 x++; }
Example
var x = 10;
while (x <= 5) {
console.log(x); // Won’t be executed
x++;
}
Read more
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/while
Do While Loops
You use do while loops, if you have to loop at least once, but if you don’t know how often.
Example
var x = 10; do { console.log(x); // Prints 10 x++; } while (x \<= 5);
Syntax
do { // Your code here } while (condition);
Example
var x = 0; do { console.log(x); // Prints numbers from 0 to 4 x++; } while (x \< 5);
Read more
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/do...while
Math
random
Returns a random number between 0 and 1.
Syntax
Math.random()
Example
Math.random(); // A random number between 0 and 1.
floor
Returns the largest integer less than or equal to a number.
Syntax
Math.floor(expression)
Example
Math.floor(9.99); // 9
Math.floor(1 + 0.5); // 1
Math.floor(Math.random() * X + 1); // Returns a random number between 1 and X
pow
Returns base raised to exponent.
Syntax
Math.pow(base,exponent)
Example
Math.pow(2,4); // gives 16
Read more
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/Math/pow?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal\_Objects%2FMath%2Fpow
ceil
Returns the smallest integer greater than or equal to a number.
Syntax
Math.ceil(expression)
Example
Math.ceil(45.4); // 46
Math.ceil(4 - 1.9); // 3
Read more
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/Math/ceil
PI
Returns the ratio of the circumference of a circle to its diameter, approximately 3.14159 or in better terms, the value of PI (π). Note in syntax , we do not put ()
at the end of Math.PI
because Math.PI
is not a function.
Syntax
Math.PI
Example
Math.round(Math.PI); // rounds the value of PI ,gives 3
Math.ceil(Math.PI); // 4
Read more
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/Math/PI
sqrt
Returns the square root of a number.
Syntax
Math.sqrt(expression)
Example
Math.sqrt(5+4); // 3
Math.sqrt(Math.sqrt(122+22) + Math.sqrt(16)); //4
Read more
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/Math/sqrt?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal\_Objects%2FMath%2Fsqrt
Numbers
% (Modulus)
it returns the remainder left after dividing the left hand side with the right hand side.
Syntax
number1 % number2
Example
14 % 9 // returns 5
isNaN
Returns true if the given number is not a number , else returns false.
Syntax
isNaN([value])
Example
var user_input = prompt(“Enter a number”); // Enter “a number”
if(isNaN(user_input))
alert(“I told you to enter a number.”);
//alert executed , since “a number” is not a number
//Another important thing:
if( isNaN(“3”) )
alert(“bad”);
//Not executed , because the string “3” gets converted into 3 ,and 3 is a number
Basic Arithmetic
Doing basic arithmetic is simple.
Syntax
4 + 5; // 9
4 * 5; // 20
5 - 4; // 1
20 / 5; // 4
Prefix and Postfix increment/decrement operators
Prefix increment / decrement operators are operators that first increase the value of the variable by 1 (increment) or decrease the value of an expression / variable by 1 (decrement) and then return this incremented / decremented value. They are used like ++(variable) [increment] or –(varaible) [decrement] On the other hand , Postfix increment / decrement operators are operators that first return the value of the variable and then increase the value of thAT variable by 1 (increment) or decrease the value of the variable by 1 (decrement) . They are used like (variable)++ [increment] or (varaible)– [decrement]
Syntax
–variable //Prefix Decrement
++variable //Prefix Increment
variable– //Postfix Decrement
variable++ //Postfix Increment
Example
//The examples will make it clear
var x = 15; // x has a value of 15
var y = x++;
// since it is postfix , the value of x (15) is first assigned to y and then the value of x is incremented by 1
console.log(y); //15
console.log(x); //16
var a = 15; // a has a value of 15
var b = ++a;
// since it is prefix , the value of a (15) is first incremented by 1 and then the value of x is assigned to b
console.log(b); //16
console.log(a); //16
Example
//Guess the output in each, and then check your answer on labs.codecademy.com
//Question 1
var x = 43;
var y = 34;
var z = x++ + –y;
console.log(z);
console.log(y);
console.log(x);
//Question 2
var a = 1;
var b = 2;
var c = ++a * b++ / 2 + 1 - b + a;
console.log(c);
console.log(b);
console.log(a);
//Question 3
var p = 6;
var q = 3;
var r = Math.pow((–p - 4) , (q++)) + Math.sqrt(q) + –q;
console.log(r);
console.log(q);
console.log(p);
Objects
Object Literals
Syntax
{
“property 1”: value1,
property2: value2,
number: value3
}
Example
var obj = { name: "Bob", married: true, "mother's name": "Alice", "year of birth": 1987, getAge: function () { return 2012 - obj["year of birth"]; }, 1: 'one' };
Property Access
Syntax
name1[string]
name2.identifier
Example
obj[‘name’]; // ‘Bob’
obj. name; // ‘Bob’
obj. getAge(); // 24
OOP
Classes
A class can be thought of as a template to create many objects with similar qualities. Classes are a fundamental component of object-oriented programming (OOP). Syntax
SubClass.prototype = new SuperClass();
Example
var Lieutenant = function (age) { this.rank = "Lieutenant"; this.age = age; };
Lieutenant.prototype = new PoliceOfficer();
Lieutenant.prototype.getRank = function () {
return this.rank;
};
var John = new Lieutenant(67);
John.getJob(); // ‘Police Officer’
John.getRank(); // ‘Lieutenant’
John.retire(); // true
Popup boxes
alert
Display an alert dialog with the specified message and an OK button. Note: The alert dialog should be used for messages which do not require any response on the part of the user, other than the acknowledgement of the message.
Syntax
alert(message);
Example
alert(“Hello World”);
Syntax
alert(variable_name)
Example
var my_message = !false;
alert(my_message);
confirm
Syntax
confirm(“message”) //returns true if confirmed, false otherwise
Example
if ( confirm(“Are you sure you want to delete this post?”) ) {
deletePost();
}
prompt
The prompt() displays a dialog with an optional message prompting the user to input some text. If the user clicks the "Cancel" button , null is returned. Syntax
prompt(message);
Example
var name = prompt("Enter your name:"); console.log("Hello " + name + "!");
Syntax
prompt(message,value) // value is a string containing the default value displayed in the text input field. It is an optional parameter.
Example
var name = prompt("Enter your name:","Your name here"); console.log("Hello " + name + "!");
Read more
https://developer.mozilla.org/en-US/docs/Web/API/window.prompt
Strings
Strings are text. They are denoted by surrounding text with either single or double quotes.
Syntax
“string of text”
‘string of text’
Concatenation
Syntax
string1 + string2
Example
"some" + "text"; // returns "sometext" var first = "my"; var second = "string"; var union = first + second; // union variable has the string "mystring"
length
Returns the length of the string.
Syntax
string.length
Example
“My name”.length // 7 , white space is also counted
““.length // 0
toUpperCase, toLowerCase
Changes the cases of all the alphabetical letters in the string.
Example
“my name”.toUpperCase(); // Returns “MY NAME”
“MY NAME”.toLowerCase(); // Returns “my name”
trim()
Removes whitespace from both ends of the string.
Syntax
string.trim()
Example
” a “.trim(); // ‘a’
“ a a “.trim(); // ‘a a’
Read more
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/String/Trim
replace()
Returns a string with the first match substring replaced with a new substring.
Example
“original string”.replace(“original”, “replaced”); // returns “replaced string”
charAt()
Returns the specified character from a string. Characters in a string are indexed from left to right. The index of the first character is 0, and the index of the last character in a string called stringName is stringName.length - 1. If the index you supply is out of range, JavaScript returns an empty string.
Syntax
string.charAt(index) // index is an integer between 0 and 1 less than the length of the string.
Example
“Hello World!”.charAt(0); // ‘H’
“Hello World!”.charAt(234); // ‘’
Read more
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/String/charAt
substring()
Returns the sequence of characters between two indices within a string.
Syntax
string.substring(indexA[, indexB]) //indexA : An integer between 0 and the length of the string // indexB : (optional) An integer between 0 and the length of the string.
Example
"adventures".substring(2,9); // Returns "venture" // It starts from indexA(2) , and goes up to but not including indexB(9) "hello".substring(1); // returns "ello" "Web Fundamentals".substring(111); // returns '' "In the market".substring(2,999); // returns ' the market' "Fast and efficient".substring(3,3); // returns '' "Go away".substring("abcd" , 5); // returns 'Go aw' // Any non-numeric thing is treated as 0
indexOf()
Returns the index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex, Returns -1 if the value is not found. The indexOf method is case sensitive.
Syntax
string.indexOf(searchValue[, fromIndex]) //fromIndex is optional.It specifies from which index should the search start.Its default value is 0.
Example
“My name is very long.”.indexOf(“name”); // returns 3
“My name is very long.”.indexOf(“Name”); // returns -1 , it’s case sensitive
“Where are you going?”.indexOf(“are”,11); //returns -1
“Learn to Code”.indexOf(“”); //returns 0
“Learn to Code”.indexOf(““,3); //returns 3
“Learn to Code”.indexOf(““,229); returns 13 , which is the string.length
Read more
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/String/indexOf
Switch statements
switch
Acts like a big if / else if / else chain. Checks a value against a list of cases, and executes the first case that is true. It goes on executing all other cases it finds after the first true case till it finds a breaking statement,after which it breaks out of the switch If it does not find any matching case , it executes the default case.
Example
var gender = “female”;
switch (gender) {
case “female”:
console.log(“Hello, ma’am!”);
case “male”:
console.log(“Hello, sir!”);
break;
default:
console.log(“Hello!”);
}
/* Output:
Hello, ma’am!
Hello, sir!
because break statement is found at the second case so execution stops there */
Syntax
switch (expression) {
case label1:
statements1
[break;]
case label2:
statements2
[break;]
…
case labelN:
statementsN
[break;]
default:
statements_def
[break;]
}
Example
var gender = “female”;
switch (gender) {
case “female”:
console.log(“Hello, ma’am!”);
case “male”:
console.log(“Hello, sir!”);
default:
console.log(“Hello!”);
}
/* Output:
Hello, ma’am!
Hello, sir!
Hello!
because no breaking statement is found it executes all of the cases after the true case (which is case 1) */
Ternary Operator
The ternary operator is usually used as a shortcut for the if statement.
Syntax
condition ? expr1 : expr2
Example
var grade = 85; console.log("You " + (grade \> 50 ? "passed!" : "failed!"));
//Output: You passed!
/* The above statement is same as saying:
if(grade > 50){
console.log(“You “ + “passed!”); //or simply “You passed!”
}
else{
console.log(“You “ + “failed!”);
}
*/
Syntax
condition ? (condition ? expr1 : expr2) : expr3
Example
var grade = 90; console.log( "Your grade is: " + (grade \> 50 ? (grade \>= 90? "Excellent!":"Average"):"Need to be improved") );
// Output: Your grade is: Excellent!
/* This is a nested if statement ,same as writing:
if(grade > 50){
if(grade >= 90){
console.log(“Your grade is: Excellent!”):
}
else{
console.log(“Your grade is: Average”);
}
}
else{
console.log(“Your grade is: Need to be improved”);
}
*/
Syntax
condition ? expr1 : (condition( expr2 : expr3 ))
Example
var grade = 51;
console.log( “Your grade is: “ + (grade >= 90 ? “Excellent!”: (grade > 50? “Average” : “Needs to be improved”)) );
/* Output: Your grade is: Average
This is in the form of an else if statements , similar to the following:
if(grade >= 90){
console.log(“Your grade is: Excellent!”);
}
else if (grade > 50){
console.log(“Your grade is: Average”);
}
else{
console.log(“Your grade is: Needs to be improved”);
}
*/
Variables
Variable Assignment
Syntax
var name = value;
Example
var x = 1; var myName = "Bob"; var hisName = myName;
Variable changing
Syntax
varname = newValue
Example
var name = "Michael" //declare variable and give it value of "Michael" name = "Samuel" //change value of name to "Samuel"