<?xml version="1.0"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
	<id>http://classes.engineering.wustl.edu/cse330/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Alex</id>
	<title>CSE330 Wiki - User contributions [en]</title>
	<link rel="self" type="application/atom+xml" href="http://classes.engineering.wustl.edu/cse330/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Alex"/>
	<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Special:Contributions/Alex"/>
	<updated>2026-11-15T18:16:33Z</updated>
	<subtitle>User contributions</subtitle>
	<generator>MediaWiki 1.34.4</generator>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Module_6&amp;diff=2558</id>
		<title>Module 6</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Module_6&amp;diff=2558"/>
		<updated>2018-05-04T16:19:35Z</updated>

		<summary type="html">&lt;p&gt;Alex: /* Group Project */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;__NOTOC__ &lt;br /&gt;
Module 6 builds upon the JavaScript skills you learned in Module 5.&lt;br /&gt;
&lt;br /&gt;
== Reading ==&lt;br /&gt;
&lt;br /&gt;
The following articles on the online class wiki textbook contain information that will help you complete the assignments.&lt;br /&gt;
&lt;br /&gt;
* [[Node.JS]]&lt;br /&gt;
* [[Socket.IO]]&lt;br /&gt;
&lt;br /&gt;
== Individual Assignments ==&lt;br /&gt;
&lt;br /&gt;
=== Install Node.JS ===&lt;br /&gt;
&lt;br /&gt;
Install Node.JS from Apt or Yum according to the instructions in the [[Node.JS]] guide.&lt;br /&gt;
&lt;br /&gt;
=== Static File Server in Node.JS ===&lt;br /&gt;
&lt;br /&gt;
The individual portion of Module 6 is short in order to give you enough time to complete the group portion.&lt;br /&gt;
&lt;br /&gt;
# Copy the example code from the Node.JS guide into a file called ''static_server.js'' or something of that nature.  Save it on your EC2 instance (but not in a place that Apache can serve!).&lt;br /&gt;
#: Ensure that you understand what the static file server script is doing…&lt;br /&gt;
# Make a directory parallel to ''static_server.js'' named ''static''.&lt;br /&gt;
# Change &amp;quot;&amp;lt;STATIC DIRECTORY NAME&amp;gt;&amp;quot; on line 11 of the static fileserver example code to reflect the name of the directory you just made.&lt;br /&gt;
# Save the following files in your ''static'' directory:&lt;br /&gt;
#* ''hello.txt'', a text file containing &amp;quot;Hello World&amp;quot;&lt;br /&gt;
#* ''brookings.jpg'', an image file you can download from here: http://classes.engineering.wustl.edu/cse330/content/brookings.jpg&lt;br /&gt;
#* ''college.html'', an HTML document based on the [[HTML and CSS#Quick and Easy Page Layout|Quick and Easy HTML Layout]] containing an image tag pointing to ''brookings.jpg''&lt;br /&gt;
#* ''phpinfo.php'', a PHP file containing the phpinfo command that generates a diagnostic page of the server:&lt;br /&gt;
#: &amp;lt;source lang=&amp;quot;php&amp;quot;&amp;gt;&amp;lt;?php   phpinfo();   ?&amp;gt;&amp;lt;/source&amp;gt;&lt;br /&gt;
# Boot up your Node.JS static fileserver, and from your browser, load all four of the files you created in step 4.&lt;br /&gt;
#: Which ones work and which ones don't?  Why might this be the case?&lt;br /&gt;
&lt;br /&gt;
== Group Project ==&lt;br /&gt;
&lt;br /&gt;
In the group portion of Module 6 you will create a multi-room chat server using Node.JS and Socket.IO. This project must be completed using Node.JS.&lt;br /&gt;
&lt;br /&gt;
This chat service will contain a main lobby where users sign on with a nickname and can communicate with each other.  Users may also create chat rooms for other to join.  The entire app should be displayed on a single webpage, listing the room you are in, all available rooms, and the users in the current room.&lt;br /&gt;
&lt;br /&gt;
The single room chat server and client are provided here: [[Socket.IO]]&lt;br /&gt;
&lt;br /&gt;
== Grading ==&lt;br /&gt;
&lt;br /&gt;
We will be grading the following aspects of your work.  There are 75 points total.&lt;br /&gt;
&lt;br /&gt;
'''Assignments (including code) must be committed to Bitbucket by the end of class on the due date (commit early and often). Failing to commit by the end of class on the due date will result in a 0. ''' &lt;br /&gt;
&lt;br /&gt;
_________&lt;br /&gt;
&lt;br /&gt;
# '''Individual Portion (25 Points):'''&lt;br /&gt;
#* Node.JS is installed on your EC2 instance (5 points)&lt;br /&gt;
#*: ''Take a screenshot of your browser visiting your EC2 instance serving up the college.html web page on port 3456, make sure the URL is visible in the screenshot.''&lt;br /&gt;
#* The ''hello.txt'', ''brookings.jpg'', and ''college.html'' files all load successfully (4 points each)&lt;br /&gt;
#* Visiting a file that does not exist inside the ''static'' directory results in a 404 (4 points)&lt;br /&gt;
#* Discuss in the README.md why ''phpinfo.php'' behaves the way it does when loaded through Node.JS (4 points)&lt;br /&gt;
#* Make sure all of your individual portion files are pushed to Bitbucket (include your node.js file, hello.txt, brookings.jpg, college.html, and phpinfo.php)&lt;br /&gt;
#*: ''The TA should be able to simply download your repo and start up your file server, without having to copy files or create additional subdirectories''&lt;br /&gt;
# '''Multi-room Chat Server (50 Points):'''&lt;br /&gt;
#* '''''Administration of user created chat rooms (25 Points):'''''&lt;br /&gt;
#** Users can create chat rooms with an arbitrary room name(5 points)&lt;br /&gt;
#** Users can join an arbitrary chat room (5 points)&lt;br /&gt;
#** The chat room displays all users currently in the room (5 points)&lt;br /&gt;
#** A private room can be created that is password protected (5 points)&lt;br /&gt;
#** Creators of chat rooms can temporarily kick others out of the room (3 points)&lt;br /&gt;
#** Creators of chat rooms can permanently ban users from joining that particular room (2 points)&lt;br /&gt;
#* '''''Messaging (5 Points):'''''&lt;br /&gt;
#** A user's message shows their username and is sent to everyone in the room (1 point)&lt;br /&gt;
#** Users can send private messages to another user in the same room (4 points)&lt;br /&gt;
#* '''''Best Practices (5 Points):'''''&lt;br /&gt;
#** Code is well formatted and easy to read, with proper commenting (2 points)&lt;br /&gt;
#** Code passes HTML validation (2 points)&lt;br /&gt;
#** node_modules folder is ignored by version control (1 points)&lt;br /&gt;
#* '''''Usability (5 Points):'''''&lt;br /&gt;
#** Communicating with others and joining rooms is easy and intuitive (4 points)&lt;br /&gt;
#** Site is visually appealing (1 point)&lt;br /&gt;
#* '''Creative Portion (10 Points)'''&lt;br /&gt;
&amp;lt;!-- #** Make sure to create a README.md file pointing to your server --&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 6]]&lt;br /&gt;
[[Category:Modules]]&lt;/div&gt;</summary>
		<author><name>Alex</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=AJAX_and_JSON&amp;diff=2555</id>
		<title>AJAX and JSON</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=AJAX_and_JSON&amp;diff=2555"/>
		<updated>2018-04-30T21:42:46Z</updated>

		<summary type="html">&lt;p&gt;Alex: /* Logging In a User */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Asynchronous Javascript And XML, or '''''AJAX''''', is a group of related web development techniques, standards, and technologies used on the client (web browser) side of the standard web server-client communication model.&lt;br /&gt;
&lt;br /&gt;
Here's the general concept: JavaScript is used to send requests to the web server in the background and retrieve data, without the need to refresh the page.  The result: dynamic, fast, user-friendly web pages.&lt;br /&gt;
&lt;br /&gt;
The requests are performed ''asynchronously'': this means that the end user can continue interacting with your web page while the server data is being loaded.&lt;br /&gt;
&lt;br /&gt;
The key idea is that a large fraction of the work happens at the web browser, and larger requests happen behind the scenes, keeping waiting times for data to come back over the network to a minimum.  AJAX is generally also associated with higher-level APIs and libraries that aid in producing cleaner user interfaces for web applications.&lt;br /&gt;
&lt;br /&gt;
== The XMLHttpRequest Object ==&lt;br /&gt;
&lt;br /&gt;
The JavaScript specification defines the '''XMLHttpRequest''' object (sometimes abbreviated as '''XHR'''), which is used to exchange data with the web servers without needing to reload the entire web page in the browser.&lt;br /&gt;
&lt;br /&gt;
=== Initializing an XMLHttpRequest Object ===&lt;br /&gt;
&lt;br /&gt;
As stated above, the XMLHttpRequest object handles communication with the web servers.  To use it, you must first initialize a variable to be an instance of the '''XMLHttpRequest''' &amp;quot;class&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var xmlHttp = new XMLHttpRequest();&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Next, use your XMLHttpRequest instance to open a connection to your server.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
xmlHttp.open(&amp;quot;METHOD&amp;quot;, &amp;quot;URL_OF_SERVER_SCRIPT&amp;quot;, ASYNCRONOUS_FLAG);&lt;br /&gt;
// METHOD: either GET or POST.&lt;br /&gt;
// URL_OF_SERVER_SCRIPT: the path to your server-side script relative to the current page.  For example, process_ajax.php&lt;br /&gt;
// ASYNCRONOUS_FLAG: Should be true in order to perform the request asynchronously.  (Having a value of false will freeze the browser until the request is completed.)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{DoctypeTV&lt;br /&gt;
|youtube_id=isrqZQPE2eQ&lt;br /&gt;
|time=3m51s&lt;br /&gt;
|desc=Explaining the Cross-Site Policy in AJAX&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
'''Note:''' For security reasons, you cannot perform AJAX requests to other domains, unless that domain has a special security policy set up to enable such requests.&lt;br /&gt;
&lt;br /&gt;
=== Sending Data ===&lt;br /&gt;
&lt;br /&gt;
==== GET Data ====&lt;br /&gt;
&lt;br /&gt;
To send GET data, append the information to the end of the URL_OF_SERVER_SCRIPT, as you would normally do, and then call xmlHttp.send(), passing ''null'' as the parameter:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var xmlHttp = new XMLHttpRequest();&lt;br /&gt;
xmlHttp.open(&amp;quot;GET&amp;quot;, &amp;quot;process_ajax.php?var1=val1&amp;amp;var2=val2&amp;quot;, true);&lt;br /&gt;
xmlHttp.send(null);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== POST Data ====&lt;br /&gt;
&lt;br /&gt;
To send POST data, pass a URL-encoded string to xmlHttp.send().  You also need to change the MIME Type of the outgoing request.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var xmlHttp = new XMLHttpRequest();&lt;br /&gt;
xmlHttp.open(&amp;quot;POST&amp;quot;, &amp;quot;process_ajax.php&amp;quot;, true);&lt;br /&gt;
xmlHttp.setRequestHeader(&amp;quot;Content-Type&amp;quot;, &amp;quot;application/x-www-form-urlencoded&amp;quot;);&lt;br /&gt;
xmlHttp.send(&amp;quot;var1=val1&amp;amp;var2=val2&amp;quot;);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Listening for a Response ===&lt;br /&gt;
&lt;br /&gt;
XMLHttpRequest will fire an [[JavaScript#Events|event]] when the request has been completed.  We therefore need to use a '''[[JavaScript#Events|callback function]]''' in order to listen for the '''load''' event on the XMLHttpRequest object.&lt;br /&gt;
&lt;br /&gt;
The server's plain text response is available as the '''responseText''' property of your XMLHttpRequest instance, which is available in the '''target''' property of the event.  For example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var xmlHttp = new XMLHttpRequest();&lt;br /&gt;
xmlHttp.open(&amp;quot;GET&amp;quot;, &amp;quot;hello.txt&amp;quot;, true);&lt;br /&gt;
xmlHttp.addEventListener(&amp;quot;load&amp;quot;, ajaxCallback, false);&lt;br /&gt;
xmlHttp.send(null);&lt;br /&gt;
&lt;br /&gt;
// ...&lt;br /&gt;
&lt;br /&gt;
function ajaxCallback(event){&lt;br /&gt;
	alert( &amp;quot;Your file contains the text: &amp;quot; + event.target.responseText );&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Browser Support ====&lt;br /&gt;
&lt;br /&gt;
Many examples that you find when Googling for &amp;quot;AJAX&amp;quot; use the '''onreadystatechange''' property of the XMLHttpRequest instance to react on the completion of the request, rather than using an event listener.  This approach works, and it is required for comprehensive browser support, but it is no longer recommended for future use in modern web applications.  The implementation of XMLHttpRequest documented here (so-called &amp;quot;XHR level 2&amp;quot;) works in the following browsers:&lt;br /&gt;
* Firefox 3.5+ (Jun 2009)&lt;br /&gt;
* Safari 5+ (Jun 2010)&lt;br /&gt;
* Chrome 7+ (Sep 2010)&lt;br /&gt;
* Opera 12+ (May 2012)&lt;br /&gt;
* Internet Explorer 10+ (unreleased)&lt;br /&gt;
Together, browsers supporting XHR level 2 account [http://caniuse.com/xhr2 77% of the market] as of August 2013.&lt;br /&gt;
&lt;br /&gt;
=== Response Formats ===&lt;br /&gt;
&lt;br /&gt;
More often than not, a plaintext response form the server is not very helpful: you want to transmit more information than simply a single string of text.  There are two good options to get more information from a single AJAX request: '''XML''' (the original format, thus the ''X'' in ''AJAX'') and '''JSON'''.&lt;br /&gt;
&lt;br /&gt;
==== XML ====&lt;br /&gt;
&lt;br /&gt;
Your server can respond with an XML document (whence, ''XMLHttpRequest'').  An '''XML document''' uses syntax that is extremely close to HTML  For example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;xml&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;?xml version=&amp;quot;1.0&amp;quot; standalone=&amp;quot;yes&amp;quot; ?&amp;gt;&lt;br /&gt;
&amp;lt;note&amp;gt;&lt;br /&gt;
  &amp;lt;date year=&amp;quot;2013&amp;quot; month=&amp;quot;02&amp;quot; day=&amp;quot;14&amp;quot; /&amp;gt;&lt;br /&gt;
  &amp;lt;to&amp;gt;Sally&amp;lt;/to&amp;gt;&lt;br /&gt;
  &amp;lt;message&amp;gt;Happy Valentine's Day!&amp;lt;/message&amp;gt;&lt;br /&gt;
  &amp;lt;from&amp;gt;Your Secret Admirer&amp;lt;/from&amp;gt;&lt;br /&gt;
&amp;lt;/note&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Like HTML, XML has a DOM that can be traversed in JavaScript.&lt;br /&gt;
&lt;br /&gt;
If you make an AJAX request to a script generating an XML document, the root XML node is accessible in the '''responseXML''' property.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
function ajaxCallback(event){&lt;br /&gt;
	var xmlDocument = event.target.responseXML;&lt;br /&gt;
	&lt;br /&gt;
	alert(xmlDocument.getElementsByTagName(&amp;quot;to&amp;quot;)[0].textContent);  // Sally (in the case of the example XML above)&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== JSON ====&lt;br /&gt;
&lt;br /&gt;
JavaScript Object Notation, or '''JSON''', is a rising standard interface format because of its lightweight syntax that makes it especially useful for AJAX requests.&lt;br /&gt;
&lt;br /&gt;
The JSON syntax closely follows the syntax for [[JavaScript#Object Literals|object literals]].  For example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
{&lt;br /&gt;
   &amp;quot;apple&amp;quot;: {&lt;br /&gt;
      &amp;quot;color&amp;quot;: &amp;quot;red&amp;quot;,&lt;br /&gt;
      &amp;quot;flavor&amp;quot;: &amp;quot;sweet&amp;quot;&lt;br /&gt;
   },&lt;br /&gt;
   &amp;quot;lemon&amp;quot;: {&lt;br /&gt;
      &amp;quot;color&amp;quot;: &amp;quot;yellow&amp;quot;,&lt;br /&gt;
      &amp;quot;flavor&amp;quot;: &amp;quot;sour&amp;quot;&lt;br /&gt;
   }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Usually when JSON is transferred over the internet, it is condensed down to one line, like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
{&amp;quot;apple&amp;quot;:{&amp;quot;color&amp;quot;:&amp;quot;red&amp;quot;,&amp;quot;flavor&amp;quot;:&amp;quot;sweet&amp;quot;},&amp;quot;lemon&amp;quot;:{&amp;quot;color&amp;quot;:&amp;quot;yellow&amp;quot;,&amp;quot;flavor&amp;quot;:&amp;quot;sour&amp;quot;}}&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In JavaScript, you can convert a JSON string to an object using '''JSON.parse()'''.  For example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var jsonData = JSON.parse('{&amp;quot;apple&amp;quot;:{&amp;quot;color&amp;quot;:&amp;quot;red&amp;quot;,&amp;quot;flavor&amp;quot;:&amp;quot;sweet&amp;quot;},&amp;quot;lemon&amp;quot;:{&amp;quot;color&amp;quot;:&amp;quot;yellow&amp;quot;,&amp;quot;flavor&amp;quot;:&amp;quot;sour&amp;quot;}}');&lt;br /&gt;
&lt;br /&gt;
alert(jsonData.apple.color);  // red&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here's how to use it in conjunction with your AJAX response callback:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
function ajaxCallback(event){&lt;br /&gt;
	var jsonData = JSON.parse(event.target.responseText);&lt;br /&gt;
	&lt;br /&gt;
	alert(jsonData.lemon.flavor);  // sour (in the case of the example JSON above)&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here is a graphic to illustrate the JSON process.&lt;br /&gt;
&lt;br /&gt;
[[File:JSON-Flowchart.png‎]]&lt;br /&gt;
&lt;br /&gt;
== Examples ==&lt;br /&gt;
&lt;br /&gt;
=== Logging In a User ===&lt;br /&gt;
&lt;br /&gt;
Suppose you had the following PHP script:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;php&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;?php&lt;br /&gt;
// login_ajax.php&lt;br /&gt;
&lt;br /&gt;
header(&amp;quot;Content-Type: application/json&amp;quot;); // Since we are sending a JSON response here (not an HTML document), set the MIME Type to application/json&lt;br /&gt;
&lt;br /&gt;
$username = $_POST['username'];&lt;br /&gt;
$password = $_POST['password'];&lt;br /&gt;
&lt;br /&gt;
// Check to see if the username and password are valid.  (You learned how to do this in Module 3.)&lt;br /&gt;
&lt;br /&gt;
if( /* valid username and password */ ){&lt;br /&gt;
	session_start();&lt;br /&gt;
	$_SESSION['username'] = $username;&lt;br /&gt;
	$_SESSION['token'] = bin2hex(openssl_random_pseudo_bytes(32)); &lt;br /&gt;
&lt;br /&gt;
	echo json_encode(array(&lt;br /&gt;
		&amp;quot;success&amp;quot; =&amp;gt; true&lt;br /&gt;
	));&lt;br /&gt;
	exit;&lt;br /&gt;
}else{&lt;br /&gt;
	echo json_encode(array(&lt;br /&gt;
		&amp;quot;success&amp;quot; =&amp;gt; false,&lt;br /&gt;
		&amp;quot;message&amp;quot; =&amp;gt; &amp;quot;Incorrect Username or Password&amp;quot;&lt;br /&gt;
	));&lt;br /&gt;
	exit;&lt;br /&gt;
}&lt;br /&gt;
?&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Note:''' This example uses PHP's very handy '''json_encode()''' function to translate an associative array into a JSON object.  This means that you can access in JavaScript the same structure that you made in PHP!&lt;br /&gt;
&lt;br /&gt;
And suppose you had the following HTML content:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;input type=&amp;quot;text&amp;quot; id=&amp;quot;username&amp;quot; placeholder=&amp;quot;Username&amp;quot; /&amp;gt;&lt;br /&gt;
&amp;lt;input type=&amp;quot;password&amp;quot; id=&amp;quot;password&amp;quot; placeholder=&amp;quot;Password&amp;quot; /&amp;gt;&lt;br /&gt;
&amp;lt;button id=&amp;quot;login_btn&amp;quot;&amp;gt;Log In&amp;lt;/button&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;script type=&amp;quot;text/javascript&amp;quot; src=&amp;quot;ajax.js&amp;quot;&amp;gt;&amp;lt;/script&amp;gt; &amp;lt;!-- load the JavaScript file --&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You could use the following JavaScript code to prepare, send, and receive a request from the server to see if the user is logged in, without ever having to refresh the page.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// ajax.js&lt;br /&gt;
&lt;br /&gt;
function loginAjax(event) {&lt;br /&gt;
    const username = document.getElementById(&amp;quot;username&amp;quot;).value; // Get the username from the form&lt;br /&gt;
    const password = document.getElementById(&amp;quot;password&amp;quot;).value; // Get the password from the form&lt;br /&gt;
&lt;br /&gt;
    // Make a URL-encoded string for passing POST data:&lt;br /&gt;
    const data = { 'username': username, 'password': password };&lt;br /&gt;
&lt;br /&gt;
    fetch(&amp;quot;login_ajax.php&amp;quot;, {&lt;br /&gt;
            body: JSON.stringify(data),&lt;br /&gt;
            headers: { 'content-type': 'application/json' },&lt;br /&gt;
            method: 'POST'&lt;br /&gt;
        })&lt;br /&gt;
        .then(response =&amp;gt; response.json())&lt;br /&gt;
        .then(data =&amp;gt; console.log(data.success ? &amp;quot;You've been logged in!&amp;quot; : `You were not logged in ${data.message}`));&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
document.getElementById(&amp;quot;login_btn&amp;quot;).addEventListener(&amp;quot;click&amp;quot;, loginAjax, false); // Bind the AJAX call to button click&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Note:''' The above example uses an '''anonymous function''' (a function without a name that is declared in an attribute) as the callback.  If you are using a certain callback function only once in your program, this is a perfectly valid approach to reduce the amount of code you need to write.&lt;br /&gt;
&lt;br /&gt;
=== Loading Data from an XML File for Display in HTML ===&lt;br /&gt;
&lt;br /&gt;
Suppose you have a file '''note.xml''' that contains the following information:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;xml&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;?xml version=&amp;quot;1.0&amp;quot; standalone=&amp;quot;yes&amp;quot; ?&amp;gt;&lt;br /&gt;
&amp;lt;note&amp;gt;&lt;br /&gt;
  &amp;lt;date year=&amp;quot;2013&amp;quot; month=&amp;quot;02&amp;quot; day=&amp;quot;14&amp;quot; /&amp;gt;&lt;br /&gt;
  &amp;lt;to&amp;gt;Sally&amp;lt;/to&amp;gt;&lt;br /&gt;
  &amp;lt;message&amp;gt;Happy Valentine's Day!&amp;lt;/message&amp;gt;&lt;br /&gt;
  &amp;lt;from&amp;gt;Your Secret Admirer&amp;lt;/from&amp;gt;&lt;br /&gt;
&amp;lt;/note&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Further, suppose you had an HTML element with ID '''note''':&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;div id=&amp;quot;note&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You could load this XML file and then display it inside of your HTML document like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
function getNoteAjax(event){&lt;br /&gt;
	// The XMLHttpRequest is simple this time:&lt;br /&gt;
	var xmlHttp = new XMLHttpRequest();&lt;br /&gt;
	xmlHttp.open(&amp;quot;GET&amp;quot;, &amp;quot;note.xml&amp;quot;, true);&lt;br /&gt;
	xmlHttp.addEventListener(&amp;quot;load&amp;quot;, getNoteCallback, false);&lt;br /&gt;
	xmlHttp.send(null);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
function getNoteCallback(event){&lt;br /&gt;
	var htmlParent = document.getElementById(&amp;quot;note&amp;quot;); // Get the HTML element into which we want to write the note&lt;br /&gt;
	var xmlDocument = event.target.responseXML; // Get the XML root node from the response&lt;br /&gt;
	&lt;br /&gt;
	// Find the &amp;lt;date/&amp;gt; element from the XML response.  We expect only 1 such element, so we can call&lt;br /&gt;
	// xmlDocument.getElementsByTagName() and then get the first (and only) element in the array all in&lt;br /&gt;
	// one step.  This is called chaining.&lt;br /&gt;
	var xmlDateElement = xmlDocument.getElementsByTagName(&amp;quot;date&amp;quot;)[0];&lt;br /&gt;
	&lt;br /&gt;
	// Put together a YYYY-MM-DD type date into a string based on the attributes of the &amp;lt;date/&amp;gt; element.&lt;br /&gt;
	var dateString = xmlDateElement.getAttribute(&amp;quot;year&amp;quot;) + &amp;quot;-&amp;quot; + xmlDateElement.getAttribute(&amp;quot;month&amp;quot;)&lt;br /&gt;
		+ &amp;quot;-&amp;quot; + xmlDateElement.getAttribute(&amp;quot;day&amp;quot;);&lt;br /&gt;
	&lt;br /&gt;
	// Get the content of the &amp;lt;to&amp;gt;, &amp;lt;message&amp;gt;, and &amp;lt;from&amp;gt; tags.  Again, you can use a chain to do this in one line for each.&lt;br /&gt;
	var to = xmlDocument.getElementsByTagName(&amp;quot;to&amp;quot;)[0].textContent;&lt;br /&gt;
	var message = xmlDocument.getElementsByTagName(&amp;quot;message&amp;quot;)[0].textContent;&lt;br /&gt;
	var from = xmlDocument.getElementsByTagName(&amp;quot;from&amp;quot;)[0].textContent;&lt;br /&gt;
	&lt;br /&gt;
	// Make a &amp;lt;strong&amp;gt; tag, append the date string as its content, and then append it to the HTML element.&lt;br /&gt;
	var htmlDateObj = document.createElement(&amp;quot;strong&amp;quot;);&lt;br /&gt;
	htmlDateObj.appendChild(document.createTextNode(dateString));&lt;br /&gt;
	htmlParent.appendChild(htmlDateObj);&lt;br /&gt;
	&lt;br /&gt;
	// Make a &amp;lt;p&amp;gt; tag to contain the note.&lt;br /&gt;
	var htmlParagraphObj = document.createElement(&amp;quot;p&amp;quot;);&lt;br /&gt;
	htmlParagraphObj.appendChild(document.createTextNode(&amp;quot;Dear &amp;quot;+to+&amp;quot;,&amp;quot;)); // First append the greeting&lt;br /&gt;
	htmlParagraphObj.appendChild(document.createElement(&amp;quot;br&amp;quot;)); // Append a couple line feeds&lt;br /&gt;
	htmlParagraphObj.appendChild(document.createElement(&amp;quot;br&amp;quot;));&lt;br /&gt;
	htmlParagraphObj.appendChild(document.createTextNode(message)); // Write the message itself&lt;br /&gt;
	htmlParagraphObj.appendChild(document.createElement(&amp;quot;br&amp;quot;)); // Append a couple more line feeds&lt;br /&gt;
	htmlParagraphObj.appendChild(document.createElement(&amp;quot;br&amp;quot;));&lt;br /&gt;
	htmlParagraphObj.appendChild(document.createTextNode(&amp;quot;Love, &amp;quot;+from)); // Finally, append the salutation&lt;br /&gt;
	htmlParent.appendChild(htmlParagraphObj); // Append the newly engineered &amp;lt;p&amp;gt; to the HTML element.&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
document.addEventListener(&amp;quot;DOMContentLoaded&amp;quot;, getNoteAjax, false); // Bind the AJAX call to page load&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This example uses a lot of techniques documented in the [[JavaScript#Document Object Model]] section above.  The resulting DOM will be something like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;div id=&amp;quot;note&amp;quot;&amp;gt;&lt;br /&gt;
  &amp;lt;strong&amp;gt;2013-02-14&amp;lt;/strong&amp;gt;&lt;br /&gt;
  &amp;lt;p&amp;gt;Dear Sally,&amp;lt;br /&amp;gt;&amp;lt;br /&amp;gt;Happy Valentine's Day!&amp;lt;br /&amp;gt;&amp;lt;br /&amp;gt;Love, Your Secret Admirer&amp;lt;/p&amp;gt;&lt;br /&gt;
&amp;lt;/div&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If you think that this is a lot of code to produce a relatively simple output, you are not alone.  You will learn how to do this job in much fewer lines when you learn about [[Ext JS]].&lt;br /&gt;
&lt;br /&gt;
== Debugging AJAX and JSON ==&lt;br /&gt;
&lt;br /&gt;
It is helpful when building your application to look at the AJAX requests and responses as they happen in real time.  Fortunately, there are many tools to help.&lt;br /&gt;
&lt;br /&gt;
In your favorite web inspector (Chrome Dev Tools, Mozilla Dev Tools, Firebug, Dragonfly, and so on), go to the &amp;quot;Network&amp;quot; tab.  This is where you can see all assets loaded by the application: images, stylesheets, and, most importantly for us, AJAX files.  Some inspectors let you filter requests by type; for example, the Chrome inspector lets you click &amp;quot;XHR&amp;quot; to only show XMLHttpRequest (AJAX) requests.&lt;br /&gt;
&lt;br /&gt;
You can also view the JSON sent by your server.  Double-clicking the entries in the web inspector opens the source URL in a new tab.&lt;br /&gt;
&lt;br /&gt;
If you find minified JSON hard to read, we recommend that you install the JSONView browser extension or one of its close relatives:&lt;br /&gt;
* [https://addons.mozilla.org/en-us/firefox/addon/jsonview/ Firefox]&lt;br /&gt;
* [https://chrome.google.com/webstore/detail/jsonview/chklaanhfefbnpoihckbnefhakgolnmc?hl=en Chrome]&lt;br /&gt;
* [https://addons.opera.com/en/extensions/details/jsonviewer/ Opera]&lt;br /&gt;
* [https://github.com/rfletcher/safari-json-formatter Safari]&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 6]]&lt;/div&gt;</summary>
		<author><name>Alex</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=AJAX_and_JSON&amp;diff=2554</id>
		<title>AJAX and JSON</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=AJAX_and_JSON&amp;diff=2554"/>
		<updated>2018-04-30T21:41:03Z</updated>

		<summary type="html">&lt;p&gt;Alex: /* Examples */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Asynchronous Javascript And XML, or '''''AJAX''''', is a group of related web development techniques, standards, and technologies used on the client (web browser) side of the standard web server-client communication model.&lt;br /&gt;
&lt;br /&gt;
Here's the general concept: JavaScript is used to send requests to the web server in the background and retrieve data, without the need to refresh the page.  The result: dynamic, fast, user-friendly web pages.&lt;br /&gt;
&lt;br /&gt;
The requests are performed ''asynchronously'': this means that the end user can continue interacting with your web page while the server data is being loaded.&lt;br /&gt;
&lt;br /&gt;
The key idea is that a large fraction of the work happens at the web browser, and larger requests happen behind the scenes, keeping waiting times for data to come back over the network to a minimum.  AJAX is generally also associated with higher-level APIs and libraries that aid in producing cleaner user interfaces for web applications.&lt;br /&gt;
&lt;br /&gt;
== The XMLHttpRequest Object ==&lt;br /&gt;
&lt;br /&gt;
The JavaScript specification defines the '''XMLHttpRequest''' object (sometimes abbreviated as '''XHR'''), which is used to exchange data with the web servers without needing to reload the entire web page in the browser.&lt;br /&gt;
&lt;br /&gt;
=== Initializing an XMLHttpRequest Object ===&lt;br /&gt;
&lt;br /&gt;
As stated above, the XMLHttpRequest object handles communication with the web servers.  To use it, you must first initialize a variable to be an instance of the '''XMLHttpRequest''' &amp;quot;class&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var xmlHttp = new XMLHttpRequest();&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Next, use your XMLHttpRequest instance to open a connection to your server.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
xmlHttp.open(&amp;quot;METHOD&amp;quot;, &amp;quot;URL_OF_SERVER_SCRIPT&amp;quot;, ASYNCRONOUS_FLAG);&lt;br /&gt;
// METHOD: either GET or POST.&lt;br /&gt;
// URL_OF_SERVER_SCRIPT: the path to your server-side script relative to the current page.  For example, process_ajax.php&lt;br /&gt;
// ASYNCRONOUS_FLAG: Should be true in order to perform the request asynchronously.  (Having a value of false will freeze the browser until the request is completed.)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{DoctypeTV&lt;br /&gt;
|youtube_id=isrqZQPE2eQ&lt;br /&gt;
|time=3m51s&lt;br /&gt;
|desc=Explaining the Cross-Site Policy in AJAX&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
'''Note:''' For security reasons, you cannot perform AJAX requests to other domains, unless that domain has a special security policy set up to enable such requests.&lt;br /&gt;
&lt;br /&gt;
=== Sending Data ===&lt;br /&gt;
&lt;br /&gt;
==== GET Data ====&lt;br /&gt;
&lt;br /&gt;
To send GET data, append the information to the end of the URL_OF_SERVER_SCRIPT, as you would normally do, and then call xmlHttp.send(), passing ''null'' as the parameter:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var xmlHttp = new XMLHttpRequest();&lt;br /&gt;
xmlHttp.open(&amp;quot;GET&amp;quot;, &amp;quot;process_ajax.php?var1=val1&amp;amp;var2=val2&amp;quot;, true);&lt;br /&gt;
xmlHttp.send(null);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== POST Data ====&lt;br /&gt;
&lt;br /&gt;
To send POST data, pass a URL-encoded string to xmlHttp.send().  You also need to change the MIME Type of the outgoing request.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var xmlHttp = new XMLHttpRequest();&lt;br /&gt;
xmlHttp.open(&amp;quot;POST&amp;quot;, &amp;quot;process_ajax.php&amp;quot;, true);&lt;br /&gt;
xmlHttp.setRequestHeader(&amp;quot;Content-Type&amp;quot;, &amp;quot;application/x-www-form-urlencoded&amp;quot;);&lt;br /&gt;
xmlHttp.send(&amp;quot;var1=val1&amp;amp;var2=val2&amp;quot;);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Listening for a Response ===&lt;br /&gt;
&lt;br /&gt;
XMLHttpRequest will fire an [[JavaScript#Events|event]] when the request has been completed.  We therefore need to use a '''[[JavaScript#Events|callback function]]''' in order to listen for the '''load''' event on the XMLHttpRequest object.&lt;br /&gt;
&lt;br /&gt;
The server's plain text response is available as the '''responseText''' property of your XMLHttpRequest instance, which is available in the '''target''' property of the event.  For example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var xmlHttp = new XMLHttpRequest();&lt;br /&gt;
xmlHttp.open(&amp;quot;GET&amp;quot;, &amp;quot;hello.txt&amp;quot;, true);&lt;br /&gt;
xmlHttp.addEventListener(&amp;quot;load&amp;quot;, ajaxCallback, false);&lt;br /&gt;
xmlHttp.send(null);&lt;br /&gt;
&lt;br /&gt;
// ...&lt;br /&gt;
&lt;br /&gt;
function ajaxCallback(event){&lt;br /&gt;
	alert( &amp;quot;Your file contains the text: &amp;quot; + event.target.responseText );&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Browser Support ====&lt;br /&gt;
&lt;br /&gt;
Many examples that you find when Googling for &amp;quot;AJAX&amp;quot; use the '''onreadystatechange''' property of the XMLHttpRequest instance to react on the completion of the request, rather than using an event listener.  This approach works, and it is required for comprehensive browser support, but it is no longer recommended for future use in modern web applications.  The implementation of XMLHttpRequest documented here (so-called &amp;quot;XHR level 2&amp;quot;) works in the following browsers:&lt;br /&gt;
* Firefox 3.5+ (Jun 2009)&lt;br /&gt;
* Safari 5+ (Jun 2010)&lt;br /&gt;
* Chrome 7+ (Sep 2010)&lt;br /&gt;
* Opera 12+ (May 2012)&lt;br /&gt;
* Internet Explorer 10+ (unreleased)&lt;br /&gt;
Together, browsers supporting XHR level 2 account [http://caniuse.com/xhr2 77% of the market] as of August 2013.&lt;br /&gt;
&lt;br /&gt;
=== Response Formats ===&lt;br /&gt;
&lt;br /&gt;
More often than not, a plaintext response form the server is not very helpful: you want to transmit more information than simply a single string of text.  There are two good options to get more information from a single AJAX request: '''XML''' (the original format, thus the ''X'' in ''AJAX'') and '''JSON'''.&lt;br /&gt;
&lt;br /&gt;
==== XML ====&lt;br /&gt;
&lt;br /&gt;
Your server can respond with an XML document (whence, ''XMLHttpRequest'').  An '''XML document''' uses syntax that is extremely close to HTML  For example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;xml&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;?xml version=&amp;quot;1.0&amp;quot; standalone=&amp;quot;yes&amp;quot; ?&amp;gt;&lt;br /&gt;
&amp;lt;note&amp;gt;&lt;br /&gt;
  &amp;lt;date year=&amp;quot;2013&amp;quot; month=&amp;quot;02&amp;quot; day=&amp;quot;14&amp;quot; /&amp;gt;&lt;br /&gt;
  &amp;lt;to&amp;gt;Sally&amp;lt;/to&amp;gt;&lt;br /&gt;
  &amp;lt;message&amp;gt;Happy Valentine's Day!&amp;lt;/message&amp;gt;&lt;br /&gt;
  &amp;lt;from&amp;gt;Your Secret Admirer&amp;lt;/from&amp;gt;&lt;br /&gt;
&amp;lt;/note&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Like HTML, XML has a DOM that can be traversed in JavaScript.&lt;br /&gt;
&lt;br /&gt;
If you make an AJAX request to a script generating an XML document, the root XML node is accessible in the '''responseXML''' property.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
function ajaxCallback(event){&lt;br /&gt;
	var xmlDocument = event.target.responseXML;&lt;br /&gt;
	&lt;br /&gt;
	alert(xmlDocument.getElementsByTagName(&amp;quot;to&amp;quot;)[0].textContent);  // Sally (in the case of the example XML above)&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== JSON ====&lt;br /&gt;
&lt;br /&gt;
JavaScript Object Notation, or '''JSON''', is a rising standard interface format because of its lightweight syntax that makes it especially useful for AJAX requests.&lt;br /&gt;
&lt;br /&gt;
The JSON syntax closely follows the syntax for [[JavaScript#Object Literals|object literals]].  For example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
{&lt;br /&gt;
   &amp;quot;apple&amp;quot;: {&lt;br /&gt;
      &amp;quot;color&amp;quot;: &amp;quot;red&amp;quot;,&lt;br /&gt;
      &amp;quot;flavor&amp;quot;: &amp;quot;sweet&amp;quot;&lt;br /&gt;
   },&lt;br /&gt;
   &amp;quot;lemon&amp;quot;: {&lt;br /&gt;
      &amp;quot;color&amp;quot;: &amp;quot;yellow&amp;quot;,&lt;br /&gt;
      &amp;quot;flavor&amp;quot;: &amp;quot;sour&amp;quot;&lt;br /&gt;
   }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Usually when JSON is transferred over the internet, it is condensed down to one line, like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
{&amp;quot;apple&amp;quot;:{&amp;quot;color&amp;quot;:&amp;quot;red&amp;quot;,&amp;quot;flavor&amp;quot;:&amp;quot;sweet&amp;quot;},&amp;quot;lemon&amp;quot;:{&amp;quot;color&amp;quot;:&amp;quot;yellow&amp;quot;,&amp;quot;flavor&amp;quot;:&amp;quot;sour&amp;quot;}}&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In JavaScript, you can convert a JSON string to an object using '''JSON.parse()'''.  For example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var jsonData = JSON.parse('{&amp;quot;apple&amp;quot;:{&amp;quot;color&amp;quot;:&amp;quot;red&amp;quot;,&amp;quot;flavor&amp;quot;:&amp;quot;sweet&amp;quot;},&amp;quot;lemon&amp;quot;:{&amp;quot;color&amp;quot;:&amp;quot;yellow&amp;quot;,&amp;quot;flavor&amp;quot;:&amp;quot;sour&amp;quot;}}');&lt;br /&gt;
&lt;br /&gt;
alert(jsonData.apple.color);  // red&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here's how to use it in conjunction with your AJAX response callback:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
function ajaxCallback(event){&lt;br /&gt;
	var jsonData = JSON.parse(event.target.responseText);&lt;br /&gt;
	&lt;br /&gt;
	alert(jsonData.lemon.flavor);  // sour (in the case of the example JSON above)&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here is a graphic to illustrate the JSON process.&lt;br /&gt;
&lt;br /&gt;
[[File:JSON-Flowchart.png‎]]&lt;br /&gt;
&lt;br /&gt;
== Examples ==&lt;br /&gt;
&lt;br /&gt;
=== Logging In a User ===&lt;br /&gt;
&lt;br /&gt;
Suppose you had the following PHP script:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;php&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;?php&lt;br /&gt;
// login_ajax.php&lt;br /&gt;
&lt;br /&gt;
header(&amp;quot;Content-Type: application/json&amp;quot;); // Since we are sending a JSON response here (not an HTML document), set the MIME Type to application/json&lt;br /&gt;
&lt;br /&gt;
$username = $_POST['username'];&lt;br /&gt;
$password = $_POST['password'];&lt;br /&gt;
&lt;br /&gt;
// Check to see if the username and password are valid.  (You learned how to do this in Module 3.)&lt;br /&gt;
&lt;br /&gt;
if( /* valid username and password */ ){&lt;br /&gt;
	session_start();&lt;br /&gt;
	$_SESSION['username'] = $username;&lt;br /&gt;
	$_SESSION['token'] = bin2hex(openssl_random_pseudo_bytes(32)); &lt;br /&gt;
&lt;br /&gt;
	echo json_encode(array(&lt;br /&gt;
		&amp;quot;success&amp;quot; =&amp;gt; true&lt;br /&gt;
	));&lt;br /&gt;
	exit;&lt;br /&gt;
}else{&lt;br /&gt;
	echo json_encode(array(&lt;br /&gt;
		&amp;quot;success&amp;quot; =&amp;gt; false,&lt;br /&gt;
		&amp;quot;message&amp;quot; =&amp;gt; &amp;quot;Incorrect Username or Password&amp;quot;&lt;br /&gt;
	));&lt;br /&gt;
	exit;&lt;br /&gt;
}&lt;br /&gt;
?&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Note:''' This example uses PHP's very handy '''json_encode()''' function to translate an associative array into a JSON object.  This means that you can access in JavaScript the same structure that you made in PHP!&lt;br /&gt;
&lt;br /&gt;
And suppose you had the following HTML content:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;input type=&amp;quot;text&amp;quot; id=&amp;quot;username&amp;quot; placeholder=&amp;quot;Username&amp;quot; /&amp;gt;&lt;br /&gt;
&amp;lt;input type=&amp;quot;password&amp;quot; id=&amp;quot;password&amp;quot; placeholder=&amp;quot;Password&amp;quot; /&amp;gt;&lt;br /&gt;
&amp;lt;button id=&amp;quot;login_btn&amp;quot;&amp;gt;Log In&amp;lt;/button&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;script type=&amp;quot;text/javascript&amp;quot; src=&amp;quot;ajax.js&amp;quot;&amp;gt;&amp;lt;/script&amp;gt; &amp;lt;!-- load the JavaScript file --&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You could use the following JavaScript code to prepare, send, and receive a request from the server to see if the user is logged in, without ever having to refresh the page.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// ajax.js&lt;br /&gt;
&lt;br /&gt;
function loginAjax(event) {&lt;br /&gt;
    const username = document.getElementById(&amp;quot;username&amp;quot;).value; // Get the username from the form&lt;br /&gt;
    const password = document.getElementById(&amp;quot;password&amp;quot;).value; // Get the password from the form&lt;br /&gt;
&lt;br /&gt;
    // Make a URL-encoded string for passing POST data:&lt;br /&gt;
    const data = { username: username, password: password };&lt;br /&gt;
&lt;br /&gt;
    fetch(&amp;quot;login_ajax.php&amp;quot;, {&lt;br /&gt;
            body: JSON.stringify(data),&lt;br /&gt;
            headers: {&lt;br /&gt;
                'content-type': 'application/json'&lt;br /&gt;
            },&lt;br /&gt;
            method: 'POST'&lt;br /&gt;
        })&lt;br /&gt;
        .then(response =&amp;gt; response.json())&lt;br /&gt;
        .then(data =&amp;gt; console.log(data.success ? &amp;quot;You've been logged in!&amp;quot; : `You were not logged in ${data.message}`)&lt;br /&gt;
&lt;br /&gt;
        }&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
document.getElementById(&amp;quot;login_btn&amp;quot;).addEventListener(&amp;quot;click&amp;quot;, loginAjax, false); // Bind the AJAX call to button click&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Note:''' The above example uses an '''anonymous function''' (a function without a name that is declared in an attribute) as the callback.  If you are using a certain callback function only once in your program, this is a perfectly valid approach to reduce the amount of code you need to write.&lt;br /&gt;
&lt;br /&gt;
=== Loading Data from an XML File for Display in HTML ===&lt;br /&gt;
&lt;br /&gt;
Suppose you have a file '''note.xml''' that contains the following information:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;xml&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;?xml version=&amp;quot;1.0&amp;quot; standalone=&amp;quot;yes&amp;quot; ?&amp;gt;&lt;br /&gt;
&amp;lt;note&amp;gt;&lt;br /&gt;
  &amp;lt;date year=&amp;quot;2013&amp;quot; month=&amp;quot;02&amp;quot; day=&amp;quot;14&amp;quot; /&amp;gt;&lt;br /&gt;
  &amp;lt;to&amp;gt;Sally&amp;lt;/to&amp;gt;&lt;br /&gt;
  &amp;lt;message&amp;gt;Happy Valentine's Day!&amp;lt;/message&amp;gt;&lt;br /&gt;
  &amp;lt;from&amp;gt;Your Secret Admirer&amp;lt;/from&amp;gt;&lt;br /&gt;
&amp;lt;/note&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Further, suppose you had an HTML element with ID '''note''':&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;div id=&amp;quot;note&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You could load this XML file and then display it inside of your HTML document like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
function getNoteAjax(event){&lt;br /&gt;
	// The XMLHttpRequest is simple this time:&lt;br /&gt;
	var xmlHttp = new XMLHttpRequest();&lt;br /&gt;
	xmlHttp.open(&amp;quot;GET&amp;quot;, &amp;quot;note.xml&amp;quot;, true);&lt;br /&gt;
	xmlHttp.addEventListener(&amp;quot;load&amp;quot;, getNoteCallback, false);&lt;br /&gt;
	xmlHttp.send(null);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
function getNoteCallback(event){&lt;br /&gt;
	var htmlParent = document.getElementById(&amp;quot;note&amp;quot;); // Get the HTML element into which we want to write the note&lt;br /&gt;
	var xmlDocument = event.target.responseXML; // Get the XML root node from the response&lt;br /&gt;
	&lt;br /&gt;
	// Find the &amp;lt;date/&amp;gt; element from the XML response.  We expect only 1 such element, so we can call&lt;br /&gt;
	// xmlDocument.getElementsByTagName() and then get the first (and only) element in the array all in&lt;br /&gt;
	// one step.  This is called chaining.&lt;br /&gt;
	var xmlDateElement = xmlDocument.getElementsByTagName(&amp;quot;date&amp;quot;)[0];&lt;br /&gt;
	&lt;br /&gt;
	// Put together a YYYY-MM-DD type date into a string based on the attributes of the &amp;lt;date/&amp;gt; element.&lt;br /&gt;
	var dateString = xmlDateElement.getAttribute(&amp;quot;year&amp;quot;) + &amp;quot;-&amp;quot; + xmlDateElement.getAttribute(&amp;quot;month&amp;quot;)&lt;br /&gt;
		+ &amp;quot;-&amp;quot; + xmlDateElement.getAttribute(&amp;quot;day&amp;quot;);&lt;br /&gt;
	&lt;br /&gt;
	// Get the content of the &amp;lt;to&amp;gt;, &amp;lt;message&amp;gt;, and &amp;lt;from&amp;gt; tags.  Again, you can use a chain to do this in one line for each.&lt;br /&gt;
	var to = xmlDocument.getElementsByTagName(&amp;quot;to&amp;quot;)[0].textContent;&lt;br /&gt;
	var message = xmlDocument.getElementsByTagName(&amp;quot;message&amp;quot;)[0].textContent;&lt;br /&gt;
	var from = xmlDocument.getElementsByTagName(&amp;quot;from&amp;quot;)[0].textContent;&lt;br /&gt;
	&lt;br /&gt;
	// Make a &amp;lt;strong&amp;gt; tag, append the date string as its content, and then append it to the HTML element.&lt;br /&gt;
	var htmlDateObj = document.createElement(&amp;quot;strong&amp;quot;);&lt;br /&gt;
	htmlDateObj.appendChild(document.createTextNode(dateString));&lt;br /&gt;
	htmlParent.appendChild(htmlDateObj);&lt;br /&gt;
	&lt;br /&gt;
	// Make a &amp;lt;p&amp;gt; tag to contain the note.&lt;br /&gt;
	var htmlParagraphObj = document.createElement(&amp;quot;p&amp;quot;);&lt;br /&gt;
	htmlParagraphObj.appendChild(document.createTextNode(&amp;quot;Dear &amp;quot;+to+&amp;quot;,&amp;quot;)); // First append the greeting&lt;br /&gt;
	htmlParagraphObj.appendChild(document.createElement(&amp;quot;br&amp;quot;)); // Append a couple line feeds&lt;br /&gt;
	htmlParagraphObj.appendChild(document.createElement(&amp;quot;br&amp;quot;));&lt;br /&gt;
	htmlParagraphObj.appendChild(document.createTextNode(message)); // Write the message itself&lt;br /&gt;
	htmlParagraphObj.appendChild(document.createElement(&amp;quot;br&amp;quot;)); // Append a couple more line feeds&lt;br /&gt;
	htmlParagraphObj.appendChild(document.createElement(&amp;quot;br&amp;quot;));&lt;br /&gt;
	htmlParagraphObj.appendChild(document.createTextNode(&amp;quot;Love, &amp;quot;+from)); // Finally, append the salutation&lt;br /&gt;
	htmlParent.appendChild(htmlParagraphObj); // Append the newly engineered &amp;lt;p&amp;gt; to the HTML element.&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
document.addEventListener(&amp;quot;DOMContentLoaded&amp;quot;, getNoteAjax, false); // Bind the AJAX call to page load&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This example uses a lot of techniques documented in the [[JavaScript#Document Object Model]] section above.  The resulting DOM will be something like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;div id=&amp;quot;note&amp;quot;&amp;gt;&lt;br /&gt;
  &amp;lt;strong&amp;gt;2013-02-14&amp;lt;/strong&amp;gt;&lt;br /&gt;
  &amp;lt;p&amp;gt;Dear Sally,&amp;lt;br /&amp;gt;&amp;lt;br /&amp;gt;Happy Valentine's Day!&amp;lt;br /&amp;gt;&amp;lt;br /&amp;gt;Love, Your Secret Admirer&amp;lt;/p&amp;gt;&lt;br /&gt;
&amp;lt;/div&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If you think that this is a lot of code to produce a relatively simple output, you are not alone.  You will learn how to do this job in much fewer lines when you learn about [[Ext JS]].&lt;br /&gt;
&lt;br /&gt;
== Debugging AJAX and JSON ==&lt;br /&gt;
&lt;br /&gt;
It is helpful when building your application to look at the AJAX requests and responses as they happen in real time.  Fortunately, there are many tools to help.&lt;br /&gt;
&lt;br /&gt;
In your favorite web inspector (Chrome Dev Tools, Mozilla Dev Tools, Firebug, Dragonfly, and so on), go to the &amp;quot;Network&amp;quot; tab.  This is where you can see all assets loaded by the application: images, stylesheets, and, most importantly for us, AJAX files.  Some inspectors let you filter requests by type; for example, the Chrome inspector lets you click &amp;quot;XHR&amp;quot; to only show XMLHttpRequest (AJAX) requests.&lt;br /&gt;
&lt;br /&gt;
You can also view the JSON sent by your server.  Double-clicking the entries in the web inspector opens the source URL in a new tab.&lt;br /&gt;
&lt;br /&gt;
If you find minified JSON hard to read, we recommend that you install the JSONView browser extension or one of its close relatives:&lt;br /&gt;
* [https://addons.mozilla.org/en-us/firefox/addon/jsonview/ Firefox]&lt;br /&gt;
* [https://chrome.google.com/webstore/detail/jsonview/chklaanhfefbnpoihckbnefhakgolnmc?hl=en Chrome]&lt;br /&gt;
* [https://addons.opera.com/en/extensions/details/jsonviewer/ Opera]&lt;br /&gt;
* [https://github.com/rfletcher/safari-json-formatter Safari]&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 6]]&lt;/div&gt;</summary>
		<author><name>Alex</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=AJAX_and_JSON&amp;diff=2553</id>
		<title>AJAX and JSON</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=AJAX_and_JSON&amp;diff=2553"/>
		<updated>2018-04-30T21:38:01Z</updated>

		<summary type="html">&lt;p&gt;Alex: /* Logging In a User */  Added fetch&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Asynchronous Javascript And XML, or '''''AJAX''''', is a group of related web development techniques, standards, and technologies used on the client (web browser) side of the standard web server-client communication model.&lt;br /&gt;
&lt;br /&gt;
Here's the general concept: JavaScript is used to send requests to the web server in the background and retrieve data, without the need to refresh the page.  The result: dynamic, fast, user-friendly web pages.&lt;br /&gt;
&lt;br /&gt;
The requests are performed ''asynchronously'': this means that the end user can continue interacting with your web page while the server data is being loaded.&lt;br /&gt;
&lt;br /&gt;
The key idea is that a large fraction of the work happens at the web browser, and larger requests happen behind the scenes, keeping waiting times for data to come back over the network to a minimum.  AJAX is generally also associated with higher-level APIs and libraries that aid in producing cleaner user interfaces for web applications.&lt;br /&gt;
&lt;br /&gt;
== The XMLHttpRequest Object ==&lt;br /&gt;
&lt;br /&gt;
The JavaScript specification defines the '''XMLHttpRequest''' object (sometimes abbreviated as '''XHR'''), which is used to exchange data with the web servers without needing to reload the entire web page in the browser.&lt;br /&gt;
&lt;br /&gt;
=== Initializing an XMLHttpRequest Object ===&lt;br /&gt;
&lt;br /&gt;
As stated above, the XMLHttpRequest object handles communication with the web servers.  To use it, you must first initialize a variable to be an instance of the '''XMLHttpRequest''' &amp;quot;class&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var xmlHttp = new XMLHttpRequest();&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Next, use your XMLHttpRequest instance to open a connection to your server.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
xmlHttp.open(&amp;quot;METHOD&amp;quot;, &amp;quot;URL_OF_SERVER_SCRIPT&amp;quot;, ASYNCRONOUS_FLAG);&lt;br /&gt;
// METHOD: either GET or POST.&lt;br /&gt;
// URL_OF_SERVER_SCRIPT: the path to your server-side script relative to the current page.  For example, process_ajax.php&lt;br /&gt;
// ASYNCRONOUS_FLAG: Should be true in order to perform the request asynchronously.  (Having a value of false will freeze the browser until the request is completed.)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{DoctypeTV&lt;br /&gt;
|youtube_id=isrqZQPE2eQ&lt;br /&gt;
|time=3m51s&lt;br /&gt;
|desc=Explaining the Cross-Site Policy in AJAX&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
'''Note:''' For security reasons, you cannot perform AJAX requests to other domains, unless that domain has a special security policy set up to enable such requests.&lt;br /&gt;
&lt;br /&gt;
=== Sending Data ===&lt;br /&gt;
&lt;br /&gt;
==== GET Data ====&lt;br /&gt;
&lt;br /&gt;
To send GET data, append the information to the end of the URL_OF_SERVER_SCRIPT, as you would normally do, and then call xmlHttp.send(), passing ''null'' as the parameter:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var xmlHttp = new XMLHttpRequest();&lt;br /&gt;
xmlHttp.open(&amp;quot;GET&amp;quot;, &amp;quot;process_ajax.php?var1=val1&amp;amp;var2=val2&amp;quot;, true);&lt;br /&gt;
xmlHttp.send(null);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== POST Data ====&lt;br /&gt;
&lt;br /&gt;
To send POST data, pass a URL-encoded string to xmlHttp.send().  You also need to change the MIME Type of the outgoing request.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var xmlHttp = new XMLHttpRequest();&lt;br /&gt;
xmlHttp.open(&amp;quot;POST&amp;quot;, &amp;quot;process_ajax.php&amp;quot;, true);&lt;br /&gt;
xmlHttp.setRequestHeader(&amp;quot;Content-Type&amp;quot;, &amp;quot;application/x-www-form-urlencoded&amp;quot;);&lt;br /&gt;
xmlHttp.send(&amp;quot;var1=val1&amp;amp;var2=val2&amp;quot;);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Listening for a Response ===&lt;br /&gt;
&lt;br /&gt;
XMLHttpRequest will fire an [[JavaScript#Events|event]] when the request has been completed.  We therefore need to use a '''[[JavaScript#Events|callback function]]''' in order to listen for the '''load''' event on the XMLHttpRequest object.&lt;br /&gt;
&lt;br /&gt;
The server's plain text response is available as the '''responseText''' property of your XMLHttpRequest instance, which is available in the '''target''' property of the event.  For example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var xmlHttp = new XMLHttpRequest();&lt;br /&gt;
xmlHttp.open(&amp;quot;GET&amp;quot;, &amp;quot;hello.txt&amp;quot;, true);&lt;br /&gt;
xmlHttp.addEventListener(&amp;quot;load&amp;quot;, ajaxCallback, false);&lt;br /&gt;
xmlHttp.send(null);&lt;br /&gt;
&lt;br /&gt;
// ...&lt;br /&gt;
&lt;br /&gt;
function ajaxCallback(event){&lt;br /&gt;
	alert( &amp;quot;Your file contains the text: &amp;quot; + event.target.responseText );&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Browser Support ====&lt;br /&gt;
&lt;br /&gt;
Many examples that you find when Googling for &amp;quot;AJAX&amp;quot; use the '''onreadystatechange''' property of the XMLHttpRequest instance to react on the completion of the request, rather than using an event listener.  This approach works, and it is required for comprehensive browser support, but it is no longer recommended for future use in modern web applications.  The implementation of XMLHttpRequest documented here (so-called &amp;quot;XHR level 2&amp;quot;) works in the following browsers:&lt;br /&gt;
* Firefox 3.5+ (Jun 2009)&lt;br /&gt;
* Safari 5+ (Jun 2010)&lt;br /&gt;
* Chrome 7+ (Sep 2010)&lt;br /&gt;
* Opera 12+ (May 2012)&lt;br /&gt;
* Internet Explorer 10+ (unreleased)&lt;br /&gt;
Together, browsers supporting XHR level 2 account [http://caniuse.com/xhr2 77% of the market] as of August 2013.&lt;br /&gt;
&lt;br /&gt;
=== Response Formats ===&lt;br /&gt;
&lt;br /&gt;
More often than not, a plaintext response form the server is not very helpful: you want to transmit more information than simply a single string of text.  There are two good options to get more information from a single AJAX request: '''XML''' (the original format, thus the ''X'' in ''AJAX'') and '''JSON'''.&lt;br /&gt;
&lt;br /&gt;
==== XML ====&lt;br /&gt;
&lt;br /&gt;
Your server can respond with an XML document (whence, ''XMLHttpRequest'').  An '''XML document''' uses syntax that is extremely close to HTML  For example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;xml&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;?xml version=&amp;quot;1.0&amp;quot; standalone=&amp;quot;yes&amp;quot; ?&amp;gt;&lt;br /&gt;
&amp;lt;note&amp;gt;&lt;br /&gt;
  &amp;lt;date year=&amp;quot;2013&amp;quot; month=&amp;quot;02&amp;quot; day=&amp;quot;14&amp;quot; /&amp;gt;&lt;br /&gt;
  &amp;lt;to&amp;gt;Sally&amp;lt;/to&amp;gt;&lt;br /&gt;
  &amp;lt;message&amp;gt;Happy Valentine's Day!&amp;lt;/message&amp;gt;&lt;br /&gt;
  &amp;lt;from&amp;gt;Your Secret Admirer&amp;lt;/from&amp;gt;&lt;br /&gt;
&amp;lt;/note&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Like HTML, XML has a DOM that can be traversed in JavaScript.&lt;br /&gt;
&lt;br /&gt;
If you make an AJAX request to a script generating an XML document, the root XML node is accessible in the '''responseXML''' property.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
function ajaxCallback(event){&lt;br /&gt;
	var xmlDocument = event.target.responseXML;&lt;br /&gt;
	&lt;br /&gt;
	alert(xmlDocument.getElementsByTagName(&amp;quot;to&amp;quot;)[0].textContent);  // Sally (in the case of the example XML above)&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== JSON ====&lt;br /&gt;
&lt;br /&gt;
JavaScript Object Notation, or '''JSON''', is a rising standard interface format because of its lightweight syntax that makes it especially useful for AJAX requests.&lt;br /&gt;
&lt;br /&gt;
The JSON syntax closely follows the syntax for [[JavaScript#Object Literals|object literals]].  For example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
{&lt;br /&gt;
   &amp;quot;apple&amp;quot;: {&lt;br /&gt;
      &amp;quot;color&amp;quot;: &amp;quot;red&amp;quot;,&lt;br /&gt;
      &amp;quot;flavor&amp;quot;: &amp;quot;sweet&amp;quot;&lt;br /&gt;
   },&lt;br /&gt;
   &amp;quot;lemon&amp;quot;: {&lt;br /&gt;
      &amp;quot;color&amp;quot;: &amp;quot;yellow&amp;quot;,&lt;br /&gt;
      &amp;quot;flavor&amp;quot;: &amp;quot;sour&amp;quot;&lt;br /&gt;
   }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Usually when JSON is transferred over the internet, it is condensed down to one line, like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
{&amp;quot;apple&amp;quot;:{&amp;quot;color&amp;quot;:&amp;quot;red&amp;quot;,&amp;quot;flavor&amp;quot;:&amp;quot;sweet&amp;quot;},&amp;quot;lemon&amp;quot;:{&amp;quot;color&amp;quot;:&amp;quot;yellow&amp;quot;,&amp;quot;flavor&amp;quot;:&amp;quot;sour&amp;quot;}}&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In JavaScript, you can convert a JSON string to an object using '''JSON.parse()'''.  For example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var jsonData = JSON.parse('{&amp;quot;apple&amp;quot;:{&amp;quot;color&amp;quot;:&amp;quot;red&amp;quot;,&amp;quot;flavor&amp;quot;:&amp;quot;sweet&amp;quot;},&amp;quot;lemon&amp;quot;:{&amp;quot;color&amp;quot;:&amp;quot;yellow&amp;quot;,&amp;quot;flavor&amp;quot;:&amp;quot;sour&amp;quot;}}');&lt;br /&gt;
&lt;br /&gt;
alert(jsonData.apple.color);  // red&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here's how to use it in conjunction with your AJAX response callback:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
function ajaxCallback(event){&lt;br /&gt;
	var jsonData = JSON.parse(event.target.responseText);&lt;br /&gt;
	&lt;br /&gt;
	alert(jsonData.lemon.flavor);  // sour (in the case of the example JSON above)&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here is a graphic to illustrate the JSON process.&lt;br /&gt;
&lt;br /&gt;
[[File:JSON-Flowchart.png‎]]&lt;br /&gt;
&lt;br /&gt;
== Examples ==&lt;br /&gt;
&lt;br /&gt;
=== Logging In a User ===&lt;br /&gt;
&lt;br /&gt;
Suppose you had the following PHP script:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;php&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;?php&lt;br /&gt;
// login_ajax.php&lt;br /&gt;
&lt;br /&gt;
header(&amp;quot;Content-Type: application/json&amp;quot;); // Since we are sending a JSON response here (not an HTML document), set the MIME Type to application/json&lt;br /&gt;
&lt;br /&gt;
$username = $_POST['username'];&lt;br /&gt;
$password = $_POST['password'];&lt;br /&gt;
&lt;br /&gt;
// Check to see if the username and password are valid.  (You learned how to do this in Module 3.)&lt;br /&gt;
&lt;br /&gt;
if( /* valid username and password */ ){&lt;br /&gt;
	session_start();&lt;br /&gt;
	$_SESSION['username'] = $username;&lt;br /&gt;
	$_SESSION['token'] = bin2hex(openssl_random_pseudo_bytes(32)); &lt;br /&gt;
&lt;br /&gt;
	echo json_encode(array(&lt;br /&gt;
		&amp;quot;success&amp;quot; =&amp;gt; true&lt;br /&gt;
	));&lt;br /&gt;
	exit;&lt;br /&gt;
}else{&lt;br /&gt;
	echo json_encode(array(&lt;br /&gt;
		&amp;quot;success&amp;quot; =&amp;gt; false,&lt;br /&gt;
		&amp;quot;message&amp;quot; =&amp;gt; &amp;quot;Incorrect Username or Password&amp;quot;&lt;br /&gt;
	));&lt;br /&gt;
	exit;&lt;br /&gt;
}&lt;br /&gt;
?&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Note:''' This example uses PHP's very handy '''json_encode()''' function to translate an associative array into a JSON object.  This means that you can access in JavaScript the same structure that you made in PHP!&lt;br /&gt;
&lt;br /&gt;
And suppose you had the following HTML content:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;input type=&amp;quot;text&amp;quot; id=&amp;quot;username&amp;quot; placeholder=&amp;quot;Username&amp;quot; /&amp;gt;&lt;br /&gt;
&amp;lt;input type=&amp;quot;password&amp;quot; id=&amp;quot;password&amp;quot; placeholder=&amp;quot;Password&amp;quot; /&amp;gt;&lt;br /&gt;
&amp;lt;button id=&amp;quot;login_btn&amp;quot;&amp;gt;Log In&amp;lt;/button&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;script type=&amp;quot;text/javascript&amp;quot; src=&amp;quot;ajax.js&amp;quot;&amp;gt;&amp;lt;/script&amp;gt; &amp;lt;!-- load the JavaScript file --&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You could use the following JavaScript code to prepare, send, and receive a request from the server to see if the user is logged in, without ever having to refresh the page.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// ajax.js&lt;br /&gt;
&lt;br /&gt;
function loginAjax(event){&lt;br /&gt;
	const username = document.getElementById(&amp;quot;username&amp;quot;).value; // Get the username from the form&lt;br /&gt;
	const password = document.getElementById(&amp;quot;password&amp;quot;).value; // Get the password from the form&lt;br /&gt;
&lt;br /&gt;
	// Make a URL-encoded string for passing POST data:&lt;br /&gt;
        const data = {username: username, password: password};&lt;br /&gt;
	&lt;br /&gt;
	fetch(&amp;quot;login_ajax.php&amp;quot;, {&lt;br /&gt;
               body: JSON.stringify(data),&lt;br /&gt;
               headers: {&lt;br /&gt;
                   'content-type': 'application/json'&lt;br /&gt;
               },&lt;br /&gt;
               method: 'POST'&lt;br /&gt;
        })&lt;br /&gt;
        .then(response =&amp;gt; response.json())&lt;br /&gt;
        .then(data =&amp;gt; console.log(data.success ? &amp;quot;You've been logged in!&amp;quot; : `You were not logged in ${data.message}`)&lt;br /&gt;
        &lt;br /&gt;
}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
document.getElementById(&amp;quot;login_btn&amp;quot;).addEventListener(&amp;quot;click&amp;quot;, loginAjax, false); // Bind the AJAX call to button click&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Note:''' The above example uses an '''anonymous function''' (a function without a name that is declared in an attribute) as the callback.  If you are using a certain callback function only once in your program, this is a perfectly valid approach to reduce the amount of code you need to write.&lt;br /&gt;
&lt;br /&gt;
=== Loading Data from an XML File for Display in HTML ===&lt;br /&gt;
&lt;br /&gt;
Suppose you have a file '''note.xml''' that contains the following information:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;xml&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;?xml version=&amp;quot;1.0&amp;quot; standalone=&amp;quot;yes&amp;quot; ?&amp;gt;&lt;br /&gt;
&amp;lt;note&amp;gt;&lt;br /&gt;
  &amp;lt;date year=&amp;quot;2013&amp;quot; month=&amp;quot;02&amp;quot; day=&amp;quot;14&amp;quot; /&amp;gt;&lt;br /&gt;
  &amp;lt;to&amp;gt;Sally&amp;lt;/to&amp;gt;&lt;br /&gt;
  &amp;lt;message&amp;gt;Happy Valentine's Day!&amp;lt;/message&amp;gt;&lt;br /&gt;
  &amp;lt;from&amp;gt;Your Secret Admirer&amp;lt;/from&amp;gt;&lt;br /&gt;
&amp;lt;/note&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Further, suppose you had an HTML element with ID '''note''':&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;div id=&amp;quot;note&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You could load this XML file and then display it inside of your HTML document like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
function getNoteAjax(event){&lt;br /&gt;
	// The XMLHttpRequest is simple this time:&lt;br /&gt;
	var xmlHttp = new XMLHttpRequest();&lt;br /&gt;
	xmlHttp.open(&amp;quot;GET&amp;quot;, &amp;quot;note.xml&amp;quot;, true);&lt;br /&gt;
	xmlHttp.addEventListener(&amp;quot;load&amp;quot;, getNoteCallback, false);&lt;br /&gt;
	xmlHttp.send(null);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
function getNoteCallback(event){&lt;br /&gt;
	var htmlParent = document.getElementById(&amp;quot;note&amp;quot;); // Get the HTML element into which we want to write the note&lt;br /&gt;
	var xmlDocument = event.target.responseXML; // Get the XML root node from the response&lt;br /&gt;
	&lt;br /&gt;
	// Find the &amp;lt;date/&amp;gt; element from the XML response.  We expect only 1 such element, so we can call&lt;br /&gt;
	// xmlDocument.getElementsByTagName() and then get the first (and only) element in the array all in&lt;br /&gt;
	// one step.  This is called chaining.&lt;br /&gt;
	var xmlDateElement = xmlDocument.getElementsByTagName(&amp;quot;date&amp;quot;)[0];&lt;br /&gt;
	&lt;br /&gt;
	// Put together a YYYY-MM-DD type date into a string based on the attributes of the &amp;lt;date/&amp;gt; element.&lt;br /&gt;
	var dateString = xmlDateElement.getAttribute(&amp;quot;year&amp;quot;) + &amp;quot;-&amp;quot; + xmlDateElement.getAttribute(&amp;quot;month&amp;quot;)&lt;br /&gt;
		+ &amp;quot;-&amp;quot; + xmlDateElement.getAttribute(&amp;quot;day&amp;quot;);&lt;br /&gt;
	&lt;br /&gt;
	// Get the content of the &amp;lt;to&amp;gt;, &amp;lt;message&amp;gt;, and &amp;lt;from&amp;gt; tags.  Again, you can use a chain to do this in one line for each.&lt;br /&gt;
	var to = xmlDocument.getElementsByTagName(&amp;quot;to&amp;quot;)[0].textContent;&lt;br /&gt;
	var message = xmlDocument.getElementsByTagName(&amp;quot;message&amp;quot;)[0].textContent;&lt;br /&gt;
	var from = xmlDocument.getElementsByTagName(&amp;quot;from&amp;quot;)[0].textContent;&lt;br /&gt;
	&lt;br /&gt;
	// Make a &amp;lt;strong&amp;gt; tag, append the date string as its content, and then append it to the HTML element.&lt;br /&gt;
	var htmlDateObj = document.createElement(&amp;quot;strong&amp;quot;);&lt;br /&gt;
	htmlDateObj.appendChild(document.createTextNode(dateString));&lt;br /&gt;
	htmlParent.appendChild(htmlDateObj);&lt;br /&gt;
	&lt;br /&gt;
	// Make a &amp;lt;p&amp;gt; tag to contain the note.&lt;br /&gt;
	var htmlParagraphObj = document.createElement(&amp;quot;p&amp;quot;);&lt;br /&gt;
	htmlParagraphObj.appendChild(document.createTextNode(&amp;quot;Dear &amp;quot;+to+&amp;quot;,&amp;quot;)); // First append the greeting&lt;br /&gt;
	htmlParagraphObj.appendChild(document.createElement(&amp;quot;br&amp;quot;)); // Append a couple line feeds&lt;br /&gt;
	htmlParagraphObj.appendChild(document.createElement(&amp;quot;br&amp;quot;));&lt;br /&gt;
	htmlParagraphObj.appendChild(document.createTextNode(message)); // Write the message itself&lt;br /&gt;
	htmlParagraphObj.appendChild(document.createElement(&amp;quot;br&amp;quot;)); // Append a couple more line feeds&lt;br /&gt;
	htmlParagraphObj.appendChild(document.createElement(&amp;quot;br&amp;quot;));&lt;br /&gt;
	htmlParagraphObj.appendChild(document.createTextNode(&amp;quot;Love, &amp;quot;+from)); // Finally, append the salutation&lt;br /&gt;
	htmlParent.appendChild(htmlParagraphObj); // Append the newly engineered &amp;lt;p&amp;gt; to the HTML element.&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
document.addEventListener(&amp;quot;DOMContentLoaded&amp;quot;, getNoteAjax, false); // Bind the AJAX call to page load&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This example uses a lot of techniques documented in the [[JavaScript#Document Object Model]] section above.  The resulting DOM will be something like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;div id=&amp;quot;note&amp;quot;&amp;gt;&lt;br /&gt;
  &amp;lt;strong&amp;gt;2013-02-14&amp;lt;/strong&amp;gt;&lt;br /&gt;
  &amp;lt;p&amp;gt;Dear Sally,&amp;lt;br /&amp;gt;&amp;lt;br /&amp;gt;Happy Valentine's Day!&amp;lt;br /&amp;gt;&amp;lt;br /&amp;gt;Love, Your Secret Admirer&amp;lt;/p&amp;gt;&lt;br /&gt;
&amp;lt;/div&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If you think that this is a lot of code to produce a relatively simple output, you are not alone.  You will learn how to do this job in much fewer lines when you learn about [[Ext JS]].&lt;br /&gt;
&lt;br /&gt;
== Debugging AJAX and JSON ==&lt;br /&gt;
&lt;br /&gt;
It is helpful when building your application to look at the AJAX requests and responses as they happen in real time.  Fortunately, there are many tools to help.&lt;br /&gt;
&lt;br /&gt;
In your favorite web inspector (Chrome Dev Tools, Mozilla Dev Tools, Firebug, Dragonfly, and so on), go to the &amp;quot;Network&amp;quot; tab.  This is where you can see all assets loaded by the application: images, stylesheets, and, most importantly for us, AJAX files.  Some inspectors let you filter requests by type; for example, the Chrome inspector lets you click &amp;quot;XHR&amp;quot; to only show XMLHttpRequest (AJAX) requests.&lt;br /&gt;
&lt;br /&gt;
You can also view the JSON sent by your server.  Double-clicking the entries in the web inspector opens the source URL in a new tab.&lt;br /&gt;
&lt;br /&gt;
If you find minified JSON hard to read, we recommend that you install the JSONView browser extension or one of its close relatives:&lt;br /&gt;
* [https://addons.mozilla.org/en-us/firefox/addon/jsonview/ Firefox]&lt;br /&gt;
* [https://chrome.google.com/webstore/detail/jsonview/chklaanhfefbnpoihckbnefhakgolnmc?hl=en Chrome]&lt;br /&gt;
* [https://addons.opera.com/en/extensions/details/jsonviewer/ Opera]&lt;br /&gt;
* [https://github.com/rfletcher/safari-json-formatter Safari]&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 6]]&lt;/div&gt;</summary>
		<author><name>Alex</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=AJAX_and_JSON&amp;diff=2552</id>
		<title>AJAX and JSON</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=AJAX_and_JSON&amp;diff=2552"/>
		<updated>2018-04-30T21:32:48Z</updated>

		<summary type="html">&lt;p&gt;Alex: /* Logging In a User */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Asynchronous Javascript And XML, or '''''AJAX''''', is a group of related web development techniques, standards, and technologies used on the client (web browser) side of the standard web server-client communication model.&lt;br /&gt;
&lt;br /&gt;
Here's the general concept: JavaScript is used to send requests to the web server in the background and retrieve data, without the need to refresh the page.  The result: dynamic, fast, user-friendly web pages.&lt;br /&gt;
&lt;br /&gt;
The requests are performed ''asynchronously'': this means that the end user can continue interacting with your web page while the server data is being loaded.&lt;br /&gt;
&lt;br /&gt;
The key idea is that a large fraction of the work happens at the web browser, and larger requests happen behind the scenes, keeping waiting times for data to come back over the network to a minimum.  AJAX is generally also associated with higher-level APIs and libraries that aid in producing cleaner user interfaces for web applications.&lt;br /&gt;
&lt;br /&gt;
== The XMLHttpRequest Object ==&lt;br /&gt;
&lt;br /&gt;
The JavaScript specification defines the '''XMLHttpRequest''' object (sometimes abbreviated as '''XHR'''), which is used to exchange data with the web servers without needing to reload the entire web page in the browser.&lt;br /&gt;
&lt;br /&gt;
=== Initializing an XMLHttpRequest Object ===&lt;br /&gt;
&lt;br /&gt;
As stated above, the XMLHttpRequest object handles communication with the web servers.  To use it, you must first initialize a variable to be an instance of the '''XMLHttpRequest''' &amp;quot;class&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var xmlHttp = new XMLHttpRequest();&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Next, use your XMLHttpRequest instance to open a connection to your server.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
xmlHttp.open(&amp;quot;METHOD&amp;quot;, &amp;quot;URL_OF_SERVER_SCRIPT&amp;quot;, ASYNCRONOUS_FLAG);&lt;br /&gt;
// METHOD: either GET or POST.&lt;br /&gt;
// URL_OF_SERVER_SCRIPT: the path to your server-side script relative to the current page.  For example, process_ajax.php&lt;br /&gt;
// ASYNCRONOUS_FLAG: Should be true in order to perform the request asynchronously.  (Having a value of false will freeze the browser until the request is completed.)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{DoctypeTV&lt;br /&gt;
|youtube_id=isrqZQPE2eQ&lt;br /&gt;
|time=3m51s&lt;br /&gt;
|desc=Explaining the Cross-Site Policy in AJAX&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
'''Note:''' For security reasons, you cannot perform AJAX requests to other domains, unless that domain has a special security policy set up to enable such requests.&lt;br /&gt;
&lt;br /&gt;
=== Sending Data ===&lt;br /&gt;
&lt;br /&gt;
==== GET Data ====&lt;br /&gt;
&lt;br /&gt;
To send GET data, append the information to the end of the URL_OF_SERVER_SCRIPT, as you would normally do, and then call xmlHttp.send(), passing ''null'' as the parameter:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var xmlHttp = new XMLHttpRequest();&lt;br /&gt;
xmlHttp.open(&amp;quot;GET&amp;quot;, &amp;quot;process_ajax.php?var1=val1&amp;amp;var2=val2&amp;quot;, true);&lt;br /&gt;
xmlHttp.send(null);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== POST Data ====&lt;br /&gt;
&lt;br /&gt;
To send POST data, pass a URL-encoded string to xmlHttp.send().  You also need to change the MIME Type of the outgoing request.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var xmlHttp = new XMLHttpRequest();&lt;br /&gt;
xmlHttp.open(&amp;quot;POST&amp;quot;, &amp;quot;process_ajax.php&amp;quot;, true);&lt;br /&gt;
xmlHttp.setRequestHeader(&amp;quot;Content-Type&amp;quot;, &amp;quot;application/x-www-form-urlencoded&amp;quot;);&lt;br /&gt;
xmlHttp.send(&amp;quot;var1=val1&amp;amp;var2=val2&amp;quot;);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Listening for a Response ===&lt;br /&gt;
&lt;br /&gt;
XMLHttpRequest will fire an [[JavaScript#Events|event]] when the request has been completed.  We therefore need to use a '''[[JavaScript#Events|callback function]]''' in order to listen for the '''load''' event on the XMLHttpRequest object.&lt;br /&gt;
&lt;br /&gt;
The server's plain text response is available as the '''responseText''' property of your XMLHttpRequest instance, which is available in the '''target''' property of the event.  For example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var xmlHttp = new XMLHttpRequest();&lt;br /&gt;
xmlHttp.open(&amp;quot;GET&amp;quot;, &amp;quot;hello.txt&amp;quot;, true);&lt;br /&gt;
xmlHttp.addEventListener(&amp;quot;load&amp;quot;, ajaxCallback, false);&lt;br /&gt;
xmlHttp.send(null);&lt;br /&gt;
&lt;br /&gt;
// ...&lt;br /&gt;
&lt;br /&gt;
function ajaxCallback(event){&lt;br /&gt;
	alert( &amp;quot;Your file contains the text: &amp;quot; + event.target.responseText );&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Browser Support ====&lt;br /&gt;
&lt;br /&gt;
Many examples that you find when Googling for &amp;quot;AJAX&amp;quot; use the '''onreadystatechange''' property of the XMLHttpRequest instance to react on the completion of the request, rather than using an event listener.  This approach works, and it is required for comprehensive browser support, but it is no longer recommended for future use in modern web applications.  The implementation of XMLHttpRequest documented here (so-called &amp;quot;XHR level 2&amp;quot;) works in the following browsers:&lt;br /&gt;
* Firefox 3.5+ (Jun 2009)&lt;br /&gt;
* Safari 5+ (Jun 2010)&lt;br /&gt;
* Chrome 7+ (Sep 2010)&lt;br /&gt;
* Opera 12+ (May 2012)&lt;br /&gt;
* Internet Explorer 10+ (unreleased)&lt;br /&gt;
Together, browsers supporting XHR level 2 account [http://caniuse.com/xhr2 77% of the market] as of August 2013.&lt;br /&gt;
&lt;br /&gt;
=== Response Formats ===&lt;br /&gt;
&lt;br /&gt;
More often than not, a plaintext response form the server is not very helpful: you want to transmit more information than simply a single string of text.  There are two good options to get more information from a single AJAX request: '''XML''' (the original format, thus the ''X'' in ''AJAX'') and '''JSON'''.&lt;br /&gt;
&lt;br /&gt;
==== XML ====&lt;br /&gt;
&lt;br /&gt;
Your server can respond with an XML document (whence, ''XMLHttpRequest'').  An '''XML document''' uses syntax that is extremely close to HTML  For example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;xml&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;?xml version=&amp;quot;1.0&amp;quot; standalone=&amp;quot;yes&amp;quot; ?&amp;gt;&lt;br /&gt;
&amp;lt;note&amp;gt;&lt;br /&gt;
  &amp;lt;date year=&amp;quot;2013&amp;quot; month=&amp;quot;02&amp;quot; day=&amp;quot;14&amp;quot; /&amp;gt;&lt;br /&gt;
  &amp;lt;to&amp;gt;Sally&amp;lt;/to&amp;gt;&lt;br /&gt;
  &amp;lt;message&amp;gt;Happy Valentine's Day!&amp;lt;/message&amp;gt;&lt;br /&gt;
  &amp;lt;from&amp;gt;Your Secret Admirer&amp;lt;/from&amp;gt;&lt;br /&gt;
&amp;lt;/note&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Like HTML, XML has a DOM that can be traversed in JavaScript.&lt;br /&gt;
&lt;br /&gt;
If you make an AJAX request to a script generating an XML document, the root XML node is accessible in the '''responseXML''' property.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
function ajaxCallback(event){&lt;br /&gt;
	var xmlDocument = event.target.responseXML;&lt;br /&gt;
	&lt;br /&gt;
	alert(xmlDocument.getElementsByTagName(&amp;quot;to&amp;quot;)[0].textContent);  // Sally (in the case of the example XML above)&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== JSON ====&lt;br /&gt;
&lt;br /&gt;
JavaScript Object Notation, or '''JSON''', is a rising standard interface format because of its lightweight syntax that makes it especially useful for AJAX requests.&lt;br /&gt;
&lt;br /&gt;
The JSON syntax closely follows the syntax for [[JavaScript#Object Literals|object literals]].  For example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
{&lt;br /&gt;
   &amp;quot;apple&amp;quot;: {&lt;br /&gt;
      &amp;quot;color&amp;quot;: &amp;quot;red&amp;quot;,&lt;br /&gt;
      &amp;quot;flavor&amp;quot;: &amp;quot;sweet&amp;quot;&lt;br /&gt;
   },&lt;br /&gt;
   &amp;quot;lemon&amp;quot;: {&lt;br /&gt;
      &amp;quot;color&amp;quot;: &amp;quot;yellow&amp;quot;,&lt;br /&gt;
      &amp;quot;flavor&amp;quot;: &amp;quot;sour&amp;quot;&lt;br /&gt;
   }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Usually when JSON is transferred over the internet, it is condensed down to one line, like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
{&amp;quot;apple&amp;quot;:{&amp;quot;color&amp;quot;:&amp;quot;red&amp;quot;,&amp;quot;flavor&amp;quot;:&amp;quot;sweet&amp;quot;},&amp;quot;lemon&amp;quot;:{&amp;quot;color&amp;quot;:&amp;quot;yellow&amp;quot;,&amp;quot;flavor&amp;quot;:&amp;quot;sour&amp;quot;}}&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In JavaScript, you can convert a JSON string to an object using '''JSON.parse()'''.  For example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var jsonData = JSON.parse('{&amp;quot;apple&amp;quot;:{&amp;quot;color&amp;quot;:&amp;quot;red&amp;quot;,&amp;quot;flavor&amp;quot;:&amp;quot;sweet&amp;quot;},&amp;quot;lemon&amp;quot;:{&amp;quot;color&amp;quot;:&amp;quot;yellow&amp;quot;,&amp;quot;flavor&amp;quot;:&amp;quot;sour&amp;quot;}}');&lt;br /&gt;
&lt;br /&gt;
alert(jsonData.apple.color);  // red&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here's how to use it in conjunction with your AJAX response callback:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
function ajaxCallback(event){&lt;br /&gt;
	var jsonData = JSON.parse(event.target.responseText);&lt;br /&gt;
	&lt;br /&gt;
	alert(jsonData.lemon.flavor);  // sour (in the case of the example JSON above)&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here is a graphic to illustrate the JSON process.&lt;br /&gt;
&lt;br /&gt;
[[File:JSON-Flowchart.png‎]]&lt;br /&gt;
&lt;br /&gt;
== Examples ==&lt;br /&gt;
&lt;br /&gt;
=== Logging In a User ===&lt;br /&gt;
&lt;br /&gt;
Suppose you had the following PHP script:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;php&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;?php&lt;br /&gt;
// login_ajax.php&lt;br /&gt;
&lt;br /&gt;
header(&amp;quot;Content-Type: application/json&amp;quot;); // Since we are sending a JSON response here (not an HTML document), set the MIME Type to application/json&lt;br /&gt;
&lt;br /&gt;
$username = $_POST['username'];&lt;br /&gt;
$password = $_POST['password'];&lt;br /&gt;
&lt;br /&gt;
// Check to see if the username and password are valid.  (You learned how to do this in Module 3.)&lt;br /&gt;
&lt;br /&gt;
if( /* valid username and password */ ){&lt;br /&gt;
	session_start();&lt;br /&gt;
	$_SESSION['username'] = $username;&lt;br /&gt;
	$_SESSION['token'] = bin2hex(openssl_random_pseudo_bytes(32)); &lt;br /&gt;
&lt;br /&gt;
	echo json_encode(array(&lt;br /&gt;
		&amp;quot;success&amp;quot; =&amp;gt; true&lt;br /&gt;
	));&lt;br /&gt;
	exit;&lt;br /&gt;
}else{&lt;br /&gt;
	echo json_encode(array(&lt;br /&gt;
		&amp;quot;success&amp;quot; =&amp;gt; false,&lt;br /&gt;
		&amp;quot;message&amp;quot; =&amp;gt; &amp;quot;Incorrect Username or Password&amp;quot;&lt;br /&gt;
	));&lt;br /&gt;
	exit;&lt;br /&gt;
}&lt;br /&gt;
?&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Note:''' This example uses PHP's very handy '''json_encode()''' function to translate an associative array into a JSON object.  This means that you can access in JavaScript the same structure that you made in PHP!&lt;br /&gt;
&lt;br /&gt;
And suppose you had the following HTML content:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;input type=&amp;quot;text&amp;quot; id=&amp;quot;username&amp;quot; placeholder=&amp;quot;Username&amp;quot; /&amp;gt;&lt;br /&gt;
&amp;lt;input type=&amp;quot;password&amp;quot; id=&amp;quot;password&amp;quot; placeholder=&amp;quot;Password&amp;quot; /&amp;gt;&lt;br /&gt;
&amp;lt;button id=&amp;quot;login_btn&amp;quot;&amp;gt;Log In&amp;lt;/button&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;script type=&amp;quot;text/javascript&amp;quot; src=&amp;quot;ajax.js&amp;quot;&amp;gt;&amp;lt;/script&amp;gt; &amp;lt;!-- load the JavaScript file --&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You could use the following JavaScript code to prepare, send, and receive a request from the server to see if the user is logged in, without ever having to refresh the page.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// ajax.js&lt;br /&gt;
&lt;br /&gt;
function loginAjax(event){&lt;br /&gt;
	var username = document.getElementById(&amp;quot;username&amp;quot;).value; // Get the username from the form&lt;br /&gt;
	var password = document.getElementById(&amp;quot;password&amp;quot;).value; // Get the password from the form&lt;br /&gt;
&lt;br /&gt;
	// Make a URL-encoded string for passing POST data:&lt;br /&gt;
	var dataString = &amp;quot;username=&amp;quot; + encodeURIComponent(username) + &amp;quot;&amp;amp;password=&amp;quot; + encodeURIComponent(password);&lt;br /&gt;
	&lt;br /&gt;
	var xmlHttp = new XMLHttpRequest(); // Initialize our XMLHttpRequest instance&lt;br /&gt;
	xmlHttp.open(&amp;quot;POST&amp;quot;, &amp;quot;login_ajax.php&amp;quot;, true); // Starting a POST request (NEVER send passwords as GET variables!!!)&lt;br /&gt;
	xmlHttp.setRequestHeader(&amp;quot;Content-Type&amp;quot;, &amp;quot;application/x-www-form-urlencoded&amp;quot;); // It's easy to forget this line for POST requests&lt;br /&gt;
	xmlHttp.addEventListener(&amp;quot;load&amp;quot;, function(event){&lt;br /&gt;
		var jsonData = JSON.parse(event.target.responseText); // parse the JSON into a JavaScript object&lt;br /&gt;
		if(jsonData.success){  // in PHP, this was the &amp;quot;success&amp;quot; key in the associative array; in JavaScript, it's the .success property of jsonData&lt;br /&gt;
			alert(&amp;quot;You've been Logged In!&amp;quot;);&lt;br /&gt;
		}else{&lt;br /&gt;
			alert(&amp;quot;You were not logged in.  &amp;quot;+jsonData.message);&lt;br /&gt;
		}&lt;br /&gt;
	}, false); // Bind the callback to the load event&lt;br /&gt;
	xmlHttp.send(dataString); // Send the data&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
document.getElementById(&amp;quot;login_btn&amp;quot;).addEventListener(&amp;quot;click&amp;quot;, loginAjax, false); // Bind the AJAX call to button click&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Note:''' The above example uses an '''anonymous function''' (a function without a name that is declared in an attribute) as the callback.  If you are using a certain callback function only once in your program, this is a perfectly valid approach to reduce the amount of code you need to write.&lt;br /&gt;
&lt;br /&gt;
=== Loading Data from an XML File for Display in HTML ===&lt;br /&gt;
&lt;br /&gt;
Suppose you have a file '''note.xml''' that contains the following information:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;xml&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;?xml version=&amp;quot;1.0&amp;quot; standalone=&amp;quot;yes&amp;quot; ?&amp;gt;&lt;br /&gt;
&amp;lt;note&amp;gt;&lt;br /&gt;
  &amp;lt;date year=&amp;quot;2013&amp;quot; month=&amp;quot;02&amp;quot; day=&amp;quot;14&amp;quot; /&amp;gt;&lt;br /&gt;
  &amp;lt;to&amp;gt;Sally&amp;lt;/to&amp;gt;&lt;br /&gt;
  &amp;lt;message&amp;gt;Happy Valentine's Day!&amp;lt;/message&amp;gt;&lt;br /&gt;
  &amp;lt;from&amp;gt;Your Secret Admirer&amp;lt;/from&amp;gt;&lt;br /&gt;
&amp;lt;/note&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Further, suppose you had an HTML element with ID '''note''':&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;div id=&amp;quot;note&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You could load this XML file and then display it inside of your HTML document like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
function getNoteAjax(event){&lt;br /&gt;
	// The XMLHttpRequest is simple this time:&lt;br /&gt;
	var xmlHttp = new XMLHttpRequest();&lt;br /&gt;
	xmlHttp.open(&amp;quot;GET&amp;quot;, &amp;quot;note.xml&amp;quot;, true);&lt;br /&gt;
	xmlHttp.addEventListener(&amp;quot;load&amp;quot;, getNoteCallback, false);&lt;br /&gt;
	xmlHttp.send(null);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
function getNoteCallback(event){&lt;br /&gt;
	var htmlParent = document.getElementById(&amp;quot;note&amp;quot;); // Get the HTML element into which we want to write the note&lt;br /&gt;
	var xmlDocument = event.target.responseXML; // Get the XML root node from the response&lt;br /&gt;
	&lt;br /&gt;
	// Find the &amp;lt;date/&amp;gt; element from the XML response.  We expect only 1 such element, so we can call&lt;br /&gt;
	// xmlDocument.getElementsByTagName() and then get the first (and only) element in the array all in&lt;br /&gt;
	// one step.  This is called chaining.&lt;br /&gt;
	var xmlDateElement = xmlDocument.getElementsByTagName(&amp;quot;date&amp;quot;)[0];&lt;br /&gt;
	&lt;br /&gt;
	// Put together a YYYY-MM-DD type date into a string based on the attributes of the &amp;lt;date/&amp;gt; element.&lt;br /&gt;
	var dateString = xmlDateElement.getAttribute(&amp;quot;year&amp;quot;) + &amp;quot;-&amp;quot; + xmlDateElement.getAttribute(&amp;quot;month&amp;quot;)&lt;br /&gt;
		+ &amp;quot;-&amp;quot; + xmlDateElement.getAttribute(&amp;quot;day&amp;quot;);&lt;br /&gt;
	&lt;br /&gt;
	// Get the content of the &amp;lt;to&amp;gt;, &amp;lt;message&amp;gt;, and &amp;lt;from&amp;gt; tags.  Again, you can use a chain to do this in one line for each.&lt;br /&gt;
	var to = xmlDocument.getElementsByTagName(&amp;quot;to&amp;quot;)[0].textContent;&lt;br /&gt;
	var message = xmlDocument.getElementsByTagName(&amp;quot;message&amp;quot;)[0].textContent;&lt;br /&gt;
	var from = xmlDocument.getElementsByTagName(&amp;quot;from&amp;quot;)[0].textContent;&lt;br /&gt;
	&lt;br /&gt;
	// Make a &amp;lt;strong&amp;gt; tag, append the date string as its content, and then append it to the HTML element.&lt;br /&gt;
	var htmlDateObj = document.createElement(&amp;quot;strong&amp;quot;);&lt;br /&gt;
	htmlDateObj.appendChild(document.createTextNode(dateString));&lt;br /&gt;
	htmlParent.appendChild(htmlDateObj);&lt;br /&gt;
	&lt;br /&gt;
	// Make a &amp;lt;p&amp;gt; tag to contain the note.&lt;br /&gt;
	var htmlParagraphObj = document.createElement(&amp;quot;p&amp;quot;);&lt;br /&gt;
	htmlParagraphObj.appendChild(document.createTextNode(&amp;quot;Dear &amp;quot;+to+&amp;quot;,&amp;quot;)); // First append the greeting&lt;br /&gt;
	htmlParagraphObj.appendChild(document.createElement(&amp;quot;br&amp;quot;)); // Append a couple line feeds&lt;br /&gt;
	htmlParagraphObj.appendChild(document.createElement(&amp;quot;br&amp;quot;));&lt;br /&gt;
	htmlParagraphObj.appendChild(document.createTextNode(message)); // Write the message itself&lt;br /&gt;
	htmlParagraphObj.appendChild(document.createElement(&amp;quot;br&amp;quot;)); // Append a couple more line feeds&lt;br /&gt;
	htmlParagraphObj.appendChild(document.createElement(&amp;quot;br&amp;quot;));&lt;br /&gt;
	htmlParagraphObj.appendChild(document.createTextNode(&amp;quot;Love, &amp;quot;+from)); // Finally, append the salutation&lt;br /&gt;
	htmlParent.appendChild(htmlParagraphObj); // Append the newly engineered &amp;lt;p&amp;gt; to the HTML element.&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
document.addEventListener(&amp;quot;DOMContentLoaded&amp;quot;, getNoteAjax, false); // Bind the AJAX call to page load&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This example uses a lot of techniques documented in the [[JavaScript#Document Object Model]] section above.  The resulting DOM will be something like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;div id=&amp;quot;note&amp;quot;&amp;gt;&lt;br /&gt;
  &amp;lt;strong&amp;gt;2013-02-14&amp;lt;/strong&amp;gt;&lt;br /&gt;
  &amp;lt;p&amp;gt;Dear Sally,&amp;lt;br /&amp;gt;&amp;lt;br /&amp;gt;Happy Valentine's Day!&amp;lt;br /&amp;gt;&amp;lt;br /&amp;gt;Love, Your Secret Admirer&amp;lt;/p&amp;gt;&lt;br /&gt;
&amp;lt;/div&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If you think that this is a lot of code to produce a relatively simple output, you are not alone.  You will learn how to do this job in much fewer lines when you learn about [[Ext JS]].&lt;br /&gt;
&lt;br /&gt;
== Debugging AJAX and JSON ==&lt;br /&gt;
&lt;br /&gt;
It is helpful when building your application to look at the AJAX requests and responses as they happen in real time.  Fortunately, there are many tools to help.&lt;br /&gt;
&lt;br /&gt;
In your favorite web inspector (Chrome Dev Tools, Mozilla Dev Tools, Firebug, Dragonfly, and so on), go to the &amp;quot;Network&amp;quot; tab.  This is where you can see all assets loaded by the application: images, stylesheets, and, most importantly for us, AJAX files.  Some inspectors let you filter requests by type; for example, the Chrome inspector lets you click &amp;quot;XHR&amp;quot; to only show XMLHttpRequest (AJAX) requests.&lt;br /&gt;
&lt;br /&gt;
You can also view the JSON sent by your server.  Double-clicking the entries in the web inspector opens the source URL in a new tab.&lt;br /&gt;
&lt;br /&gt;
If you find minified JSON hard to read, we recommend that you install the JSONView browser extension or one of its close relatives:&lt;br /&gt;
* [https://addons.mozilla.org/en-us/firefox/addon/jsonview/ Firefox]&lt;br /&gt;
* [https://chrome.google.com/webstore/detail/jsonview/chklaanhfefbnpoihckbnefhakgolnmc?hl=en Chrome]&lt;br /&gt;
* [https://addons.opera.com/en/extensions/details/jsonviewer/ Opera]&lt;br /&gt;
* [https://github.com/rfletcher/safari-json-formatter Safari]&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 6]]&lt;/div&gt;</summary>
		<author><name>Alex</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Module_5&amp;diff=2551</id>
		<title>Module 5</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Module_5&amp;diff=2551"/>
		<updated>2018-04-22T20:03:08Z</updated>

		<summary type="html">&lt;p&gt;Alex: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;__NOTOC__&lt;br /&gt;
In Module 5, you will learn JavaScript, the dominant client-side web language.  JavaScript is the third and final programming language you will learn in CSE 330.&lt;br /&gt;
&lt;br /&gt;
This article contains your assignments for Module 5.&lt;br /&gt;
&lt;br /&gt;
'''Warning:'''&lt;br /&gt;
&lt;br /&gt;
''This module takes students a while. It is strongly recommended that you start early and ask questions as they come up.''&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Reading ==&lt;br /&gt;
&lt;br /&gt;
The following articles on the online class wiki textbook contain information that will help you complete the assignments.&lt;br /&gt;
&lt;br /&gt;
* [[JavaScript]]&lt;br /&gt;
* [[AJAX and JSON]]&lt;br /&gt;
* [[jQuery]]&lt;br /&gt;
* [[Web Application Security, Part 3]]&lt;br /&gt;
&lt;br /&gt;
== Individual Assignments ==&lt;br /&gt;
&lt;br /&gt;
'''''IMPORTANT:'' Both of the individual assignments must be completed ''without'' using a JavaScript library like jQuery.'''  However, you may use jQuery for the group portion.&lt;br /&gt;
&lt;br /&gt;
=== JavaScript Calculator ===&lt;br /&gt;
&lt;br /&gt;
In Module 2, you made a calculator using PHP.  Now you will be making one using JavaScript.&lt;br /&gt;
&lt;br /&gt;
* The web page should have two input fields and a radio button group for the operation, with the 4 basic math operations represented (add, subtract, multiply, divide).&lt;br /&gt;
* JavaScript should monitor all three fields and display the current result whenever the user changes any value in any field, without refreshing the page.&lt;br /&gt;
*: '''Tip 1:''' Consider using either the ''change'' or the ''keyup'' event on the text fields, and either the ''change'' or the ''click'' event on the radio buttons.&lt;br /&gt;
*: '''Tip 2:''' Re-read [[JavaScript|the JavaScript guide]] if you need help figuring our how to bind callback functions to events, or how to determine which radio button is currently selected.  (There are examples for both of these!)&lt;br /&gt;
* The calculator should be completely self-contained; i.e., you should not be making any requests to any other server-side or client-side scripts or web pages after the initial page load.&lt;br /&gt;
&lt;br /&gt;
'''Tip:''' You can embed JavaScript code into an HTML document like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;script&amp;gt;&lt;br /&gt;
// your code here&lt;br /&gt;
&amp;lt;/script&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Tip:''' If your code isn't working the way you expect, use a JavaScript error console.  In Chrome, for example, press Ctrl-Shift-I (or Cmd-Option-I) to open the WebKit inspector.&lt;br /&gt;
&lt;br /&gt;
'''Important:''' It is best practice to fully separate the content, appearance, and behavior.  In previous modules, you may have lost points for using HTML tags that change the appearance of things &amp;lt;nowiki&amp;gt;(like &amp;lt;center&amp;gt; and &amp;lt;font&amp;gt;).&amp;lt;/nowiki&amp;gt;  In this module, make sure that you define your event listeners in JavaScript as in &amp;lt;code&amp;gt;document.getElementById(&amp;quot;xyz&amp;quot;).addEventListener(...)&amp;lt;/code&amp;gt; and '''''not''''' in the HTML like &amp;lt;code&amp;gt;&amp;lt;button onclick=&amp;quot;badExample();&amp;quot;&amp;gt;Bad Example&amp;lt;/button&amp;gt;&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== Weather Widget ===&lt;br /&gt;
&lt;br /&gt;
In this section, you will make a web page that displays the weather forecast using AJAX requests to a weather server.&lt;br /&gt;
&lt;br /&gt;
# Make an empty HTML document; name it '''weather.html'''&lt;br /&gt;
#: Refer to the [[HTML and CSS]] guide for the skeleton of an HTML document&lt;br /&gt;
# Define a function in JavaScript; call it '''fetchWeather()'''.  You may write your JavaScript in an embedded script in your HTML document.&lt;br /&gt;
# Inside your '''fetchWeather()''' function, make an AJAX request to the weather server.&lt;br /&gt;
#: We have a server that outputs the current weather in JSON format.  The format is documented in the [[#JSON Structure]] section below.&lt;br /&gt;
#: '''URL:''' https://classes.engineering.wustl.edu/cse330/content/weather_json.php&lt;br /&gt;
#: We kindly thank Yahoo Weather for providing us with up-to-date weather information.&lt;br /&gt;
#* '''IMPORTANT:''' Under normal circumstances, AJAX requests ''cannot'' be performed cross-domain for security reasons.  We have set the &amp;lt;code&amp;gt;Access-Control-Allow-Origin&amp;lt;/code&amp;gt; header on our server to allow requests from your EC2 instances, or from localhost.  '''You will therefore need to upload your code to your EC2, or access it via localhost, in order for the AJAX requests to work.'''  This means that you cannot, for example, complete this part of the individual portion in JSFiddle.&lt;br /&gt;
# In your callback, process the JSON and use JavaScript to manipulate the HTML DOM to display the following information on your page:&lt;br /&gt;
#* Location&lt;br /&gt;
#** City, in a &amp;lt;nowiki&amp;gt;&amp;lt;strong&amp;gt;&amp;lt;/nowiki&amp;gt; tag&lt;br /&gt;
#** State, not in any tag&lt;br /&gt;
#* Humidity&lt;br /&gt;
#* Current Temperature&lt;br /&gt;
#* Image for Tomorrow's Forecast (see [[#Weather Condition Images]] below for more information)&lt;br /&gt;
#* Image for the Day After Tomorrow's Forecast&lt;br /&gt;
# Finally, bind '''fetchWeather()''' to the DOMContentLoaded event so that your weather widget is automatically initialized when the page is loaded:&lt;br /&gt;
#: &amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;document.addEventListener(&amp;quot;DOMContentLoaded&amp;quot;, fetchWeather, false);&amp;lt;/source&amp;gt;&lt;br /&gt;
# In addition, add a button that runs your ''fetchWeather'' function when clicked.  This should update your widget with the current weather conditions.&lt;br /&gt;
&lt;br /&gt;
Use the following HTML:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;div class=&amp;quot;weather&amp;quot; id=&amp;quot;weatherWidget&amp;quot;&amp;gt;&lt;br /&gt;
	&amp;lt;div class=&amp;quot;weather-loc&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
	&amp;lt;div class=&amp;quot;weather-humidity&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
	&amp;lt;div class=&amp;quot;weather-temp&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
	&amp;lt;img class=&amp;quot;weather-tomorrow&amp;quot; /&amp;gt;&lt;br /&gt;
	&amp;lt;img class=&amp;quot;weather-dayaftertomorrow&amp;quot; /&amp;gt;&lt;br /&gt;
&amp;lt;/div&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Include the CSS file from here: http://classes.engineering.wustl.edu/cse330/content/weather.css&lt;br /&gt;
&lt;br /&gt;
When everything is working, the weather widget should look something like this:&lt;br /&gt;
&lt;br /&gt;
[[File:WeatherWidget.png]]&lt;br /&gt;
&lt;br /&gt;
'''Important:''' The widget in this section needs to work in only Firefox and Chrome.  It does '''''not''''' need to work Internet Explorer.&lt;br /&gt;
&lt;br /&gt;
==== Tips ====&lt;br /&gt;
&lt;br /&gt;
===== JSON Structure =====&lt;br /&gt;
&lt;br /&gt;
The JSON from our server looks like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
{&lt;br /&gt;
   &amp;quot;updated&amp;quot;: &amp;quot;Thu, 11 Oct 2012 5:54 pm CDT&amp;quot;,&lt;br /&gt;
   &amp;quot;location&amp;quot;: {&lt;br /&gt;
      &amp;quot;city&amp;quot;: &amp;quot;St. Louis&amp;quot;,&lt;br /&gt;
      &amp;quot;state&amp;quot;: &amp;quot;MO&amp;quot;&lt;br /&gt;
   },&lt;br /&gt;
   &amp;quot;wind&amp;quot;: {&lt;br /&gt;
      &amp;quot;chill&amp;quot;: &amp;quot;62&amp;quot;,&lt;br /&gt;
      &amp;quot;direction&amp;quot;: &amp;quot;150&amp;quot;,&lt;br /&gt;
      &amp;quot;speed&amp;quot;: &amp;quot;3 mph&amp;quot;&lt;br /&gt;
   },&lt;br /&gt;
   &amp;quot;atmosphere&amp;quot;: {&lt;br /&gt;
      &amp;quot;humidity&amp;quot;: &amp;quot;50&amp;quot;,&lt;br /&gt;
      &amp;quot;visibility&amp;quot;: &amp;quot;10&amp;quot;,&lt;br /&gt;
      &amp;quot;pressure&amp;quot;: &amp;quot;30.12 in&amp;quot;&lt;br /&gt;
   },&lt;br /&gt;
   &amp;quot;current&amp;quot;: {&lt;br /&gt;
      &amp;quot;code&amp;quot;: &amp;quot;28&amp;quot;,&lt;br /&gt;
      &amp;quot;text&amp;quot;: &amp;quot;Mostly Cloudy&amp;quot;,&lt;br /&gt;
      &amp;quot;temp&amp;quot;: &amp;quot;62°F&amp;quot;,&lt;br /&gt;
      &amp;quot;date&amp;quot;: &amp;quot;Thu, 11 Oct 2012 5:54 pm CDT&amp;quot;&lt;br /&gt;
   },&lt;br /&gt;
   &amp;quot;tomorrow&amp;quot;: {&lt;br /&gt;
      &amp;quot;code&amp;quot;: &amp;quot;29&amp;quot;,&lt;br /&gt;
      &amp;quot;text&amp;quot;: &amp;quot;Clouds Early/Clearing Late&amp;quot;,&lt;br /&gt;
      &amp;quot;low&amp;quot;: &amp;quot;45°F&amp;quot;,&lt;br /&gt;
      &amp;quot;high&amp;quot;: &amp;quot;61°F&amp;quot;&lt;br /&gt;
   },&lt;br /&gt;
   &amp;quot;dayafter&amp;quot;: {&lt;br /&gt;
      &amp;quot;code&amp;quot;: &amp;quot;30&amp;quot;,&lt;br /&gt;
      &amp;quot;text&amp;quot;: &amp;quot;Partly Cloudy&amp;quot;,&lt;br /&gt;
      &amp;quot;low&amp;quot;: &amp;quot;53°F&amp;quot;,&lt;br /&gt;
      &amp;quot;high&amp;quot;: &amp;quot;65°F&amp;quot;&lt;br /&gt;
   },&lt;br /&gt;
   &amp;quot;credit&amp;quot;: &amp;quot;http://us.rd.yahoo.com/dailynews/rss/weather/St._Louis__MO/*http://weather.yahoo.com/forecast/USMO0170_f.html&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===== Weather Condition Images =====&lt;br /&gt;
&lt;br /&gt;
Each day's forecast has a code.  There are images associated with these codes.&lt;br /&gt;
&lt;br /&gt;
One place to get the images is from here: &amp;lt;nowiki&amp;gt;http://us.yimg.com/i/us/nws/weather/gr/&amp;lt;/nowiki&amp;gt;'''##'''&amp;lt;nowiki&amp;gt;ds.png&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Replace the '''##''' with the forecast code.  For example, for code 32, the URL would be: http://us.yimg.com/i/us/nws/weather/gr/32ds.png&lt;br /&gt;
&lt;br /&gt;
== Group Project ==&lt;br /&gt;
&lt;br /&gt;
I forgot if I already mentioned this, but '''start early on this project!''' It will take longer than you think, I promise!&lt;br /&gt;
&lt;br /&gt;
You are encouraged to use the advanced version control practices you learned in Module 5 when completing this assignment.&lt;br /&gt;
&lt;br /&gt;
=== Calendar ===&lt;br /&gt;
&lt;br /&gt;
Build a simple calendar that allows users to add and remove events dynamically.&lt;br /&gt;
&lt;br /&gt;
You will use JavaScript to process user interactions at the web browser, without ever refreshing the browser after the initial web page load.  You may use a JavaScript library of your choice, including Ext JS, so long as that JavaScript library does not defeat the purpose of the assignment. If you have questions about this, ask. In particular, libraries like FullCalendar are unacceptable.&lt;br /&gt;
&lt;br /&gt;
Your application should utilize AJAX to run server-side scripts that query your database to save and retrieve information, including user accounts and events.&lt;br /&gt;
&lt;br /&gt;
We have also written some functions to help you get started: [[JavaScript Calendar Library]]&lt;br /&gt;
&lt;br /&gt;
==== Examples ====&lt;br /&gt;
&lt;br /&gt;
* https://calendar.google.com/&lt;br /&gt;
* http://www.zoho.com/calendar/&lt;br /&gt;
&lt;br /&gt;
==== Server Side Language ====&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Additionally, you may use a database of your choice.  MySQL is probably the logical choice since you have been using it since Module 2, but you are free to explore other databases if you like.&lt;br /&gt;
&lt;br /&gt;
==== Requirements ====&lt;br /&gt;
&lt;br /&gt;
* Support a month-by-month view of the calendar.&lt;br /&gt;
*: Show one month at a time, with buttons to move forward or backward.&lt;br /&gt;
*: There should be no limit to how far forward or backward the user can go.&lt;br /&gt;
* Users can register and log in to the website.&lt;br /&gt;
*: You may leverage your MySQL project code and database from module 3 to get started.&lt;br /&gt;
* Unregistered users should see no events on the calendar.&lt;br /&gt;
* Registered users can add events.&lt;br /&gt;
*: All events should have a date and time, but do not need to have a duration.&lt;br /&gt;
*: You do ''not'' need to support recurring events (where you add an event that repeats, for example, every monday).&lt;br /&gt;
* Registered users see only events that they have added.&lt;br /&gt;
*: Your AJAX should not ask the server for events from a certain username.  Instead, your AJAX should ask the server for events, and the server should respond with the events for only the currently-logged-in user (from the session).  Can you think of why?&lt;br /&gt;
* Registered users can delete their events, but not the events of others.&lt;br /&gt;
*: Again, the server should delete events based on the username present in the session.  (If it deletes only based on an Event ID, an attacker could feed any arbitrary Event ID to your server, even if he/she didn't own that event.)&lt;br /&gt;
* All user and event data should be kept in a database.&lt;br /&gt;
* At no time should the main page need to be reloaded.&lt;br /&gt;
*: User registration, user authentication, event addition, and event deletion should all be handled by JavaScript and AJAX requests to your server.&lt;br /&gt;
* Your page needs to work in the versions of Firefox and Chrome installed on the lab computers.&lt;br /&gt;
&lt;br /&gt;
'''Tip:''' Run your database schema by a TA before implementing it.&lt;br /&gt;
&lt;br /&gt;
=== Web Security and Validation ===&lt;br /&gt;
&lt;br /&gt;
Your project needs to demonstrate that thought was put into web security and best practice.  For more information, see this week's Web Application Security guide: [[Web Application Security, Part 3]]&lt;br /&gt;
&lt;br /&gt;
In particular:&lt;br /&gt;
&lt;br /&gt;
* '''Your application needs to prevent XSS attacks.'''  Be careful when transmitting data over JSON that will be reflected in an event title!  (Note: JSON data should be sanitized on the client side, not the server side.)&lt;br /&gt;
* '''Perform precautionary measures to prevent session hijacking attacks.'''&lt;br /&gt;
*: You should specify your session cookie to be HTTP-Only.  However, for the means of this module, you need not test for user agent consistency.&lt;br /&gt;
* '''Optional:''' Validate your JavaScript code using [http://www.jshint.com/ JSHint] '''''or''''' [http://jslint.com/ JSLint] for up to 3 points of extra credit.&lt;br /&gt;
&lt;br /&gt;
You should continue the practices that you have learned in past weeks:&lt;br /&gt;
&lt;br /&gt;
* Pass tokens in forms to prevent CSRF attacks.&lt;br /&gt;
*: '''Hint:''' You will need to send your CSRF tokens in your AJAX requests.  Remember that AJAX still submits forms and runs server-side scripts, just like the vanilla forms you've been using in Modules 2 and 3.&lt;br /&gt;
* Use prepared queries to prevent SQL Injection attacks.&lt;br /&gt;
* If storing passwords in a database, always store them salted and encrypted.&lt;br /&gt;
* Your page should validate with no errors through the W3C validator.&lt;br /&gt;
&lt;br /&gt;
== Grading ==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
We will be grading the following aspects of your work.  There are 100 points total.&lt;br /&gt;
&lt;br /&gt;
'''Assignments (including code) must be committed to Bitbucket by the end of class on the due date (commit early and often). Failing to commit by the end of class on the due date will result in a 0. ''' &lt;br /&gt;
&lt;br /&gt;
If you do not include a link to your group portion running on your instance in your group portion README.md, you will receive a 0 for the group portion&lt;br /&gt;
_________&lt;br /&gt;
&lt;br /&gt;
# '''JavaScript Calculator (10 Points):'''&lt;br /&gt;
#* Calculator successfully adds, subtracts, multiplies, and divides numbers (3 points)&lt;br /&gt;
#* The result is automatically computed when a value in either field is changed (3 points)&lt;br /&gt;
#* Calculator is written entirely in pure, conventional JavaScript with no external libraries (4 points)*&lt;br /&gt;
#*: ''Note: be sure to fully separate content, appearance, and behavior.  This means that you should '''not''' use the event attributes on the HTML elements like onclick, onchange, and onkeyup.''&lt;br /&gt;
# '''Weather Widget (15 Points):'''&lt;br /&gt;
#* Widget performs an AJAX request to fetch the current weather (4 points)&lt;br /&gt;
#* The HTML template is filled with the correct information, including an image (4 points)&lt;br /&gt;
#* Button to reload the weather widget (2 points)&lt;br /&gt;
#* Widget is written entirely in pure, conventional JavaScript with no external libraries (5 points)*&lt;br /&gt;
# '''AJAX Calendar (60 Points):'''&lt;br /&gt;
#* '''''Calendar View (10 Points):'''''&lt;br /&gt;
#** The calendar is displayed as a table grid with days as the columns and weeks as the rows, one month at a time (5 points)&lt;br /&gt;
#** The user can view different months as far in the past or future as desired (5 points)&lt;br /&gt;
#* '''''User and Event Management (25 Points):'''''&lt;br /&gt;
#** Events can be added, modified, and deleted (5 points)&lt;br /&gt;
#** Events have a title, date, and time (2 points)&lt;br /&gt;
#** Users can log into the site, and they cannot view or manipulate events associated with other users (8 points)&lt;br /&gt;
#**: ''Don't fall into the Abuse of Functionality trap!  Check user credentials on the server side as well as on the client side.''&lt;br /&gt;
#** All actions are performed over AJAX, without ever needing to reload the page (10 points)&lt;br /&gt;
#* '''''Best Practices (20 Points):'''''&lt;br /&gt;
#** Code is well formatted and easy to read, with proper commenting (2 points)&lt;br /&gt;
#** If storing passwords, they are stored salted and hashed (2 points)&lt;br /&gt;
#** All AJAX requests that either contain sensitive information or modify something on the server are performed via POST, not GET (3 points)&lt;br /&gt;
#** Safe from XSS attacks; that is, all content is escaped on output (3 points)&lt;br /&gt;
#** Safe from SQL Injection attacks (2 points)&lt;br /&gt;
#** CSRF tokens are passed when editing or removing events (3 points)&lt;br /&gt;
#** Session cookie is HTTP-Only (3 points)&lt;br /&gt;
#** Page passes the W3C validator (2 points)&lt;br /&gt;
#** ''Extra Credit:'' Your code passes ''JSHint'' or ''JSLint'' (+3 bonus points)&lt;br /&gt;
#* '''''Usability (5 Points):'''''&lt;br /&gt;
#** Site is intuitive to use and navigate (4 points)&lt;br /&gt;
#** Site is visually appealing (1 point)&lt;br /&gt;
# '''Creative Portion (15 Points)'''&lt;br /&gt;
#* '''Additional Calendars Features (worth 15 points):''' Develop some additional features for the calendar, a few examples are provided below.&lt;br /&gt;
#**  Users can tag an event with a particular category and enable/disable those tags in the calendar view. (5 points)&lt;br /&gt;
#**  Users can share their calendar with additional users. (5 points)&lt;br /&gt;
#**  Users can create group events that display on multiple users calendars (5 points)&lt;br /&gt;
#*  '''Make sure to save a description of your creative portion, and a link to your server in your README.md file.'''&lt;br /&gt;
''* These points can be earned only if at least 3 other points have been earned in that category.  This is to prevent these points from being &amp;quot;free.&amp;quot;''&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 5]]&lt;br /&gt;
[[Category:Modules]]&lt;/div&gt;</summary>
		<author><name>Alex</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Module_4&amp;diff=2541</id>
		<title>Module 4</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Module_4&amp;diff=2541"/>
		<updated>2018-03-19T04:56:53Z</updated>

		<summary type="html">&lt;p&gt;Alex: /* Write some Regular Expressions */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;__NOTOC__&lt;br /&gt;
In Module 4, you will learn the fundamentals of Python, a popular scripting language, and Regular Expressions, which give you power in text processing.&lt;br /&gt;
&lt;br /&gt;
This article contains your assignments for Module 4.&lt;br /&gt;
&lt;br /&gt;
== Reading ==&lt;br /&gt;
&lt;br /&gt;
The following articles on the online class wiki textbook contain information that will help you complete the assignments.&lt;br /&gt;
&lt;br /&gt;
* [[Python]]&lt;br /&gt;
* [[Regular Expressions]]&lt;br /&gt;
&lt;br /&gt;
== Individual Assignments ==&lt;br /&gt;
&lt;br /&gt;
=== Learn Python and Regular Expressions ===&lt;br /&gt;
&lt;br /&gt;
Up to this point in CSE 330, you have used only one programming language: PHP.  In Module 4, you will learn a new language: Python.  Before starting this assignment, you should look over the [[Python|online textbook article about Python]].  You should be using version 3 (or greater) of Python. Additionally, you may find it helpful to look over the [[Regular Expressions|online textbook article about Regular Expressions]].&lt;br /&gt;
&lt;br /&gt;
=== Write some Regular Expressions ===&lt;br /&gt;
&lt;br /&gt;
Please write regular expressions that do each the following:&lt;br /&gt;
&lt;br /&gt;
# Match the substring &amp;quot;hello world&amp;quot; in a string.&lt;br /&gt;
# Find all words in an input string that contains three consecutive vowels, regardless of case.&lt;br /&gt;
# Match an input string that is '''entirely''' a flight code, of the format AA####, where '''AA''' is a two-letter uppercase airline code, and '''####''' is a three- or four-digit flight number.&lt;br /&gt;
Examples:&lt;br /&gt;
   Note: text in ''[[red]]'' is matched by the regular expression. Each line is a separate test input string.&lt;br /&gt;
   Regex 1:  Programmers will often write ''[[hello world]]'' as their first project with a programming language.&lt;br /&gt;
   Regex 2:  The ''[[gooey]]'' peanut butter and jelly sandwich was a ''[[beauty]]''.&lt;br /&gt;
   Regex 3:  ''[[AA312]]''&lt;br /&gt;
             ''[[AA1298]]''&lt;br /&gt;
             ''[[NW1234]]''&lt;br /&gt;
             ''[[US443]]''&lt;br /&gt;
             US31344&lt;br /&gt;
             AA123 extratext&lt;br /&gt;
&lt;br /&gt;
            &lt;br /&gt;
&lt;br /&gt;
Save your regexes to text files – one each.&lt;br /&gt;
&lt;br /&gt;
=== Baseball Stats Counter ===&lt;br /&gt;
&lt;br /&gt;
The St. Louis Cardinals are the most legendary baseball team in the national league.  In this exercise, you will be creating a Python script that reads box scores from a file and computes the Cardinals' players' batting averages in a particular season.&lt;br /&gt;
&lt;br /&gt;
==== Tips and Instructions ====&lt;br /&gt;
&lt;br /&gt;
* You should write a Python script file to solve this problem.&lt;br /&gt;
* You should use a regular expression to parse players' names, at-bats, hits, and runs from the input file.&lt;br /&gt;
* You may want to create a class to hold and compute information about each player.&lt;br /&gt;
* Your file should take one command-line argument: the path to an input file.  If no path is given, your program should print a usage message.&lt;br /&gt;
&lt;br /&gt;
==== Input ====&lt;br /&gt;
&lt;br /&gt;
Sample input files may be found here: http://classes.engineering.wustl.edu/cse330/content/cardinals/&lt;br /&gt;
&lt;br /&gt;
The top of the file contains a citation, and what follows is an entire season of Cardinals Baseball box scores.  Each game starts with a title; for example:&lt;br /&gt;
&lt;br /&gt;
 === St.Louis Cardinals vs. Chicago Cubs, 1940-04-19 ===&lt;br /&gt;
&lt;br /&gt;
What follows are the performance of each player in that game.  The format of each line is as follows:&lt;br /&gt;
&lt;br /&gt;
 XXX batted # times with # hits and # runs&lt;br /&gt;
&lt;br /&gt;
where '''XXX''' is the player's name (you may assume that the name is unique), and each '''#''' are integers representing the number of &amp;quot;at bats&amp;quot;, the number of &amp;quot;hits&amp;quot;, and the number of &amp;quot;runs&amp;quot;, respectively.&lt;br /&gt;
&lt;br /&gt;
==== Output ====&lt;br /&gt;
&lt;br /&gt;
Your script needs to output all players' batting average across the season.  A player's batting average is that player's total hits divided by that player's total at-bats throughout the entire season.  For example, Johnny Hopp was at bat 149 times in 1940, and he had 41 hits, so his batting average was 0.275.&lt;br /&gt;
&lt;br /&gt;
Each line in the output should have the format:&lt;br /&gt;
&lt;br /&gt;
 XXX: #.###&lt;br /&gt;
&lt;br /&gt;
where '''XXX''' is the player's name, and '''#.###''' is the player's batting average, '''rounded''' (not truncated) to three decimal places.&lt;br /&gt;
&lt;br /&gt;
The players should be sorted by batting average, with the highest batting average on top.  If two players have the exact same batting average (before rounding occurs), the order between those two players is unimportant.&lt;br /&gt;
&lt;br /&gt;
For example, the correct output for the 1940 season is:&lt;br /&gt;
&amp;lt;!-- Jimmy Brown was 0.280 and Ira Hutchinson was 0.125 --&amp;gt;&lt;br /&gt;
&amp;lt;source lang=&amp;quot;text&amp;quot;&amp;gt;&lt;br /&gt;
Pepper Martin: 0.316&lt;br /&gt;
Walker Cooper: 0.316&lt;br /&gt;
Johnny Mize: 0.314&lt;br /&gt;
Ernie Koy: 0.310&lt;br /&gt;
Enos Slaughter: 0.306&lt;br /&gt;
Joe Medwick: 0.304&lt;br /&gt;
Terry Moore: 0.304&lt;br /&gt;
Joe Orengo: 0.286&lt;br /&gt;
Jimmy Brown: 0.280&lt;br /&gt;
Marty Marion: 0.279&lt;br /&gt;
Don Gutteridge: 0.276&lt;br /&gt;
Johnny Hopp: 0.275&lt;br /&gt;
Creepy Crespi: 0.273&lt;br /&gt;
Mickey Owen: 0.265&lt;br /&gt;
Bill DeLancey: 0.250&lt;br /&gt;
Don Padgett: 0.242&lt;br /&gt;
Stu Martin: 0.238&lt;br /&gt;
Eddie Lake: 0.222&lt;br /&gt;
Hal Epps: 0.214&lt;br /&gt;
Lon Warneke: 0.209&lt;br /&gt;
Harry Walker: 0.185&lt;br /&gt;
Max Lanier: 0.179&lt;br /&gt;
Bill McGee: 0.178&lt;br /&gt;
Carl Doyle: 0.174&lt;br /&gt;
Mort Cooper: 0.157&lt;br /&gt;
Clyde Shoun: 0.145&lt;br /&gt;
Carden Gillenwater: 0.130&lt;br /&gt;
Bob Bowman: 0.067&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Grading ==&lt;br /&gt;
&lt;br /&gt;
We will be grading the following aspects of your work.  There are 50 points total.&lt;br /&gt;
&lt;br /&gt;
'''Assignments (including code) must be committed to Bitbucket by the end of class on the due date (commit early and often). Failing to commit by the end of class on the due date will result in a 0. ''' &lt;br /&gt;
&lt;br /&gt;
Upload your baseball code and a file with your Regular expressions.&lt;br /&gt;
&lt;br /&gt;
# '''Regular Expressions (15 Points):'''&lt;br /&gt;
#* '''Your regex files should contain your regex (with no delimiters) and nothing else.'''&lt;br /&gt;
#* Regular Expression 1 Correct and saved in a file named &amp;lt;code&amp;gt;regex1.txt&amp;lt;/code&amp;gt; (5 points)&lt;br /&gt;
#* Regular Expression 2 Correct and saved in a file named &amp;lt;code&amp;gt;regex2.txt&amp;lt;/code&amp;gt;(5 points)&lt;br /&gt;
#* Regular Expression 3 Correct and saved in a file named &amp;lt;code&amp;gt;regex3.txt&amp;lt;/code&amp;gt;(5 points)&lt;br /&gt;
# '''Baseball Stats Counter (35 Points):'''&lt;br /&gt;
#* Solution is written entirely in Python and saved in a file named &amp;lt;code&amp;gt;baseball.py&amp;lt;/code&amp;gt; (8 points)&lt;br /&gt;
#*: ''Note: Failing to write your code in Python 3 will result in losing, at a minimum, points for this category.''&lt;br /&gt;
#* Correct usage of one or more regular expressions to parse and extract data from each line of the input file (8 points)&lt;br /&gt;
#*: ''Note: You should not be using &amp;lt;code&amp;gt;str.split&amp;lt;/code&amp;gt; to extract data.''&lt;br /&gt;
#* Script prints a usage message if a command line argument is not present (4 points)&lt;br /&gt;
#*: ''Note: For an example of a usage message, see [https://en.wikipedia.org/wiki/Usage_message#Examples this link.]''&lt;br /&gt;
#* Output is correct for all test cases (15 points)&lt;br /&gt;
#*: ''This includes sorting and rounding.''&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 4]]&lt;br /&gt;
[[Category:Modules]]&lt;/div&gt;</summary>
		<author><name>Alex</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Module_4&amp;diff=2539</id>
		<title>Module 4</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Module_4&amp;diff=2539"/>
		<updated>2018-03-07T17:55:33Z</updated>

		<summary type="html">&lt;p&gt;Alex: /* Grading */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;__NOTOC__&lt;br /&gt;
In Module 4, you will learn the fundamentals of Python, a popular scripting language, and Regular Expressions, which give you power in text processing.&lt;br /&gt;
&lt;br /&gt;
This article contains your assignments for Module 4.&lt;br /&gt;
&lt;br /&gt;
== Reading ==&lt;br /&gt;
&lt;br /&gt;
The following articles on the online class wiki textbook contain information that will help you complete the assignments.&lt;br /&gt;
&lt;br /&gt;
* [[Python]]&lt;br /&gt;
* [[Regular Expressions]]&lt;br /&gt;
&lt;br /&gt;
== Individual Assignments ==&lt;br /&gt;
&lt;br /&gt;
=== Learn Python and Regular Expressions ===&lt;br /&gt;
&lt;br /&gt;
Up to this point in CSE 330, you have used only one programming language: PHP.  In Module 4, you will learn a new language: Python.  Before starting this assignment, you should look over the [[Python|online textbook article about Python]].  You should be using version 3 (or greater) of Python. Additionally, you may find it helpful to look over the [[Regular Expressions|online textbook article about Regular Expressions]].&lt;br /&gt;
&lt;br /&gt;
=== Write some Regular Expressions ===&lt;br /&gt;
&lt;br /&gt;
Please write regular expressions that do each the following:&lt;br /&gt;
&lt;br /&gt;
# Match the substring &amp;quot;hello world&amp;quot; in string.&lt;br /&gt;
# Find all words in an input string that contains three consecutive vowels, regardless of case.&lt;br /&gt;
# Match an input string that is '''entirely''' a flight code, of the format AA####, where '''AA''' is a two-letter uppercase airline code, and '''####''' is a three- or four-digit flight number.&lt;br /&gt;
Examples:&lt;br /&gt;
   Note: text in ''[[red]]'' is matched by the regular expression. Each line is a separate test input string.&lt;br /&gt;
   Regex 1:  Programmers will often write ''[[hello world]]'' as their first project with a programming language.&lt;br /&gt;
   Regex 2:  The ''[[gooey]]'' peanut butter and jelly sandwich was a ''[[beauty]]''.&lt;br /&gt;
   Regex 3:  ''[[AA312]]''&lt;br /&gt;
             ''[[AA1298]]''&lt;br /&gt;
             ''[[NW1234]]''&lt;br /&gt;
             ''[[US443]]''&lt;br /&gt;
             US31344&lt;br /&gt;
             AA123 extratext&lt;br /&gt;
&lt;br /&gt;
            &lt;br /&gt;
&lt;br /&gt;
Save your regexes to text files – one each.&lt;br /&gt;
&lt;br /&gt;
=== Baseball Stats Counter ===&lt;br /&gt;
&lt;br /&gt;
The St. Louis Cardinals are the most legendary baseball team in the national league.  In this exercise, you will be creating a Python script that reads box scores from a file and computes the Cardinals' players' batting averages in a particular season.&lt;br /&gt;
&lt;br /&gt;
==== Tips and Instructions ====&lt;br /&gt;
&lt;br /&gt;
* You should write a Python script file to solve this problem.&lt;br /&gt;
* You should use a regular expression to parse players' names, at-bats, hits, and runs from the input file.&lt;br /&gt;
* You may want to create a class to hold and compute information about each player.&lt;br /&gt;
* Your file should take one command-line argument: the path to an input file.  If no path is given, your program should print a usage message.&lt;br /&gt;
&lt;br /&gt;
==== Input ====&lt;br /&gt;
&lt;br /&gt;
Sample input files may be found here: http://classes.engineering.wustl.edu/cse330/content/cardinals/&lt;br /&gt;
&lt;br /&gt;
The top of the file contains a citation, and what follows is an entire season of Cardinals Baseball box scores.  Each game starts with a title; for example:&lt;br /&gt;
&lt;br /&gt;
 === St.Louis Cardinals vs. Chicago Cubs, 1940-04-19 ===&lt;br /&gt;
&lt;br /&gt;
What follows are the performance of each player in that game.  The format of each line is as follows:&lt;br /&gt;
&lt;br /&gt;
 XXX batted # times with # hits and # runs&lt;br /&gt;
&lt;br /&gt;
where '''XXX''' is the player's name (you may assume that the name is unique), and each '''#''' are integers representing the number of &amp;quot;at bats&amp;quot;, the number of &amp;quot;hits&amp;quot;, and the number of &amp;quot;runs&amp;quot;, respectively.&lt;br /&gt;
&lt;br /&gt;
==== Output ====&lt;br /&gt;
&lt;br /&gt;
Your script needs to output all players' batting average across the season.  A player's batting average is that player's total hits divided by that player's total at-bats throughout the entire season.  For example, Johnny Hopp was at bat 149 times in 1940, and he had 41 hits, so his batting average was 0.275.&lt;br /&gt;
&lt;br /&gt;
Each line in the output should have the format:&lt;br /&gt;
&lt;br /&gt;
 XXX: #.###&lt;br /&gt;
&lt;br /&gt;
where '''XXX''' is the player's name, and '''#.###''' is the player's batting average, '''rounded''' (not truncated) to three decimal places.&lt;br /&gt;
&lt;br /&gt;
The players should be sorted by batting average, with the highest batting average on top.  If two players have the exact same batting average (before rounding occurs), the order between those two players is unimportant.&lt;br /&gt;
&lt;br /&gt;
For example, the correct output for the 1940 season is:&lt;br /&gt;
&amp;lt;!-- Jimmy Brown was 0.280 and Ira Hutchinson was 0.125 --&amp;gt;&lt;br /&gt;
&amp;lt;source lang=&amp;quot;text&amp;quot;&amp;gt;&lt;br /&gt;
Pepper Martin: 0.316&lt;br /&gt;
Walker Cooper: 0.316&lt;br /&gt;
Johnny Mize: 0.314&lt;br /&gt;
Ernie Koy: 0.310&lt;br /&gt;
Enos Slaughter: 0.306&lt;br /&gt;
Joe Medwick: 0.304&lt;br /&gt;
Terry Moore: 0.304&lt;br /&gt;
Joe Orengo: 0.286&lt;br /&gt;
Jimmy Brown: 0.280&lt;br /&gt;
Marty Marion: 0.279&lt;br /&gt;
Don Gutteridge: 0.276&lt;br /&gt;
Johnny Hopp: 0.275&lt;br /&gt;
Creepy Crespi: 0.273&lt;br /&gt;
Mickey Owen: 0.265&lt;br /&gt;
Bill DeLancey: 0.250&lt;br /&gt;
Don Padgett: 0.242&lt;br /&gt;
Stu Martin: 0.238&lt;br /&gt;
Eddie Lake: 0.222&lt;br /&gt;
Hal Epps: 0.214&lt;br /&gt;
Lon Warneke: 0.209&lt;br /&gt;
Harry Walker: 0.185&lt;br /&gt;
Max Lanier: 0.179&lt;br /&gt;
Bill McGee: 0.178&lt;br /&gt;
Carl Doyle: 0.174&lt;br /&gt;
Mort Cooper: 0.157&lt;br /&gt;
Clyde Shoun: 0.145&lt;br /&gt;
Carden Gillenwater: 0.130&lt;br /&gt;
Bob Bowman: 0.067&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Grading ==&lt;br /&gt;
&lt;br /&gt;
We will be grading the following aspects of your work.  There are 50 points total.&lt;br /&gt;
&lt;br /&gt;
'''Assignments (including code) must be committed to Bitbucket by the end of class on the due date (commit early and often). Failing to commit by the end of class on the due date will result in a 0. ''' &lt;br /&gt;
&lt;br /&gt;
Upload your baseball code and a file with your Regular expressions.&lt;br /&gt;
&lt;br /&gt;
# '''Regular Expressions (15 Points):'''&lt;br /&gt;
#* '''Your regex files should contain your regex (with no delimiters) and nothing else.'''&lt;br /&gt;
#* Regular Expression 1 Correct and saved in a file named &amp;lt;code&amp;gt;regex1.txt&amp;lt;/code&amp;gt; (5 points)&lt;br /&gt;
#* Regular Expression 2 Correct and saved in a file named &amp;lt;code&amp;gt;regex2.txt&amp;lt;/code&amp;gt;(5 points)&lt;br /&gt;
#* Regular Expression 3 Correct and saved in a file named &amp;lt;code&amp;gt;regex3.txt&amp;lt;/code&amp;gt;(5 points)&lt;br /&gt;
# '''Baseball Stats Counter (35 Points):'''&lt;br /&gt;
#* Solution is written entirely in Python and saved in a file named &amp;lt;code&amp;gt;baseball.py&amp;lt;/code&amp;gt; (8 points)&lt;br /&gt;
#*: ''Note: Failing to write your code in Python 3 will result in losing, at a minimum, points for this category.''&lt;br /&gt;
#* Correct usage of one or more regular expressions to parse and extract data from each line of the input file (8 points)&lt;br /&gt;
#*: ''Note: You should not be using &amp;lt;code&amp;gt;str.split&amp;lt;/code&amp;gt; to extract data.''&lt;br /&gt;
#* Script prints a usage message if a command line argument is not present (4 points)&lt;br /&gt;
#*: ''Note: For an example of a usage message, see [https://en.wikipedia.org/wiki/Usage_message#Examples this link.]''&lt;br /&gt;
#* Output is correct for all test cases (15 points)&lt;br /&gt;
#*: ''This includes sorting and rounding.''&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 4]]&lt;br /&gt;
[[Category:Modules]]&lt;/div&gt;</summary>
		<author><name>Alex</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Module_5&amp;diff=2538</id>
		<title>Module 5</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Module_5&amp;diff=2538"/>
		<updated>2018-03-03T22:56:36Z</updated>

		<summary type="html">&lt;p&gt;Alex: /* Grading */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;__NOTOC__&lt;br /&gt;
In Module 5, you will learn JavaScript, the dominant client-side web language.  JavaScript is the third and final programming language you will learn in CSE 330.&lt;br /&gt;
&lt;br /&gt;
This article contains your assignments for Module 5.&lt;br /&gt;
&lt;br /&gt;
'''Warning:'''&lt;br /&gt;
&lt;br /&gt;
''This module takes students a while. It is strongly recommended that you start early and ask questions as they come up.''&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Reading ==&lt;br /&gt;
&lt;br /&gt;
The following articles on the online class wiki textbook contain information that will help you complete the assignments.&lt;br /&gt;
&lt;br /&gt;
* [[JavaScript]]&lt;br /&gt;
* [[AJAX and JSON]]&lt;br /&gt;
* [[jQuery]]&lt;br /&gt;
* [[Web Application Security, Part 3]]&lt;br /&gt;
&lt;br /&gt;
== Individual Assignments ==&lt;br /&gt;
&lt;br /&gt;
'''''IMPORTANT:'' Both of the individual assignments must be completed ''without'' using a JavaScript library like jQuery.'''  However, you may (and should) use jQuery for the group portion.&lt;br /&gt;
&lt;br /&gt;
=== JavaScript Calculator ===&lt;br /&gt;
&lt;br /&gt;
In Module 2, you made a calculator using PHP.  Now you will be making one using JavaScript.&lt;br /&gt;
&lt;br /&gt;
* The web page should have two input fields and a radio button group for the operation, with the 4 basic math operations represented (add, subtract, multiply, divide).&lt;br /&gt;
* JavaScript should monitor all three fields and display the current result whenever the user changes any value in any field, without refreshing the page.&lt;br /&gt;
*: '''Tip 1:''' Consider using either the ''change'' or the ''keyup'' event on the text fields, and either the ''change'' or the ''click'' event on the radio buttons.&lt;br /&gt;
*: '''Tip 2:''' Re-read [[JavaScript|the JavaScript guide]] if you need help figuring our how to bind callback functions to events, or how to determine which radio button is currently selected.  (There are examples for both of these!)&lt;br /&gt;
* The calculator should be completely self-contained; i.e., you should not be making any requests to any other server-side or client-side scripts or web pages after the initial page load.&lt;br /&gt;
&lt;br /&gt;
'''Tip:''' You can embed JavaScript code into an HTML document like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;script type=&amp;quot;text/javascript&amp;quot;&amp;gt;&lt;br /&gt;
// your code here&lt;br /&gt;
&amp;lt;/script&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Tip:''' If your code isn't working the way you expect, use a JavaScript error console.  In Chrome, for example, press Ctrl-Shift-I (or Cmd-Option-I) to open the WebKit inspector.&lt;br /&gt;
&lt;br /&gt;
'''Important:''' It is best practice to fully separate the content, appearance, and behavior.  In previous modules, you may have lost points for using HTML tags that change the appearance of things &amp;lt;nowiki&amp;gt;(like &amp;lt;center&amp;gt; and &amp;lt;font&amp;gt;).&amp;lt;/nowiki&amp;gt;  In this module, make sure that you define your event listeners in JavaScript as in &amp;lt;code&amp;gt;document.getElementById(&amp;quot;xyz&amp;quot;).addEventListener(...)&amp;lt;/code&amp;gt; and '''''not''''' in the HTML like &amp;lt;code&amp;gt;&amp;lt;button onclick=&amp;quot;badExample();&amp;quot;&amp;gt;Bad Example&amp;lt;/button&amp;gt;&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== Weather Widget ===&lt;br /&gt;
&lt;br /&gt;
In this section, you will make a web page that displays the weather forecast using AJAX requests to a weather server.&lt;br /&gt;
&lt;br /&gt;
# Make an empty HTML document; name it '''weather.html'''&lt;br /&gt;
#: Refer to the [[HTML and CSS]] guide for the skeleton of an HTML document&lt;br /&gt;
# Define a function in JavaScript; call it '''fetchWeather()'''.  You may write your JavaScript in an embedded script in your HTML document.&lt;br /&gt;
# Inside your '''fetchWeather()''' function, make an AJAX request to the weather server.&lt;br /&gt;
#: We have a server that outputs the current weather in JSON format.  The format is documented in the [[#JSON Structure]] section below.&lt;br /&gt;
#: '''URL:''' https://classes.engineering.wustl.edu/cse330/content/weather_json.php&lt;br /&gt;
#: We kindly thank Yahoo Weather for providing us with up-to-date weather information.&lt;br /&gt;
#* '''IMPORTANT:''' Under normal circumstances, AJAX requests ''cannot'' be performed cross-domain for security reasons.  We have set the &amp;lt;code&amp;gt;Access-Control-Allow-Origin&amp;lt;/code&amp;gt; header on our server to allow requests from your EC2 instances, or from localhost.  '''You will therefore need to upload your code to your EC2, or access it via localhost, in order for the AJAX requests to work.'''  This means that you cannot, for example, complete this part of the individual portion in JSFiddle.&lt;br /&gt;
# In your callback, process the JSON and use JavaScript to manipulate the HTML DOM to display the following information on your page:&lt;br /&gt;
#* Location&lt;br /&gt;
#** City, in a &amp;lt;nowiki&amp;gt;&amp;lt;strong&amp;gt;&amp;lt;/nowiki&amp;gt; tag&lt;br /&gt;
#** State, not in any tag&lt;br /&gt;
#* Humidity&lt;br /&gt;
#* Current Temperature&lt;br /&gt;
#* Image for Tomorrow's Forecast (see [[#Weather Condition Images]] below for more information)&lt;br /&gt;
#* Image for the Day After Tomorrow's Forecast&lt;br /&gt;
# Finally, bind '''fetchWeather()''' to the DOMContentLoaded event so that your weather widget is automatically initialized when the page is loaded:&lt;br /&gt;
#: &amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;document.addEventListener(&amp;quot;DOMContentLoaded&amp;quot;, fetchWeather, false);&amp;lt;/source&amp;gt;&lt;br /&gt;
# In addition, add a button that runs your ''fetchWeather'' function when clicked.  This should update your widget with the current weather conditions.&lt;br /&gt;
&lt;br /&gt;
Use the following HTML:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;div class=&amp;quot;weather&amp;quot; id=&amp;quot;weatherWidget&amp;quot;&amp;gt;&lt;br /&gt;
	&amp;lt;div class=&amp;quot;weather-loc&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
	&amp;lt;div class=&amp;quot;weather-humidity&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
	&amp;lt;div class=&amp;quot;weather-temp&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
	&amp;lt;img class=&amp;quot;weather-tomorrow&amp;quot; /&amp;gt;&lt;br /&gt;
	&amp;lt;img class=&amp;quot;weather-dayaftertomorrow&amp;quot; /&amp;gt;&lt;br /&gt;
&amp;lt;/div&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Include the CSS file from here: http://classes.engineering.wustl.edu/cse330/content/weather.css&lt;br /&gt;
&lt;br /&gt;
When everything is working, the weather widget should look something like this:&lt;br /&gt;
&lt;br /&gt;
[[File:WeatherWidget.png]]&lt;br /&gt;
&lt;br /&gt;
'''Important:''' The widget in this section needs to work in only Firefox and Chrome.  It does '''''not''''' need to work Internet Explorer.&lt;br /&gt;
&lt;br /&gt;
==== Tips ====&lt;br /&gt;
&lt;br /&gt;
===== JSON Structure =====&lt;br /&gt;
&lt;br /&gt;
The JSON from our server looks like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
{&lt;br /&gt;
   &amp;quot;updated&amp;quot;: &amp;quot;Thu, 11 Oct 2012 5:54 pm CDT&amp;quot;,&lt;br /&gt;
   &amp;quot;location&amp;quot;: {&lt;br /&gt;
      &amp;quot;city&amp;quot;: &amp;quot;St. Louis&amp;quot;,&lt;br /&gt;
      &amp;quot;state&amp;quot;: &amp;quot;MO&amp;quot;&lt;br /&gt;
   },&lt;br /&gt;
   &amp;quot;wind&amp;quot;: {&lt;br /&gt;
      &amp;quot;chill&amp;quot;: &amp;quot;62&amp;quot;,&lt;br /&gt;
      &amp;quot;direction&amp;quot;: &amp;quot;150&amp;quot;,&lt;br /&gt;
      &amp;quot;speed&amp;quot;: &amp;quot;3 mph&amp;quot;&lt;br /&gt;
   },&lt;br /&gt;
   &amp;quot;atmosphere&amp;quot;: {&lt;br /&gt;
      &amp;quot;humidity&amp;quot;: &amp;quot;50&amp;quot;,&lt;br /&gt;
      &amp;quot;visibility&amp;quot;: &amp;quot;10&amp;quot;,&lt;br /&gt;
      &amp;quot;pressure&amp;quot;: &amp;quot;30.12 in&amp;quot;&lt;br /&gt;
   },&lt;br /&gt;
   &amp;quot;current&amp;quot;: {&lt;br /&gt;
      &amp;quot;code&amp;quot;: &amp;quot;28&amp;quot;,&lt;br /&gt;
      &amp;quot;text&amp;quot;: &amp;quot;Mostly Cloudy&amp;quot;,&lt;br /&gt;
      &amp;quot;temp&amp;quot;: &amp;quot;62°F&amp;quot;,&lt;br /&gt;
      &amp;quot;date&amp;quot;: &amp;quot;Thu, 11 Oct 2012 5:54 pm CDT&amp;quot;&lt;br /&gt;
   },&lt;br /&gt;
   &amp;quot;tomorrow&amp;quot;: {&lt;br /&gt;
      &amp;quot;code&amp;quot;: &amp;quot;29&amp;quot;,&lt;br /&gt;
      &amp;quot;text&amp;quot;: &amp;quot;Clouds Early/Clearing Late&amp;quot;,&lt;br /&gt;
      &amp;quot;low&amp;quot;: &amp;quot;45°F&amp;quot;,&lt;br /&gt;
      &amp;quot;high&amp;quot;: &amp;quot;61°F&amp;quot;&lt;br /&gt;
   },&lt;br /&gt;
   &amp;quot;dayafter&amp;quot;: {&lt;br /&gt;
      &amp;quot;code&amp;quot;: &amp;quot;30&amp;quot;,&lt;br /&gt;
      &amp;quot;text&amp;quot;: &amp;quot;Partly Cloudy&amp;quot;,&lt;br /&gt;
      &amp;quot;low&amp;quot;: &amp;quot;53°F&amp;quot;,&lt;br /&gt;
      &amp;quot;high&amp;quot;: &amp;quot;65°F&amp;quot;&lt;br /&gt;
   },&lt;br /&gt;
   &amp;quot;credit&amp;quot;: &amp;quot;http://us.rd.yahoo.com/dailynews/rss/weather/St._Louis__MO/*http://weather.yahoo.com/forecast/USMO0170_f.html&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===== Weather Condition Images =====&lt;br /&gt;
&lt;br /&gt;
Each day's forecast has a code.  There are images associated with these codes.&lt;br /&gt;
&lt;br /&gt;
One place to get the images is from here: &amp;lt;nowiki&amp;gt;http://us.yimg.com/i/us/nws/weather/gr/&amp;lt;/nowiki&amp;gt;'''##'''&amp;lt;nowiki&amp;gt;ds.png&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Replace the '''##''' with the forecast code.  For example, for code 32, the URL would be: http://us.yimg.com/i/us/nws/weather/gr/32ds.png&lt;br /&gt;
&lt;br /&gt;
== Group Project ==&lt;br /&gt;
&lt;br /&gt;
I forgot if I already mentioned this, but '''start early on this project!''' It will take longer than you think, I promise!&lt;br /&gt;
&lt;br /&gt;
You are encouraged to use the advanced version control practices you learned in Module 5 when completing this assignment.&lt;br /&gt;
&lt;br /&gt;
=== Calendar ===&lt;br /&gt;
&lt;br /&gt;
Build a simple calendar that allows users to add and remove events dynamically.&lt;br /&gt;
&lt;br /&gt;
You will use JavaScript to process user interactions at the web browser, without ever refreshing the browser after the initial web page load.  You may use a JavaScript library of your choice, including Ext JS.&lt;br /&gt;
&lt;br /&gt;
Your application should utilize AJAX to run server-side scripts that query your database to save and retrieve information, including user accounts and events.&lt;br /&gt;
&lt;br /&gt;
We have also written some functions to help you get started: [[JavaScript Calendar Library]]&lt;br /&gt;
&lt;br /&gt;
==== Examples ====&lt;br /&gt;
&lt;br /&gt;
* https://calendar.google.com/&lt;br /&gt;
* http://www.zoho.com/calendar/&lt;br /&gt;
&lt;br /&gt;
==== Server Side Language ====&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Additionally, you may use a database of your choice.  MySQL is probably the logical choice since you have been using it since Module 2, but you are free to explore other databases if you like.&lt;br /&gt;
&lt;br /&gt;
==== Requirements ====&lt;br /&gt;
&lt;br /&gt;
* Support a month-by-month view of the calendar.&lt;br /&gt;
*: Show one month at a time, with buttons to move forward or backward.&lt;br /&gt;
*: There should be no limit to how far forward or backward the user can go.&lt;br /&gt;
* Users can register and log in to the website.&lt;br /&gt;
*: You may leverage your MySQL project code and database from module 3 to get started.&lt;br /&gt;
* Unregistered users should see no events on the calendar.&lt;br /&gt;
* Registered users can add events.&lt;br /&gt;
*: All events should have a date and time, but do not need to have a duration.&lt;br /&gt;
*: You do ''not'' need to support recurring events (where you add an event that repeats, for example, every monday).&lt;br /&gt;
* Registered users see only events that they have added.&lt;br /&gt;
*: Your AJAX should not ask the server for events from a certain username.  Instead, your AJAX should ask the server for events, and the server should respond with the events for only the currently-logged-in user (from the session).  Can you think of why?&lt;br /&gt;
* Registered users can delete their events, but not the events of others.&lt;br /&gt;
*: Again, the server should delete events based on the username present in the session.  (If it deletes only based on an Event ID, an attacker could feed any arbitrary Event ID to your server, even if he/she didn't own that event.)&lt;br /&gt;
* All user and event data should be kept in a database.&lt;br /&gt;
* At no time should the main page need to be reloaded.&lt;br /&gt;
*: User registration, user authentication, event addition, and event deletion should all be handled by JavaScript and AJAX requests to your server.&lt;br /&gt;
* Your page needs to work in the versions of Firefox and Chrome installed on the lab computers.&lt;br /&gt;
&lt;br /&gt;
'''Tip:''' Run your database schema by a TA before implementing it.&lt;br /&gt;
&lt;br /&gt;
=== Web Security and Validation ===&lt;br /&gt;
&lt;br /&gt;
Your project needs to demonstrate that thought was put into web security and best practice.  For more information, see this week's Web Application Security guide: [[Web Application Security, Part 3]]&lt;br /&gt;
&lt;br /&gt;
In particular:&lt;br /&gt;
&lt;br /&gt;
* '''Your application needs to prevent XSS attacks.'''  Be careful when transmitting data over JSON that will be reflected in an event title!  (Note: JSON data should be sanitized on the client side, not the server side.)&lt;br /&gt;
* '''Perform precautionary measures to prevent session hijacking attacks.'''&lt;br /&gt;
*: You should specify your session cookie to be HTTP-Only.  However, for the means of this module, you need not test for user agent consistency.&lt;br /&gt;
* '''Optional:''' Validate your JavaScript code using [http://www.jshint.com/ JSHint] '''''or''''' [http://jslint.com/ JSLint] for up to 3 points of extra credit.&lt;br /&gt;
&lt;br /&gt;
You should continue the practices that you have learned in past weeks:&lt;br /&gt;
&lt;br /&gt;
* Pass tokens in forms to prevent CSRF attacks.&lt;br /&gt;
*: '''Hint:''' You will need to send your CSRF tokens in your AJAX requests.  Remember that AJAX still submits forms and runs server-side scripts, just like the vanilla forms you've been using in Modules 2 and 3.&lt;br /&gt;
* Use prepared queries to prevent SQL Injection attacks.&lt;br /&gt;
* If storing passwords in a database, always store them salted and encrypted.&lt;br /&gt;
* Your page should validate with no errors through the W3C validator.&lt;br /&gt;
&lt;br /&gt;
== Grading ==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
We will be grading the following aspects of your work.  There are 100 points total.&lt;br /&gt;
&lt;br /&gt;
'''Assignments (including code) must be committed to Bitbucket by the end of class on the due date (commit early and often). Failing to commit by the end of class on the due date will result in a 0. ''' &lt;br /&gt;
&lt;br /&gt;
If you do not include a link to your group portion running on your instance in your group portion README.md, you will receive a 0 for the group portion&lt;br /&gt;
_________&lt;br /&gt;
&lt;br /&gt;
# '''JavaScript Calculator (10 Points):'''&lt;br /&gt;
#* Calculator successfully adds, subtracts, multiplies, and divides numbers (3 points)&lt;br /&gt;
#* The result is automatically computed when a value in either field is changed (3 points)&lt;br /&gt;
#* Calculator is written entirely in pure, conventional JavaScript with no external libraries (4 points)*&lt;br /&gt;
#*: ''Note: be sure to fully separate content, appearance, and behavior.  This means that you should '''not''' use the event attributes on the HTML elements like onclick, onchange, and onkeyup.''&lt;br /&gt;
# '''Weather Widget (15 Points):'''&lt;br /&gt;
#* Widget performs an AJAX request to fetch the current weather (4 points)&lt;br /&gt;
#* The HTML template is filled with the correct information, including an image (4 points)&lt;br /&gt;
#* Button to reload the weather widget (2 points)&lt;br /&gt;
#* Widget is written entirely in pure, conventional JavaScript with no external libraries (5 points)*&lt;br /&gt;
# '''AJAX Calendar (60 Points):'''&lt;br /&gt;
#* '''''Calendar View (10 Points):'''''&lt;br /&gt;
#** The calendar is displayed as a table grid with days as the columns and weeks as the rows, one month at a time (5 points)&lt;br /&gt;
#** The user can view different months as far in the past or future as desired (5 points)&lt;br /&gt;
#* '''''User and Event Management (25 Points):'''''&lt;br /&gt;
#** Events can be added, modified, and deleted (5 points)&lt;br /&gt;
#** Events have a title, date, and time (2 points)&lt;br /&gt;
#** Users can log into the site, and they cannot view or manipulate events associated with other users (8 points)&lt;br /&gt;
#**: ''Don't fall into the Abuse of Functionality trap!  Check user credentials on the server side as well as on the client side.''&lt;br /&gt;
#** All actions are performed over AJAX, without ever needing to reload the page (10 points)&lt;br /&gt;
#* '''''Best Practices (20 Points):'''''&lt;br /&gt;
#** Code is well formatted and easy to read, with proper commenting (2 points)&lt;br /&gt;
#** If storing passwords, they are stored salted and encrypted (2 points)&lt;br /&gt;
#** All AJAX requests that either contain sensitive information or modify something on the server are performed via POST, not GET (3 points)&lt;br /&gt;
#** Safe from XSS attacks; that is, all content is escaped on output (3 points)&lt;br /&gt;
#** Safe from SQL Injection attacks (2 points)&lt;br /&gt;
#** CSRF tokens are passed when editing or removing events (3 points)&lt;br /&gt;
#** Session cookie is HTTP-Only (3 points)&lt;br /&gt;
#** Page passes the W3C validator (2 points)&lt;br /&gt;
#** ''Extra Credit:'' Your code passes ''JSHint'' or ''JSLint'' (+3 bonus points)&lt;br /&gt;
#* '''''Usability (5 Points):'''''&lt;br /&gt;
#** Site is intuitive to use and navigate (4 points)&lt;br /&gt;
#** Site is visually appealing (1 point)&lt;br /&gt;
# '''Creative Portion (15 Points)'''&lt;br /&gt;
#* '''Additional Calendars Features (worth 15 points):''' Develop some additional features for the calendar, a few examples are provided below.&lt;br /&gt;
#**  Users can tag an event with a particular category and enable/disable those tags in the calendar view. (5 points)&lt;br /&gt;
#**  Users can share their calendar with additional users. (5 points)&lt;br /&gt;
#**  Users can create group events that display on multiple users calendars (5 points)&lt;br /&gt;
#*  '''Make sure to save a description of your creative portion, and a link to your server in your README.md file.'''&lt;br /&gt;
''* These points can be earned only if at least 3 other points have been earned in that category.  This is to prevent these points from being &amp;quot;free.&amp;quot;''&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 5]]&lt;br /&gt;
[[Category:Modules]]&lt;/div&gt;</summary>
		<author><name>Alex</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Web_Application_Security,_Part_2&amp;diff=2537</id>
		<title>Web Application Security, Part 2</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Web_Application_Security,_Part_2&amp;diff=2537"/>
		<updated>2018-02-25T20:26:59Z</updated>

		<summary type="html">&lt;p&gt;Alex: /* Example */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This is Part 2 of the Web Application Security article, geared toward the material covered in [[Module 3]].  For material covered in [[Module 2]] (HTML, CSS, and PHP), see [[Web Application Security, Part 1]]. For material covered in [[Module 6]] (JavaScript), see [[Web Application Security, Part 3]].&lt;br /&gt;
&lt;br /&gt;
== Password Security ==&lt;br /&gt;
&lt;br /&gt;
Let's assume for a moment that despite all of your efforts in the other fronts of web security, an attacker was still able to extract information from your database.  If you store your passwords as plain text, not only will the attacker be able to log in as whomever he chooses, but the attacker will ''also'' likely be able to log in as the users of your site on different sites (since many users employ the same password on several different web sites).&lt;br /&gt;
&lt;br /&gt;
=== Hashing ===&lt;br /&gt;
&lt;br /&gt;
In cryptography, a ''hash function'' is a function which maps an input to an output in a way that is (hopefully) impossible to undo.&lt;br /&gt;
In other words, if you have the hashed version of a password and you want to figure out what password could've been used to create it, your only option is to try every possible password until one matches. With a secure hash function and strong password, that process will take many millions of years.&lt;br /&gt;
&lt;br /&gt;
In web development, you should '''always''' store the hashed version of passwords.  What this means is that you feed a string of text (a password) to a hash function, and that hash function returns another string of text that is a ''digest'' or ''hash'' of the password, and that ''digest'' is what you'll store in your database. The reason we use them is so that, if someone evil ever gains access to your database, they won't be able to easily figure out what passwords your users used for your website. People tend to reuse passwords, so a breach at your site could easily become a breach at other sites, too.&lt;br /&gt;
&lt;br /&gt;
An important thing to note is that cryptographic hashes always have constant length, meaning that, in your database, you should be using a field of a fixed length to store them if you're using a fixed hashing algorithm. Because you're only storing the hashed version of a password, and not the original, it doesn't matter to you how big the original password was; you don't have to store it! As a result, if you ever see a website that limits your password to, say, 20 characters, that's a good sign that they're insecurely storing your password in plaintext.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Now, hashing is very important, but, by itself, it can be vulnerable to precomputation attacks, because a given string will always hash to the same value. In other words, an attacker could assemble a list of common passwords and their hashes, and simply look for those hashes in your database, saving them the work of trying to break each hash individually. To defend against such attacks, hashing algorithms can be used with so-called ''salts'' to increase their security. What this means is that the string to be hashed is modified using a randomly generated chunk of data called a ''salt'' before the hashing takes place. The salt is stored with the hash in the database, and, when a user enters their password, it is combined with the salt before the hash function is applied. The resulting hash defeats precomputation attacks, because it means that a given password no longer hashes to the same value across multiple databases, but as long as you're hashing the same string with the same salt, you'll always get the same results.&lt;br /&gt;
&lt;br /&gt;
[[File:xkcd_221.png|xkcd 221]]&lt;br /&gt;
&lt;br /&gt;
=== Solution ===&lt;br /&gt;
&lt;br /&gt;
So, the solution is to store salted, hashed passwords in your database.  PHP provides the [https://secure.php.net/manual/en/function.password-hash.php password-hash()] function to do this for you.&lt;br /&gt;
&lt;br /&gt;
'''&amp;lt;code&amp;gt;password_hash&amp;lt;/code&amp;gt; is only available in PHP 5.5 or newer.'''&lt;br /&gt;
&lt;br /&gt;
Note that, as part of generating a more secure hash, &amp;lt;code&amp;gt;password_hash&amp;lt;/code&amp;gt; will output a longer hash, so make sure your database field is large enough to hold the whole hash - as of PHP 5.6, 61 characters or larger will do the trick.&lt;br /&gt;
&lt;br /&gt;
How does they work?  They're both automagical functions that use a random salt and hash your password. &amp;lt;code&amp;gt;password_hash&amp;lt;/code&amp;gt; Takes two arguments: the string to hash and a constant representing the hashing algorithm to use.  Let's look at a few examples.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;php&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;?php&lt;br /&gt;
&lt;br /&gt;
echo password_hash(&amp;quot;Hello World&amp;quot;, PASSWORD_BCRYPT);&lt;br /&gt;
/*&lt;br /&gt;
 * The above line prints, for example: $2y$10$hfd4bRj2w2shMdxVZc7MEu3uZoXU7CNUEmUhWCEJB11xO8vTc8ply&lt;br /&gt;
 * This line is of the format:   $2$random-salt$hashed-password&lt;br /&gt;
 * Note that the actual hash generated will be different if you run this, because of a different random salt.&lt;br /&gt;
 */&lt;br /&gt;
?&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
As you can see from the above example, '''The functions generate a string that contains ''both'' a random salt ''and'' the hashed password.'''&lt;br /&gt;
&lt;br /&gt;
====Password Storage====&lt;br /&gt;
You should store the constant-length value in a &amp;lt;code&amp;gt;CHAR&amp;lt;/code&amp;gt; field in your database, and then have just one field for both the password and the salt.&lt;br /&gt;
&lt;br /&gt;
A note about &amp;lt;code&amp;gt;password_hash&amp;lt;/code&amp;gt;: If you always want to use the latest recommended hashing algorithm, you can specify PASSWORD_DEFAULT as your&lt;br /&gt;
hashing algorithm. As of PHP 7 and below, &amp;lt;code&amp;gt;PASSWORD_DEFAULT&amp;lt;/code&amp;gt; is equivalent to &amp;lt;code&amp;gt;PASSWORD_BCRYPT&amp;lt;/code&amp;gt;, but that may change in future versions. Because it's possible that a future hashing algorithm may produce larger hashes than BCrypt does, the maintainers of PHP recommend you use a field that can handle hashes of up to 255 characters in length. '''If, and only if you choose to use &amp;lt;code&amp;gt;PASSWORD_DEFAULT&amp;lt;/code&amp;gt;, you may use a variable-length field that can hold 255 characters to store your hashes.''' In MySQL, for example, a field of type &amp;lt;code&amp;gt;VARCHAR(255)&amp;lt;/code&amp;gt; would be acceptable here. However, because (during the timeframe of this class) there will not be any changes to the hashing algorithms used, you may still use a fixed-length field.&lt;br /&gt;
&lt;br /&gt;
=== Checking Passwords ===&lt;br /&gt;
To check a password, one might simply compare the hash of the password a user inputs against the hash stored in your database using normal string comparison (i.e. the == operator). If they're the same, you're all set. Simple enough, right? Wrong. The fact is, security is really, really hard, and there are lots of things you have to be aware of in a security context that you don't normally need to worry about.&lt;br /&gt;
&lt;br /&gt;
In this case, the == operator exposes you to what's called a timing attack. The string comparison algorithm used by == returns false as soon as a character is different in the two strings, meaning that, if the two strings have a different first character, it will return earlier than if they have a different last character. Normally, this is a good thing; it makes your code run faster. In this context, though, it's a bad thing, because an attacker can time how long the function takes to run, and, using that information, guess the characters of the string.&lt;br /&gt;
&lt;br /&gt;
As an extra bit of fun, the == operator exhibits some behavior that's less than intuitive.&lt;br /&gt;
&lt;br /&gt;
Try to guess what the output would be if you were to run the following code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;php&amp;quot;&amp;gt;&lt;br /&gt;
$a = &amp;quot;0e153958235710973524115407854157&amp;quot;;&lt;br /&gt;
$b = &amp;quot;0e015339760548602306096794382326&amp;quot;;&lt;br /&gt;
if ($a == $b) {&lt;br /&gt;
    echo &amp;quot;Passwords Match!&amp;quot;;&lt;br /&gt;
} else {&lt;br /&gt;
    echo &amp;quot;Passwords Don't Match!&amp;quot;;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Believe it or not, that snippet of code will output &amp;quot;Passwords Match!&amp;quot;. The reason for this is that the == operator tries to convert strings to other types before testing their equality. In this case, the two strings both start with &amp;quot;0e&amp;quot;, which PHP treats as the beginning of a floating-point number written in scientific notation (e.g. 2e10 == 2 * pow(10, 10)). Because the part of each string after the &amp;quot;0e&amp;quot; is an invalid exponent, PHP interprets the entire thing as 0. That's right: both $a and $b evaluate to 0, so the comparison is true.&lt;br /&gt;
&lt;br /&gt;
In a security situation, that's a terrible thing - any passwords with hashes that start with 0e will always be reported as equal to one another. &lt;br /&gt;
&lt;br /&gt;
Luckily, PHP, starting in version 5.5, has your back, with a function that solves both the problems above. You can use the [https://secure.php.net/manual/en/function.password-verify.php password_verify()] function to check a password securely.&lt;br /&gt;
&lt;br /&gt;
=== Example ===&lt;br /&gt;
&lt;br /&gt;
Here is an example of what you might do on your login page.  '''''Note:'' This example assumes that you hashed the user's password already and stored it in the database.'''&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;php&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;?php&lt;br /&gt;
// This is a *good* example of how you can implement password-based user authentication in your web application.&lt;br /&gt;
&lt;br /&gt;
require 'database.php';&lt;br /&gt;
&lt;br /&gt;
// Use a prepared statement&lt;br /&gt;
$stmt = $mysqli-&amp;gt;prepare(&amp;quot;SELECT COUNT(*), id, hashed_password FROM users WHERE username=?&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
// Bind the parameter&lt;br /&gt;
$stmt-&amp;gt;bind_param('s', $user);&lt;br /&gt;
$user = $_POST['username'];&lt;br /&gt;
$stmt-&amp;gt;execute();&lt;br /&gt;
&lt;br /&gt;
// Bind the results&lt;br /&gt;
$stmt-&amp;gt;bind_result($cnt, $user_id, $pwd_hash);&lt;br /&gt;
$stmt-&amp;gt;fetch();&lt;br /&gt;
&lt;br /&gt;
$pwd_guess = $_POST['password'];&lt;br /&gt;
// Compare the submitted password to the actual password hash&lt;br /&gt;
&lt;br /&gt;
if($cnt == 1 &amp;amp;&amp;amp; password_verify($pwd_guess, $pwd_hash)){&lt;br /&gt;
	// Login succeeded!&lt;br /&gt;
	$_SESSION['user_id'] = $user_id;&lt;br /&gt;
	// Redirect to your target page&lt;br /&gt;
} else{&lt;br /&gt;
	// Login failed; redirect back to the login screen&lt;br /&gt;
}&lt;br /&gt;
?&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Note:''' You may sometimes see functions like vanilla [http://php.net/md5 md5()] or [http://php.net/crypt crypt()] used to hash passwords.  md5() does indeed perform one-way hashing, but it does so without a salt.  '''THIS IS BAD PRACTICE''', because unsalted md5 hashes can be trivially reversed using a rainbow table.  (Just Google for &amp;quot;md5 decrypter&amp;quot;.)  Using a salt prevents the effective use of a rainbow table. Additionally, '''the md5 function, even with a salt, should not be used because it has been proved vulnerable.'''&lt;br /&gt;
&lt;br /&gt;
=== Real-Life Examples ===&lt;br /&gt;
&lt;br /&gt;
Here is a constantly-updated list of sites that do not use proper password security: http://plaintextoffenders.com/&lt;br /&gt;
&lt;br /&gt;
== Cross-Site Request Forgery ==&lt;br /&gt;
&lt;br /&gt;
{{DoctypeTV&lt;br /&gt;
|youtube_id=3IOKaIRg8V4&lt;br /&gt;
|time=3m45s&lt;br /&gt;
|desc=Cross Site Request Forgeries&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
A cross-site request forgery (CSRF, pronounced ''sea-surf'') involves a victim, who is logged in to the targeted site, visiting an attacker’s site.  The attacker has code on his site that forces the victim to unwittingly perform actions on the targeted site.&lt;br /&gt;
&lt;br /&gt;
For example, suppose Mother Goose visited Dr. Evil's blog.  Dr. Evil had the following tag embedded in his bloc:&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;&amp;lt;img src=&amp;quot;http://www.bank.com/transfer.php?dest=dr-evil&amp;amp;amp;amount=5000&amp;quot; /&amp;gt;&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This would cause Mother Goose to authorize a $5000 transfer to Dr. Evil, completely without Mother Goose's knowledge!&lt;br /&gt;
&lt;br /&gt;
Worse yet, Dr. Evil could just send an e-mail to Mother Goose with this image tag.  All Mother Goose would need to do to be attacked is open the e-mail!  (Now you know why sometimes your e-mail client turns off images from suspicious sources.)&lt;br /&gt;
&lt;br /&gt;
=== Solution ===&lt;br /&gt;
&lt;br /&gt;
The first precautionary measure is to always use POST requests (as opposed to GET requests) for actions that change something on your server.  This will fend off all except the most hard-core CSRF attacks.&lt;br /&gt;
&lt;br /&gt;
However, fully preventing CSRF attacks is not difficult.  To do this, you can use a '''CSRF token'''.  A CSRF token is a known string of text that is submitted in all of the forms on your site.  If the string is not what you expect, then you can assume that the request was forged.&lt;br /&gt;
&lt;br /&gt;
For example, consider this form:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;form action=&amp;quot;transfer.php&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;input type=&amp;quot;text&amp;quot; name=&amp;quot;dest&amp;quot; /&amp;gt;&lt;br /&gt;
    &amp;lt;input type=&amp;quot;number&amp;quot; name=&amp;quot;amount&amp;quot; /&amp;gt;&lt;br /&gt;
    &amp;lt;input type=&amp;quot;submit&amp;quot; value=&amp;quot;Transfer&amp;quot; /&amp;gt;&lt;br /&gt;
&amp;lt;/form&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We can easily add a hidden CSRF token field like so (as well as making the form POST rather than GET):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;form action=&amp;quot;transfer.php&amp;quot; method=&amp;quot;post&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;input type=&amp;quot;text&amp;quot; name=&amp;quot;dest&amp;quot; /&amp;gt;&lt;br /&gt;
    &amp;lt;input type=&amp;quot;number&amp;quot; name=&amp;quot;amount&amp;quot; /&amp;gt;&lt;br /&gt;
    &amp;lt;input type=&amp;quot;hidden&amp;quot; name=&amp;quot;token&amp;quot; value=&amp;quot;&amp;lt;?php echo $_SESSION['token'];?&amp;gt;&amp;quot; /&amp;gt;&lt;br /&gt;
    &amp;lt;input type=&amp;quot;submit&amp;quot; value=&amp;quot;Transfer&amp;quot; /&amp;gt;&lt;br /&gt;
&amp;lt;/form&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''This assumes that &amp;lt;code&amp;gt;$_SESSION['token']&amp;lt;/code&amp;gt; contains an alphanumeric string that was randomly generated upon session creation.'''  For example, you could add this line ''beneath beneath where the user successfully authenticates'':&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;php&amp;quot;&amp;gt;&lt;br /&gt;
$_SESSION['token'] = bin2hex(openssl_random_pseudo_bytes(32)); // generate a 32-byte random string&lt;br /&gt;
// In PHP 7, you can use the following, better technique:&lt;br /&gt;
// $_SESSION['token'] = bin2hex(random_bytes(32));&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We can now test for validity of the CSRF token on the server side (in transfer.php):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;php&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;?php&lt;br /&gt;
$destination_username = $_POST['dest'];&lt;br /&gt;
$amount = $_POST['amount'];&lt;br /&gt;
if(!hash_equals($_SESSION['token'], $_POST['token'])){&lt;br /&gt;
	die(&amp;quot;Request forgery detected&amp;quot;);&lt;br /&gt;
}&lt;br /&gt;
$mysqli-&amp;gt;query(/* perform transfer */);&lt;br /&gt;
?&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Now, if Mother Goose were to view a page containing the malicious &amp;lt;code&amp;gt;&amp;lt;img&amp;gt;&amp;lt;/code&amp;gt; tag, the transfer would not take place.&lt;br /&gt;
&lt;br /&gt;
=== Real-Life Examples ===&lt;br /&gt;
&lt;br /&gt;
* [http://www.zdnet.com/no-data-breach-in-first-weibo-attack-2062301014/ Weibo, June 2011]&lt;br /&gt;
* [http://www.huffingtonpost.com/huff-wires/20110601/us-tec-google-hacking-attack/ Gmail, June 2011]&lt;br /&gt;
* [http://www.pcworld.com/businesscenter/article/228609/hackers_steal_hotmail_messages_thanks_to_web_flaw.html Hotmail, May 2011]&lt;br /&gt;
* [http://www.theregister.co.uk/2010/05/19/facebook_private_data_leak/ Facebook, May 2010]&lt;br /&gt;
&lt;br /&gt;
== SQL Injection ==&lt;br /&gt;
&lt;br /&gt;
[[File:Exploits of a mom.png]]&lt;br /&gt;
&lt;br /&gt;
SQL injection occurs when an attacker submits specially-crafted input into your server, which is then included in an SQL query.  The input modifies the query to perform additional actions on the database or to access unwanted information.&lt;br /&gt;
&lt;br /&gt;
For instance, suppose you had the following code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;php&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;?php&lt;br /&gt;
require 'database.php';&lt;br /&gt;
&lt;br /&gt;
/* DISCLAIMER: THIS CODE IS BAD IN MANY MORE WAYS THAN JUST&lt;br /&gt;
BEING VULNERABLE TO SQL INJECTION! IT IS FOR DEMONSTRATION OF&lt;br /&gt;
CONCEPT ONLY. DO NOT USE THIS CODE IN YOUR OWN PROJECTS! */&lt;br /&gt;
&lt;br /&gt;
$res = $mysqli-&amp;gt;query(&amp;quot;SELECT id FROM users WHERE username='&amp;quot;.$_POST['username'].&amp;quot;' AND password='&amp;quot;.$_POST['password'].&amp;quot;'&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
if( $res-&amp;gt;num_rows==1 ){&lt;br /&gt;
    $row = $res-&amp;gt;fetch_assoc();&lt;br /&gt;
    $_SESSION['user_id'] = $row[&amp;quot;id&amp;quot;];&lt;br /&gt;
}else{&lt;br /&gt;
    echo &amp;quot;Login failed.&amp;quot;;&lt;br /&gt;
    exit;&lt;br /&gt;
}&lt;br /&gt;
?&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This code is vulnerable to SQL injection.  For example, suppose the attacker used the following string of text for his username:&lt;br /&gt;
&lt;br /&gt;
 mother-goose' --&lt;br /&gt;
&lt;br /&gt;
Here's what the resulting query would look like:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;mysql&amp;quot;&amp;gt;&lt;br /&gt;
SELECT id FROM users WHERE username='mother-goose' --' AND password=''&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Since &amp;lt;code&amp;gt;--&amp;lt;/code&amp;gt; is the start of a comment in SQL, when MySQL interprets this query, it will ''completely ignore'' the password-checking part of the query!  Dr. Evil can log in using anyone's username and steal all of their money!&lt;br /&gt;
&lt;br /&gt;
=== Solution ===&lt;br /&gt;
&lt;br /&gt;
If you write your queries manually (as in the example above), you need to use &amp;lt;code&amp;gt;$mysqli-&amp;gt;real_escape_string()&amp;lt;/code&amp;gt; to sanitize your input:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;php&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;?php&lt;br /&gt;
$safe_username = $mysqli-&amp;gt;real_escape_string($_POST['username']);&lt;br /&gt;
// ...&lt;br /&gt;
?&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
However, the better solution is to use prepared queries.  For more information on prepared queries, see [[PHP and MySQL]].&lt;br /&gt;
&lt;br /&gt;
'''IMPORTANT:''' If you correctly use the sample code in the PHP and MySQL guide above, you are already safe from SQL injection attacks.&lt;br /&gt;
&lt;br /&gt;
=== Real-Life Examples ===&lt;br /&gt;
&lt;br /&gt;
* [http://www.zdnet.com/unknowns-hack-european-space-agency-4010026071/ European Space Agency, May 2012]&lt;br /&gt;
* [http://www.dutchnews.nl/news/archives/2012/04/new_online_medical_records_sca.php Dutch Department Stores, April 2012]&lt;br /&gt;
* [http://www.msnbc.msn.com/id/46735808/ns/technology_and_science-security/ Ancestry.com, March 2012]&lt;br /&gt;
* [http://www.scmagazine.com.au/News/292592,allphones-hacked-staff-passwords-exposed.aspx Allphones (Australian Telecommunications Retailer), March 2012]&lt;br /&gt;
* [http://www.abc4.com/content/news/slc/story/More-fallout-Salt-Lake-City-police-website-hacked/PiSspE768UiioitJ3K4gyQ.cspx Salt Lake City Police Department, February 2012]&lt;br /&gt;
&lt;br /&gt;
== Abuse of Functionality ==&lt;br /&gt;
&lt;br /&gt;
''Abuse of Functionality'' is a general term that refers to when an attacker exploits vulnerabilities in the logic of your application.&lt;br /&gt;
&lt;br /&gt;
For example, suppose you were a banking site, and you had the following code to perform a transaction:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;php&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;?php&lt;br /&gt;
require 'database.php';&lt;br /&gt;
&lt;br /&gt;
$amount = (double) $_POST['amount'];&lt;br /&gt;
$destination_username = $mysqli-&amp;gt;real_escape_string($_POST['destination']);&lt;br /&gt;
&lt;br /&gt;
$mysqli-&amp;gt;autocommit(false); // start transaction&lt;br /&gt;
$mysqli-&amp;gt;query(&amp;quot;UPDATE users SET balance=balance-&amp;quot;.$amount.&amp;quot;&lt;br /&gt;
	WHERE id=&amp;quot;.$_SESSION['user_id']);&lt;br /&gt;
$mysqli-&amp;gt;query(&amp;quot;UPDATE users SET balance=balance+&amp;quot;.$amount.&amp;quot;&lt;br /&gt;
	WHERE username='&amp;quot;.$destination_username.&amp;quot;'&amp;quot;);&lt;br /&gt;
$mysqli-&amp;gt;commit(); // commit transaction&lt;br /&gt;
?&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It may not be obvious, but if you don't filter your input, it is trivial for an attacker to ''insert a negative number'' into the &amp;quot;amount&amp;quot; field and transfer money from anyone's account to his account!  The solution here is to simply filter amount for what you expect (in this case, a positive number that is not greater than the user's current balance).&lt;br /&gt;
&lt;br /&gt;
=== Filtering on the Client Side is Never Enough ===&lt;br /&gt;
&lt;br /&gt;
Suppose you have an e-mail field in a form in HTML, and you use some JavaScript function (or HTML5) to check it for form as an e-mail address:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;input type=&amp;quot;text&amp;quot; name=&amp;quot;email&amp;quot; onchange=&amp;quot;checkEmail(this);&amp;quot; /&amp;gt; &amp;lt;!-- HTML versions ≤ XHTML 1.0 --&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;input type=&amp;quot;email&amp;quot; name=&amp;quot;email&amp;quot; /&amp;gt; &amp;lt;!-- HTML versions ≥ 5 --&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
With this filter in place, any layperson using your form is now required to submit an e-mail address in that field.  ''However'', it is trivial for an attacker to bypass this client-side filtering (e.g., by using web developer tools like Firebug) and still submit non-email text to your server.  This is why '''IT IS ESSENTIAL THAT YOU FILTER INPUT ON THE SERVER SIDE!  Any sort of filtering on the client side are just bells and whistles for the end user.'''&lt;br /&gt;
&lt;br /&gt;
=== Information Leakage ===&lt;br /&gt;
&lt;br /&gt;
''Information Leakage'' is a noteworthy type of ''Abuse of Functionality'' attack that involves unprivileged users accessing privileged information.  In fact, Information Leakage accounts for a significant percentage of all recorded web application vulnerabilities (second only to Cross-Site Scripting).&lt;br /&gt;
&lt;br /&gt;
The concept is relatively simple.  Suppose you have an administration page that loads an image containing a graph of all activity on your site:&lt;br /&gt;
&lt;br /&gt;
'''admin.php'''&lt;br /&gt;
&amp;lt;source lang=&amp;quot;php&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;?php&lt;br /&gt;
if($_SESSION['admin']) echo '&amp;lt;img src=&amp;quot;stats.php?day=2012-08-19&amp;quot; alt=&amp;quot;Stats for 2012-08-19&amp;quot; /&amp;gt;';&lt;br /&gt;
?&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''stats.php'''&lt;br /&gt;
&amp;lt;source lang=&amp;quot;php&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;?php&lt;br /&gt;
// query the database, and save the results in $result&lt;br /&gt;
&lt;br /&gt;
$im = new PNGraph();&lt;br /&gt;
$im-&amp;gt;takeData($result);&lt;br /&gt;
&lt;br /&gt;
header(&amp;quot;Content-Type: image/png&amp;quot;);&lt;br /&gt;
print $im-&amp;gt;toString();&lt;br /&gt;
?&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Notice how you check for admin credentials in ''admin.php''.  However, you forgot to do this in ''stats.php'' itself.  An attacker could simply load ''stats.php'' directly to see all of the sensitive admin-only information!&lt;br /&gt;
&lt;br /&gt;
==== Solution ====&lt;br /&gt;
&lt;br /&gt;
Information Leakage is an attack that requires the developer to see the big picture and really keep track of what's going on in his or her application.  As a rule of thumb, ''whenever'' you query the database to access sensitive information, check the permissions of the user first.&lt;br /&gt;
&lt;br /&gt;
=== A Note about Frameworks ===&lt;br /&gt;
&lt;br /&gt;
Web frameworks are designed to make web development more agile, but they in turn have security weaknesses of their own.  For instance, the infamous ''mass-assignment vulnerability'' in Ruby on Rails-type MVC frameworks is an abuse of functionality vulnerability that enables attackers to save arbitrary information in your database (!).&lt;br /&gt;
&lt;br /&gt;
The important thing to know is that '''if you use a web framework, be familiar with the security considerations with that framework'''.  Most of the time, frameworks will have articles on their web sites that discuss these concerns.  (If your framework doesn't have a guide like this, you should probably be using a different framework!)&lt;br /&gt;
&lt;br /&gt;
=== Real-Life Examples ===&lt;br /&gt;
&lt;br /&gt;
* [http://gizmodo.com/some-guy-figured-out-how-to-delete-every-photo-on-faceb-1685491356 Facebook, February 2015 (bypassing authorization on REST API calls)]&lt;br /&gt;
* [http://www.whitec0de.com/new-hotmail-exploit-can-get-any-hotmail-email-account-hacked-for-just-20/ Hotmail, April 2012 (parameter manipulation)]&lt;br /&gt;
* [http://www.theregister.co.uk/2012/04/18/toshiba_slapped_by_ico/ Toshiba, April 2012 (parameter manipulation / information leakage)]&lt;br /&gt;
* [http://www.zdnet.com/blog/security/3-million-bank-accounts-hacked-in-iran/11577 Iranian Banks, April 2012 (information leakage)]&lt;br /&gt;
* [http://www.zdnet.com/blog/security/hacker-steals-chinese-government-defense-contracts/11386 Chinese Department of Defense, April 2012 (information leakage)]&lt;br /&gt;
* [http://articles.chicagotribune.com/2012-04-04/news/sns-rt-us-usa-hackers-utahbre83404g-20120404_1_data-security-breach-cyber-attack-hackers Utah Medicaid, April 2012]&lt;br /&gt;
&lt;br /&gt;
== CAPTCHA Abuse ==&lt;br /&gt;
&lt;br /&gt;
CAPTCHAs are a great way to stop robots from submitting forms in your web application.  However, depending on how you implement CAPTCHAs, it might be possible for a hacker to bypass the CAPTCHA on your site.&lt;br /&gt;
&lt;br /&gt;
For example, suppose you are making a home-grown CAPTCHA system for your application.  You have a table '''CaptchaTable''' with the following fields: '''id''' and '''value'''.  Your form looks like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;form action=&amp;quot;signup.php&amp;quot; method=&amp;quot;post&amp;quot;&amp;gt;&lt;br /&gt;
	&amp;lt;strong&amp;gt;Subscribe to our newsletter&amp;lt;/strong&amp;gt;&lt;br /&gt;
	&amp;lt;input type=&amp;quot;email&amp;quot; name=&amp;quot;email&amp;quot; placeholder=&amp;quot;Enter Your Email Here&amp;quot; /&amp;gt;&lt;br /&gt;
	&amp;lt;input type=&amp;quot;text&amp;quot; name=&amp;quot;captcha_value&amp;quot; placeholder=&amp;quot;Type what you see in the CAPTCHA below.&amp;quot; /&amp;gt;&lt;br /&gt;
	&amp;lt;img src=&amp;quot;captcha.php?id=12345&amp;quot; /&amp;gt;&lt;br /&gt;
	&amp;lt;input type=&amp;quot;hidden&amp;quot; name=&amp;quot;captcha_id&amp;quot; value=&amp;quot;12345&amp;quot; /&amp;gt;&lt;br /&gt;
	&amp;lt;input type=&amp;quot;submit&amp;quot; value=&amp;quot;Sign Up&amp;quot; /&amp;gt;&lt;br /&gt;
&amp;lt;/form&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here's what the code on ''signup.php'' might look like:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;php&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;?php&lt;br /&gt;
$email = $_POST[&amp;quot;email&amp;quot;];&lt;br /&gt;
$captcha_id = (int) $_POST[&amp;quot;captcha_id&amp;quot;];&lt;br /&gt;
$captcha_value = $_POST[&amp;quot;captcha_value&amp;quot;];&lt;br /&gt;
&lt;br /&gt;
// check CAPTCHA&lt;br /&gt;
&lt;br /&gt;
$captcha_stmt = $mysqli-&amp;gt;prepare(&amp;quot;select count(*) as match from CaptchaTable where id=? and value=?&amp;quot;);&lt;br /&gt;
$captcha_stmt-&amp;gt;bind_param(&amp;quot;is&amp;quot;, $captcha_id, $captcha_value);&lt;br /&gt;
$captcha_stmt-&amp;gt;execute();&lt;br /&gt;
$captcha_row = (int) $captcha_stmt-&amp;gt;fetch_assoc();&lt;br /&gt;
$captcha_stmt-&amp;gt;close();&lt;br /&gt;
&lt;br /&gt;
if ($captcha_row[&amp;quot;match&amp;quot;] == 0){&lt;br /&gt;
	http_response_code(403);&lt;br /&gt;
	echo &amp;quot;Invalid CAPTCHA&amp;quot;;&lt;br /&gt;
	exit;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
// continue with signup procedure down here&lt;br /&gt;
?&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The issue here is that a hacker can simply solve one CAPTCHA and then send that CAPTCHA ID and Value over and over again!&lt;br /&gt;
&lt;br /&gt;
=== Solution ===&lt;br /&gt;
&lt;br /&gt;
If you already have a home-grown CAPTCHA system, the best solution here would be to simply issue another query to the database that deletes a CAPTCHA id-value pair as soon as it is submitted in a form.&lt;br /&gt;
&lt;br /&gt;
If you haven't yet implemented your CAPTCHA system, you might want to consider a third-party solution like [http://www.google.com/recaptcha reCAPTCHA].&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 3]]&lt;br /&gt;
[[Category:Web Application Security]]&lt;/div&gt;</summary>
		<author><name>Alex</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Module_4&amp;diff=2536</id>
		<title>Module 4</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Module_4&amp;diff=2536"/>
		<updated>2018-02-21T17:32:15Z</updated>

		<summary type="html">&lt;p&gt;Alex: /* Grading */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;__NOTOC__&lt;br /&gt;
In Module 4, you will learn the fundamentals of Python, a popular scripting language, and Regular Expressions, which give you power in text processing.&lt;br /&gt;
&lt;br /&gt;
This article contains your assignments for Module 4.&lt;br /&gt;
&lt;br /&gt;
== Reading ==&lt;br /&gt;
&lt;br /&gt;
The following articles on the online class wiki textbook contain information that will help you complete the assignments.&lt;br /&gt;
&lt;br /&gt;
* [[Python]]&lt;br /&gt;
* [[Regular Expressions]]&lt;br /&gt;
&lt;br /&gt;
== Individual Assignments ==&lt;br /&gt;
&lt;br /&gt;
=== Learn Python and Regular Expressions ===&lt;br /&gt;
&lt;br /&gt;
Up to this point in CSE 330, you have used only one programming language: PHP.  In Module 4, you will learn a new language: Python.  Before starting this assignment, you should look over the [[Python|online textbook article about Python]].  You should be using version 3 (or greater) of Python. Additionally, you may find it helpful to look over the [[Regular Expressions|online textbook article about Regular Expressions]].&lt;br /&gt;
&lt;br /&gt;
=== Write some Regular Expressions ===&lt;br /&gt;
&lt;br /&gt;
Please write regular expressions that do each the following:&lt;br /&gt;
&lt;br /&gt;
# Match the substring &amp;quot;hello world&amp;quot; in string.&lt;br /&gt;
# Find all words in an input string that contains three consecutive vowels, regardless of case.&lt;br /&gt;
# Match an input string that is '''entirely''' a flight code, of the format AA####, where '''AA''' is a two-letter uppercase airline code, and '''####''' is a three- or four-digit flight number.&lt;br /&gt;
Examples:&lt;br /&gt;
   Note: text in ''[[red]]'' is matched by the regular expression. Each line is a separate test input string.&lt;br /&gt;
   Regex 1:  Programmers will often write ''[[hello world]]'' as their first project with a programming language.&lt;br /&gt;
   Regex 2:  The ''[[gooey]]'' peanut butter and jelly sandwich was a ''[[beauty]]''.&lt;br /&gt;
   Regex 3:  ''[[AA312]]''&lt;br /&gt;
             ''[[AA1298]]''&lt;br /&gt;
             ''[[NW1234]]''&lt;br /&gt;
             ''[[US443]]''&lt;br /&gt;
             US31344&lt;br /&gt;
             AA123 extratext&lt;br /&gt;
&lt;br /&gt;
            &lt;br /&gt;
&lt;br /&gt;
Save your regexes to text files – one each.&lt;br /&gt;
&lt;br /&gt;
=== Baseball Stats Counter ===&lt;br /&gt;
&lt;br /&gt;
The St. Louis Cardinals are the most legendary baseball team in the national league.  In this exercise, you will be creating a Python script that reads box scores from a file and computes the Cardinals' players' batting averages in a particular season.&lt;br /&gt;
&lt;br /&gt;
==== Tips and Instructions ====&lt;br /&gt;
&lt;br /&gt;
* You should write a Python script file to solve this problem.&lt;br /&gt;
* You should use a regular expression to parse players' names, at-bats, hits, and runs from the input file.&lt;br /&gt;
* You may want to create a class to hold and compute information about each player.&lt;br /&gt;
* Your file should take one command-line argument: the path to an input file.  If no path is given, your program should print a usage message.&lt;br /&gt;
&lt;br /&gt;
==== Input ====&lt;br /&gt;
&lt;br /&gt;
Sample input files may be found here: http://classes.engineering.wustl.edu/cse330/content/cardinals/&lt;br /&gt;
&lt;br /&gt;
The top of the file contains a citation, and what follows is an entire season of Cardinals Baseball box scores.  Each game starts with a title; for example:&lt;br /&gt;
&lt;br /&gt;
 === St.Louis Cardinals vs. Chicago Cubs, 1940-04-19 ===&lt;br /&gt;
&lt;br /&gt;
What follows are the performance of each player in that game.  The format of each line is as follows:&lt;br /&gt;
&lt;br /&gt;
 XXX batted # times with # hits and # runs&lt;br /&gt;
&lt;br /&gt;
where '''XXX''' is the player's name (you may assume that the name is unique), and each '''#''' are integers representing the number of &amp;quot;at bats&amp;quot;, the number of &amp;quot;hits&amp;quot;, and the number of &amp;quot;runs&amp;quot;, respectively.&lt;br /&gt;
&lt;br /&gt;
==== Output ====&lt;br /&gt;
&lt;br /&gt;
Your script needs to output all players' batting average across the season.  A player's batting average is that player's total hits divided by that player's total at-bats throughout the entire season.  For example, Johnny Hopp was at bat 149 times in 1940, and he had 41 hits, so his batting average was 0.275.&lt;br /&gt;
&lt;br /&gt;
Each line in the output should have the format:&lt;br /&gt;
&lt;br /&gt;
 XXX: #.###&lt;br /&gt;
&lt;br /&gt;
where '''XXX''' is the player's name, and '''#.###''' is the player's batting average, '''rounded''' (not truncated) to three decimal places.&lt;br /&gt;
&lt;br /&gt;
The players should be sorted by batting average, with the highest batting average on top.  If two players have the exact same batting average (before rounding occurs), the order between those two players is unimportant.&lt;br /&gt;
&lt;br /&gt;
For example, the correct output for the 1940 season is:&lt;br /&gt;
&amp;lt;!-- Jimmy Brown was 0.280 and Ira Hutchinson was 0.125 --&amp;gt;&lt;br /&gt;
&amp;lt;source lang=&amp;quot;text&amp;quot;&amp;gt;&lt;br /&gt;
Pepper Martin: 0.316&lt;br /&gt;
Walker Cooper: 0.316&lt;br /&gt;
Johnny Mize: 0.314&lt;br /&gt;
Ernie Koy: 0.310&lt;br /&gt;
Enos Slaughter: 0.306&lt;br /&gt;
Joe Medwick: 0.304&lt;br /&gt;
Terry Moore: 0.304&lt;br /&gt;
Joe Orengo: 0.286&lt;br /&gt;
Jimmy Brown: 0.280&lt;br /&gt;
Marty Marion: 0.279&lt;br /&gt;
Don Gutteridge: 0.276&lt;br /&gt;
Johnny Hopp: 0.275&lt;br /&gt;
Creepy Crespi: 0.273&lt;br /&gt;
Mickey Owen: 0.265&lt;br /&gt;
Bill DeLancey: 0.250&lt;br /&gt;
Don Padgett: 0.242&lt;br /&gt;
Stu Martin: 0.238&lt;br /&gt;
Eddie Lake: 0.222&lt;br /&gt;
Hal Epps: 0.214&lt;br /&gt;
Lon Warneke: 0.209&lt;br /&gt;
Harry Walker: 0.185&lt;br /&gt;
Max Lanier: 0.179&lt;br /&gt;
Bill McGee: 0.178&lt;br /&gt;
Carl Doyle: 0.174&lt;br /&gt;
Mort Cooper: 0.157&lt;br /&gt;
Clyde Shoun: 0.145&lt;br /&gt;
Carden Gillenwater: 0.130&lt;br /&gt;
Bob Bowman: 0.067&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Grading ==&lt;br /&gt;
&lt;br /&gt;
We will be grading the following aspects of your work.  There are 50 points total.&lt;br /&gt;
&lt;br /&gt;
'''Assignments (including code) must be committed to Bitbucket by the end of class on the due date (commit early and often). Failing to commit by the end of class on the due date will result in a 0. ''' &lt;br /&gt;
&lt;br /&gt;
Upload your baseball code and a file with your Regular expressions.&lt;br /&gt;
&lt;br /&gt;
# '''Regular Expressions (15 Points):'''&lt;br /&gt;
#* '''Your regex files should contain your regex (with no delimiters) and nothing else.'''&lt;br /&gt;
#* Regular Expression 1 Correct and saved in a file named &amp;lt;code&amp;gt;regex1.txt&amp;lt;/code&amp;gt; (5 points)&lt;br /&gt;
#* Regular Expression 2 Correct and saved in a file named &amp;lt;code&amp;gt;regex2.txt&amp;lt;/code&amp;gt;(5 points)&lt;br /&gt;
#* Regular Expression 3 Correct and saved in a file named &amp;lt;code&amp;gt;regex3.txt&amp;lt;/code&amp;gt;(5 points)&lt;br /&gt;
# '''Baseball Stats Counter (35 Points):'''&lt;br /&gt;
#* Solution is written entirely in Python and saved in a file named &amp;lt;code&amp;gt;baseball.py&amp;lt;/code&amp;gt; (8 points)&lt;br /&gt;
#*: ''Note: Failing to write your code in Python 3 will result is losing, at a minimum, points for this category.''&lt;br /&gt;
#* Correct usage of one or more regular expressions to parse and extract data from each line of the input file (8 points)&lt;br /&gt;
#*: ''Note: You should not be using &amp;lt;code&amp;gt;str.split&amp;lt;/code&amp;gt; to extract data.''&lt;br /&gt;
#* Script prints a usage message if a command line argument is not present (4 points)&lt;br /&gt;
#*: ''Note: For an example of a usage message, see [https://en.wikipedia.org/wiki/Usage_message#Examples this link.]''&lt;br /&gt;
#* Output is correct for all test cases (15 points)&lt;br /&gt;
#*: ''This includes sorting and rounding.''&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 4]]&lt;br /&gt;
[[Category:Modules]]&lt;/div&gt;</summary>
		<author><name>Alex</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Module_4&amp;diff=2535</id>
		<title>Module 4</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Module_4&amp;diff=2535"/>
		<updated>2018-02-21T17:29:24Z</updated>

		<summary type="html">&lt;p&gt;Alex: /* Grading */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;__NOTOC__&lt;br /&gt;
In Module 4, you will learn the fundamentals of Python, a popular scripting language, and Regular Expressions, which give you power in text processing.&lt;br /&gt;
&lt;br /&gt;
This article contains your assignments for Module 4.&lt;br /&gt;
&lt;br /&gt;
== Reading ==&lt;br /&gt;
&lt;br /&gt;
The following articles on the online class wiki textbook contain information that will help you complete the assignments.&lt;br /&gt;
&lt;br /&gt;
* [[Python]]&lt;br /&gt;
* [[Regular Expressions]]&lt;br /&gt;
&lt;br /&gt;
== Individual Assignments ==&lt;br /&gt;
&lt;br /&gt;
=== Learn Python and Regular Expressions ===&lt;br /&gt;
&lt;br /&gt;
Up to this point in CSE 330, you have used only one programming language: PHP.  In Module 4, you will learn a new language: Python.  Before starting this assignment, you should look over the [[Python|online textbook article about Python]].  You should be using version 3 (or greater) of Python. Additionally, you may find it helpful to look over the [[Regular Expressions|online textbook article about Regular Expressions]].&lt;br /&gt;
&lt;br /&gt;
=== Write some Regular Expressions ===&lt;br /&gt;
&lt;br /&gt;
Please write regular expressions that do each the following:&lt;br /&gt;
&lt;br /&gt;
# Match the substring &amp;quot;hello world&amp;quot; in string.&lt;br /&gt;
# Find all words in an input string that contains three consecutive vowels, regardless of case.&lt;br /&gt;
# Match an input string that is '''entirely''' a flight code, of the format AA####, where '''AA''' is a two-letter uppercase airline code, and '''####''' is a three- or four-digit flight number.&lt;br /&gt;
Examples:&lt;br /&gt;
   Note: text in ''[[red]]'' is matched by the regular expression. Each line is a separate test input string.&lt;br /&gt;
   Regex 1:  Programmers will often write ''[[hello world]]'' as their first project with a programming language.&lt;br /&gt;
   Regex 2:  The ''[[gooey]]'' peanut butter and jelly sandwich was a ''[[beauty]]''.&lt;br /&gt;
   Regex 3:  ''[[AA312]]''&lt;br /&gt;
             ''[[AA1298]]''&lt;br /&gt;
             ''[[NW1234]]''&lt;br /&gt;
             ''[[US443]]''&lt;br /&gt;
             US31344&lt;br /&gt;
             AA123 extratext&lt;br /&gt;
&lt;br /&gt;
            &lt;br /&gt;
&lt;br /&gt;
Save your regexes to text files – one each.&lt;br /&gt;
&lt;br /&gt;
=== Baseball Stats Counter ===&lt;br /&gt;
&lt;br /&gt;
The St. Louis Cardinals are the most legendary baseball team in the national league.  In this exercise, you will be creating a Python script that reads box scores from a file and computes the Cardinals' players' batting averages in a particular season.&lt;br /&gt;
&lt;br /&gt;
==== Tips and Instructions ====&lt;br /&gt;
&lt;br /&gt;
* You should write a Python script file to solve this problem.&lt;br /&gt;
* You should use a regular expression to parse players' names, at-bats, hits, and runs from the input file.&lt;br /&gt;
* You may want to create a class to hold and compute information about each player.&lt;br /&gt;
* Your file should take one command-line argument: the path to an input file.  If no path is given, your program should print a usage message.&lt;br /&gt;
&lt;br /&gt;
==== Input ====&lt;br /&gt;
&lt;br /&gt;
Sample input files may be found here: http://classes.engineering.wustl.edu/cse330/content/cardinals/&lt;br /&gt;
&lt;br /&gt;
The top of the file contains a citation, and what follows is an entire season of Cardinals Baseball box scores.  Each game starts with a title; for example:&lt;br /&gt;
&lt;br /&gt;
 === St.Louis Cardinals vs. Chicago Cubs, 1940-04-19 ===&lt;br /&gt;
&lt;br /&gt;
What follows are the performance of each player in that game.  The format of each line is as follows:&lt;br /&gt;
&lt;br /&gt;
 XXX batted # times with # hits and # runs&lt;br /&gt;
&lt;br /&gt;
where '''XXX''' is the player's name (you may assume that the name is unique), and each '''#''' are integers representing the number of &amp;quot;at bats&amp;quot;, the number of &amp;quot;hits&amp;quot;, and the number of &amp;quot;runs&amp;quot;, respectively.&lt;br /&gt;
&lt;br /&gt;
==== Output ====&lt;br /&gt;
&lt;br /&gt;
Your script needs to output all players' batting average across the season.  A player's batting average is that player's total hits divided by that player's total at-bats throughout the entire season.  For example, Johnny Hopp was at bat 149 times in 1940, and he had 41 hits, so his batting average was 0.275.&lt;br /&gt;
&lt;br /&gt;
Each line in the output should have the format:&lt;br /&gt;
&lt;br /&gt;
 XXX: #.###&lt;br /&gt;
&lt;br /&gt;
where '''XXX''' is the player's name, and '''#.###''' is the player's batting average, '''rounded''' (not truncated) to three decimal places.&lt;br /&gt;
&lt;br /&gt;
The players should be sorted by batting average, with the highest batting average on top.  If two players have the exact same batting average (before rounding occurs), the order between those two players is unimportant.&lt;br /&gt;
&lt;br /&gt;
For example, the correct output for the 1940 season is:&lt;br /&gt;
&amp;lt;!-- Jimmy Brown was 0.280 and Ira Hutchinson was 0.125 --&amp;gt;&lt;br /&gt;
&amp;lt;source lang=&amp;quot;text&amp;quot;&amp;gt;&lt;br /&gt;
Pepper Martin: 0.316&lt;br /&gt;
Walker Cooper: 0.316&lt;br /&gt;
Johnny Mize: 0.314&lt;br /&gt;
Ernie Koy: 0.310&lt;br /&gt;
Enos Slaughter: 0.306&lt;br /&gt;
Joe Medwick: 0.304&lt;br /&gt;
Terry Moore: 0.304&lt;br /&gt;
Joe Orengo: 0.286&lt;br /&gt;
Jimmy Brown: 0.280&lt;br /&gt;
Marty Marion: 0.279&lt;br /&gt;
Don Gutteridge: 0.276&lt;br /&gt;
Johnny Hopp: 0.275&lt;br /&gt;
Creepy Crespi: 0.273&lt;br /&gt;
Mickey Owen: 0.265&lt;br /&gt;
Bill DeLancey: 0.250&lt;br /&gt;
Don Padgett: 0.242&lt;br /&gt;
Stu Martin: 0.238&lt;br /&gt;
Eddie Lake: 0.222&lt;br /&gt;
Hal Epps: 0.214&lt;br /&gt;
Lon Warneke: 0.209&lt;br /&gt;
Harry Walker: 0.185&lt;br /&gt;
Max Lanier: 0.179&lt;br /&gt;
Bill McGee: 0.178&lt;br /&gt;
Carl Doyle: 0.174&lt;br /&gt;
Mort Cooper: 0.157&lt;br /&gt;
Clyde Shoun: 0.145&lt;br /&gt;
Carden Gillenwater: 0.130&lt;br /&gt;
Bob Bowman: 0.067&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Grading ==&lt;br /&gt;
&lt;br /&gt;
We will be grading the following aspects of your work.  There are 50 points total.&lt;br /&gt;
&lt;br /&gt;
'''Assignments (including code) must be committed to Bitbucket by the end of class on the due date (commit early and often). Failing to commit by the end of class on the due date will result in a 0. ''' &lt;br /&gt;
&lt;br /&gt;
Upload your baseball code and a file with your Regular expressions.&lt;br /&gt;
&lt;br /&gt;
# '''Regular Expressions (15 Points):'''&lt;br /&gt;
#* '''Your regex files should contain your regex (with no delimiters) and nothing else.'''&lt;br /&gt;
#* Regular Expression 1 Correct and saved in a file named &amp;lt;code&amp;gt;regex1.txt&amp;lt;/code&amp;gt; (5 points)'&lt;br /&gt;
#* Regular Expression 2 Correct and saved in a file named &amp;lt;code&amp;gt;regex2.txt&amp;lt;/code&amp;gt;(5 points)&lt;br /&gt;
#* Regular Expression 3 Correct and saved in a file named &amp;lt;code&amp;gt;regex3.txt&amp;lt;/code&amp;gt;(5 points)&lt;br /&gt;
# '''Baseball Stats Counter (35 Points):'''&lt;br /&gt;
#* Solution is written entirely in Python and saved in a file named &amp;lt;code&amp;gt;baseball.py&amp;lt;/code&amp;gt; (8 points)&lt;br /&gt;
#*: ''Note: Failing to write your code in Python 3 will result is losing, at a minimum, points for this category.''&lt;br /&gt;
#* Correct usage of one or more regular expressions to parse and extract data from each line of the input file (8 points)&lt;br /&gt;
#*: ''Note: You should not be using &amp;lt;code&amp;gt;str.split&amp;lt;/code&amp;gt; to extract data.''&lt;br /&gt;
#* Script prints a usage message if a command line argument is not present (4 points)&lt;br /&gt;
#*: ''Note: For an example of a usage message, see [https://en.wikipedia.org/wiki/Usage_message#Examples this link.]''&lt;br /&gt;
#* Output is correct for all test cases (15 points)&lt;br /&gt;
#*: ''This includes sorting and rounding.''&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 4]]&lt;br /&gt;
[[Category:Modules]]&lt;/div&gt;</summary>
		<author><name>Alex</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Module_4&amp;diff=2534</id>
		<title>Module 4</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Module_4&amp;diff=2534"/>
		<updated>2018-02-21T17:28:58Z</updated>

		<summary type="html">&lt;p&gt;Alex: /* Grading */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;__NOTOC__&lt;br /&gt;
In Module 4, you will learn the fundamentals of Python, a popular scripting language, and Regular Expressions, which give you power in text processing.&lt;br /&gt;
&lt;br /&gt;
This article contains your assignments for Module 4.&lt;br /&gt;
&lt;br /&gt;
== Reading ==&lt;br /&gt;
&lt;br /&gt;
The following articles on the online class wiki textbook contain information that will help you complete the assignments.&lt;br /&gt;
&lt;br /&gt;
* [[Python]]&lt;br /&gt;
* [[Regular Expressions]]&lt;br /&gt;
&lt;br /&gt;
== Individual Assignments ==&lt;br /&gt;
&lt;br /&gt;
=== Learn Python and Regular Expressions ===&lt;br /&gt;
&lt;br /&gt;
Up to this point in CSE 330, you have used only one programming language: PHP.  In Module 4, you will learn a new language: Python.  Before starting this assignment, you should look over the [[Python|online textbook article about Python]].  You should be using version 3 (or greater) of Python. Additionally, you may find it helpful to look over the [[Regular Expressions|online textbook article about Regular Expressions]].&lt;br /&gt;
&lt;br /&gt;
=== Write some Regular Expressions ===&lt;br /&gt;
&lt;br /&gt;
Please write regular expressions that do each the following:&lt;br /&gt;
&lt;br /&gt;
# Match the substring &amp;quot;hello world&amp;quot; in string.&lt;br /&gt;
# Find all words in an input string that contains three consecutive vowels, regardless of case.&lt;br /&gt;
# Match an input string that is '''entirely''' a flight code, of the format AA####, where '''AA''' is a two-letter uppercase airline code, and '''####''' is a three- or four-digit flight number.&lt;br /&gt;
Examples:&lt;br /&gt;
   Note: text in ''[[red]]'' is matched by the regular expression. Each line is a separate test input string.&lt;br /&gt;
   Regex 1:  Programmers will often write ''[[hello world]]'' as their first project with a programming language.&lt;br /&gt;
   Regex 2:  The ''[[gooey]]'' peanut butter and jelly sandwich was a ''[[beauty]]''.&lt;br /&gt;
   Regex 3:  ''[[AA312]]''&lt;br /&gt;
             ''[[AA1298]]''&lt;br /&gt;
             ''[[NW1234]]''&lt;br /&gt;
             ''[[US443]]''&lt;br /&gt;
             US31344&lt;br /&gt;
             AA123 extratext&lt;br /&gt;
&lt;br /&gt;
            &lt;br /&gt;
&lt;br /&gt;
Save your regexes to text files – one each.&lt;br /&gt;
&lt;br /&gt;
=== Baseball Stats Counter ===&lt;br /&gt;
&lt;br /&gt;
The St. Louis Cardinals are the most legendary baseball team in the national league.  In this exercise, you will be creating a Python script that reads box scores from a file and computes the Cardinals' players' batting averages in a particular season.&lt;br /&gt;
&lt;br /&gt;
==== Tips and Instructions ====&lt;br /&gt;
&lt;br /&gt;
* You should write a Python script file to solve this problem.&lt;br /&gt;
* You should use a regular expression to parse players' names, at-bats, hits, and runs from the input file.&lt;br /&gt;
* You may want to create a class to hold and compute information about each player.&lt;br /&gt;
* Your file should take one command-line argument: the path to an input file.  If no path is given, your program should print a usage message.&lt;br /&gt;
&lt;br /&gt;
==== Input ====&lt;br /&gt;
&lt;br /&gt;
Sample input files may be found here: http://classes.engineering.wustl.edu/cse330/content/cardinals/&lt;br /&gt;
&lt;br /&gt;
The top of the file contains a citation, and what follows is an entire season of Cardinals Baseball box scores.  Each game starts with a title; for example:&lt;br /&gt;
&lt;br /&gt;
 === St.Louis Cardinals vs. Chicago Cubs, 1940-04-19 ===&lt;br /&gt;
&lt;br /&gt;
What follows are the performance of each player in that game.  The format of each line is as follows:&lt;br /&gt;
&lt;br /&gt;
 XXX batted # times with # hits and # runs&lt;br /&gt;
&lt;br /&gt;
where '''XXX''' is the player's name (you may assume that the name is unique), and each '''#''' are integers representing the number of &amp;quot;at bats&amp;quot;, the number of &amp;quot;hits&amp;quot;, and the number of &amp;quot;runs&amp;quot;, respectively.&lt;br /&gt;
&lt;br /&gt;
==== Output ====&lt;br /&gt;
&lt;br /&gt;
Your script needs to output all players' batting average across the season.  A player's batting average is that player's total hits divided by that player's total at-bats throughout the entire season.  For example, Johnny Hopp was at bat 149 times in 1940, and he had 41 hits, so his batting average was 0.275.&lt;br /&gt;
&lt;br /&gt;
Each line in the output should have the format:&lt;br /&gt;
&lt;br /&gt;
 XXX: #.###&lt;br /&gt;
&lt;br /&gt;
where '''XXX''' is the player's name, and '''#.###''' is the player's batting average, '''rounded''' (not truncated) to three decimal places.&lt;br /&gt;
&lt;br /&gt;
The players should be sorted by batting average, with the highest batting average on top.  If two players have the exact same batting average (before rounding occurs), the order between those two players is unimportant.&lt;br /&gt;
&lt;br /&gt;
For example, the correct output for the 1940 season is:&lt;br /&gt;
&amp;lt;!-- Jimmy Brown was 0.280 and Ira Hutchinson was 0.125 --&amp;gt;&lt;br /&gt;
&amp;lt;source lang=&amp;quot;text&amp;quot;&amp;gt;&lt;br /&gt;
Pepper Martin: 0.316&lt;br /&gt;
Walker Cooper: 0.316&lt;br /&gt;
Johnny Mize: 0.314&lt;br /&gt;
Ernie Koy: 0.310&lt;br /&gt;
Enos Slaughter: 0.306&lt;br /&gt;
Joe Medwick: 0.304&lt;br /&gt;
Terry Moore: 0.304&lt;br /&gt;
Joe Orengo: 0.286&lt;br /&gt;
Jimmy Brown: 0.280&lt;br /&gt;
Marty Marion: 0.279&lt;br /&gt;
Don Gutteridge: 0.276&lt;br /&gt;
Johnny Hopp: 0.275&lt;br /&gt;
Creepy Crespi: 0.273&lt;br /&gt;
Mickey Owen: 0.265&lt;br /&gt;
Bill DeLancey: 0.250&lt;br /&gt;
Don Padgett: 0.242&lt;br /&gt;
Stu Martin: 0.238&lt;br /&gt;
Eddie Lake: 0.222&lt;br /&gt;
Hal Epps: 0.214&lt;br /&gt;
Lon Warneke: 0.209&lt;br /&gt;
Harry Walker: 0.185&lt;br /&gt;
Max Lanier: 0.179&lt;br /&gt;
Bill McGee: 0.178&lt;br /&gt;
Carl Doyle: 0.174&lt;br /&gt;
Mort Cooper: 0.157&lt;br /&gt;
Clyde Shoun: 0.145&lt;br /&gt;
Carden Gillenwater: 0.130&lt;br /&gt;
Bob Bowman: 0.067&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Grading ==&lt;br /&gt;
&lt;br /&gt;
We will be grading the following aspects of your work.  There are 50 points total.&lt;br /&gt;
&lt;br /&gt;
'''Assignments (including code) must be committed to Bitbucket by the end of class on the due date (commit early and often). Failing to commit by the end of class on the due date will result in a 0. ''' &lt;br /&gt;
&lt;br /&gt;
Upload your baseball code and a file with your Regular expressions.&lt;br /&gt;
&lt;br /&gt;
# '''Regular Expressions (15 Points):'''&lt;br /&gt;
#* '''Your regex files should contain your regex and nothing else (including delimiters and the like.)'''&lt;br /&gt;
#* Regular Expression 1 Correct and saved in a file named &amp;lt;code&amp;gt;regex1.txt&amp;lt;/code&amp;gt; (5 points)'&lt;br /&gt;
#* Regular Expression 2 Correct and saved in a file named &amp;lt;code&amp;gt;regex2.txt&amp;lt;/code&amp;gt;(5 points)&lt;br /&gt;
#* Regular Expression 3 Correct and saved in a file named &amp;lt;code&amp;gt;regex3.txt&amp;lt;/code&amp;gt;(5 points)&lt;br /&gt;
# '''Baseball Stats Counter (35 Points):'''&lt;br /&gt;
#* Solution is written entirely in Python and saved in a file named &amp;lt;code&amp;gt;baseball.py&amp;lt;/code&amp;gt; (8 points)&lt;br /&gt;
#*: ''Note: Failing to write your code in Python 3 will result is losing, at a minimum, points for this category.''&lt;br /&gt;
#* Correct usage of one or more regular expressions to parse and extract data from each line of the input file (8 points)&lt;br /&gt;
#*: ''Note: You should not be using &amp;lt;code&amp;gt;str.split&amp;lt;/code&amp;gt; to extract data.''&lt;br /&gt;
#* Script prints a usage message if a command line argument is not present (4 points)&lt;br /&gt;
#*: ''Note: For an example of a usage message, see [https://en.wikipedia.org/wiki/Usage_message#Examples this link.]''&lt;br /&gt;
#* Output is correct for all test cases (15 points)&lt;br /&gt;
#*: ''This includes sorting and rounding.''&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 4]]&lt;br /&gt;
[[Category:Modules]]&lt;/div&gt;</summary>
		<author><name>Alex</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Module_4&amp;diff=2533</id>
		<title>Module 4</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Module_4&amp;diff=2533"/>
		<updated>2018-02-21T17:24:37Z</updated>

		<summary type="html">&lt;p&gt;Alex: /* Grading */  Added usage message example.&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;__NOTOC__&lt;br /&gt;
In Module 4, you will learn the fundamentals of Python, a popular scripting language, and Regular Expressions, which give you power in text processing.&lt;br /&gt;
&lt;br /&gt;
This article contains your assignments for Module 4.&lt;br /&gt;
&lt;br /&gt;
== Reading ==&lt;br /&gt;
&lt;br /&gt;
The following articles on the online class wiki textbook contain information that will help you complete the assignments.&lt;br /&gt;
&lt;br /&gt;
* [[Python]]&lt;br /&gt;
* [[Regular Expressions]]&lt;br /&gt;
&lt;br /&gt;
== Individual Assignments ==&lt;br /&gt;
&lt;br /&gt;
=== Learn Python and Regular Expressions ===&lt;br /&gt;
&lt;br /&gt;
Up to this point in CSE 330, you have used only one programming language: PHP.  In Module 4, you will learn a new language: Python.  Before starting this assignment, you should look over the [[Python|online textbook article about Python]].  You should be using version 3 (or greater) of Python. Additionally, you may find it helpful to look over the [[Regular Expressions|online textbook article about Regular Expressions]].&lt;br /&gt;
&lt;br /&gt;
=== Write some Regular Expressions ===&lt;br /&gt;
&lt;br /&gt;
Please write regular expressions that do each the following:&lt;br /&gt;
&lt;br /&gt;
# Match the substring &amp;quot;hello world&amp;quot; in string.&lt;br /&gt;
# Find all words in an input string that contains three consecutive vowels, regardless of case.&lt;br /&gt;
# Match an input string that is '''entirely''' a flight code, of the format AA####, where '''AA''' is a two-letter uppercase airline code, and '''####''' is a three- or four-digit flight number.&lt;br /&gt;
Examples:&lt;br /&gt;
   Note: text in ''[[red]]'' is matched by the regular expression. Each line is a separate test input string.&lt;br /&gt;
   Regex 1:  Programmers will often write ''[[hello world]]'' as their first project with a programming language.&lt;br /&gt;
   Regex 2:  The ''[[gooey]]'' peanut butter and jelly sandwich was a ''[[beauty]]''.&lt;br /&gt;
   Regex 3:  ''[[AA312]]''&lt;br /&gt;
             ''[[AA1298]]''&lt;br /&gt;
             ''[[NW1234]]''&lt;br /&gt;
             ''[[US443]]''&lt;br /&gt;
             US31344&lt;br /&gt;
             AA123 extratext&lt;br /&gt;
&lt;br /&gt;
            &lt;br /&gt;
&lt;br /&gt;
Save your regexes to text files – one each.&lt;br /&gt;
&lt;br /&gt;
=== Baseball Stats Counter ===&lt;br /&gt;
&lt;br /&gt;
The St. Louis Cardinals are the most legendary baseball team in the national league.  In this exercise, you will be creating a Python script that reads box scores from a file and computes the Cardinals' players' batting averages in a particular season.&lt;br /&gt;
&lt;br /&gt;
==== Tips and Instructions ====&lt;br /&gt;
&lt;br /&gt;
* You should write a Python script file to solve this problem.&lt;br /&gt;
* You should use a regular expression to parse players' names, at-bats, hits, and runs from the input file.&lt;br /&gt;
* You may want to create a class to hold and compute information about each player.&lt;br /&gt;
* Your file should take one command-line argument: the path to an input file.  If no path is given, your program should print a usage message.&lt;br /&gt;
&lt;br /&gt;
==== Input ====&lt;br /&gt;
&lt;br /&gt;
Sample input files may be found here: http://classes.engineering.wustl.edu/cse330/content/cardinals/&lt;br /&gt;
&lt;br /&gt;
The top of the file contains a citation, and what follows is an entire season of Cardinals Baseball box scores.  Each game starts with a title; for example:&lt;br /&gt;
&lt;br /&gt;
 === St.Louis Cardinals vs. Chicago Cubs, 1940-04-19 ===&lt;br /&gt;
&lt;br /&gt;
What follows are the performance of each player in that game.  The format of each line is as follows:&lt;br /&gt;
&lt;br /&gt;
 XXX batted # times with # hits and # runs&lt;br /&gt;
&lt;br /&gt;
where '''XXX''' is the player's name (you may assume that the name is unique), and each '''#''' are integers representing the number of &amp;quot;at bats&amp;quot;, the number of &amp;quot;hits&amp;quot;, and the number of &amp;quot;runs&amp;quot;, respectively.&lt;br /&gt;
&lt;br /&gt;
==== Output ====&lt;br /&gt;
&lt;br /&gt;
Your script needs to output all players' batting average across the season.  A player's batting average is that player's total hits divided by that player's total at-bats throughout the entire season.  For example, Johnny Hopp was at bat 149 times in 1940, and he had 41 hits, so his batting average was 0.275.&lt;br /&gt;
&lt;br /&gt;
Each line in the output should have the format:&lt;br /&gt;
&lt;br /&gt;
 XXX: #.###&lt;br /&gt;
&lt;br /&gt;
where '''XXX''' is the player's name, and '''#.###''' is the player's batting average, '''rounded''' (not truncated) to three decimal places.&lt;br /&gt;
&lt;br /&gt;
The players should be sorted by batting average, with the highest batting average on top.  If two players have the exact same batting average (before rounding occurs), the order between those two players is unimportant.&lt;br /&gt;
&lt;br /&gt;
For example, the correct output for the 1940 season is:&lt;br /&gt;
&amp;lt;!-- Jimmy Brown was 0.280 and Ira Hutchinson was 0.125 --&amp;gt;&lt;br /&gt;
&amp;lt;source lang=&amp;quot;text&amp;quot;&amp;gt;&lt;br /&gt;
Pepper Martin: 0.316&lt;br /&gt;
Walker Cooper: 0.316&lt;br /&gt;
Johnny Mize: 0.314&lt;br /&gt;
Ernie Koy: 0.310&lt;br /&gt;
Enos Slaughter: 0.306&lt;br /&gt;
Joe Medwick: 0.304&lt;br /&gt;
Terry Moore: 0.304&lt;br /&gt;
Joe Orengo: 0.286&lt;br /&gt;
Jimmy Brown: 0.280&lt;br /&gt;
Marty Marion: 0.279&lt;br /&gt;
Don Gutteridge: 0.276&lt;br /&gt;
Johnny Hopp: 0.275&lt;br /&gt;
Creepy Crespi: 0.273&lt;br /&gt;
Mickey Owen: 0.265&lt;br /&gt;
Bill DeLancey: 0.250&lt;br /&gt;
Don Padgett: 0.242&lt;br /&gt;
Stu Martin: 0.238&lt;br /&gt;
Eddie Lake: 0.222&lt;br /&gt;
Hal Epps: 0.214&lt;br /&gt;
Lon Warneke: 0.209&lt;br /&gt;
Harry Walker: 0.185&lt;br /&gt;
Max Lanier: 0.179&lt;br /&gt;
Bill McGee: 0.178&lt;br /&gt;
Carl Doyle: 0.174&lt;br /&gt;
Mort Cooper: 0.157&lt;br /&gt;
Clyde Shoun: 0.145&lt;br /&gt;
Carden Gillenwater: 0.130&lt;br /&gt;
Bob Bowman: 0.067&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Grading ==&lt;br /&gt;
&lt;br /&gt;
We will be grading the following aspects of your work.  There are 50 points total.&lt;br /&gt;
&lt;br /&gt;
'''Assignments (including code) must be committed to Bitbucket by the end of class on the due date (commit early and often). Failing to commit by the end of class on the due date will result in a 0. ''' &lt;br /&gt;
&lt;br /&gt;
Upload your baseball code and a file with your Regular expressions.&lt;br /&gt;
&lt;br /&gt;
# '''Regular Expressions (15 Points):'''&lt;br /&gt;
#* Regular Expression 1 Correct and saved in a file named &amp;lt;code&amp;gt;regex1.txt&amp;lt;/code&amp;gt; (5 points)&lt;br /&gt;
#* Regular Expression 2 Correct and saved in a file named &amp;lt;code&amp;gt;regex2.txt&amp;lt;/code&amp;gt;(5 points)&lt;br /&gt;
#* Regular Expression 3 Correct and saved in a file named &amp;lt;code&amp;gt;regex3.txt&amp;lt;/code&amp;gt;(5 points)&lt;br /&gt;
# '''Baseball Stats Counter (35 Points):'''&lt;br /&gt;
#* Solution is written entirely in Python and saved in a file named &amp;lt;code&amp;gt;baseball.py&amp;lt;/code&amp;gt; (8 points)&lt;br /&gt;
#*: ''Note: Failing to write your code in Python 3 will result is losing, at a minimum, points for this category.''&lt;br /&gt;
#* Correct usage of one or more regular expressions to parse and extract data from each line of the input file (8 points)&lt;br /&gt;
#*: ''Note: You should not be using &amp;lt;code&amp;gt;str.split&amp;lt;/code&amp;gt; to extract data.''&lt;br /&gt;
#* Script prints a usage message if a command line argument is not present (4 points)&lt;br /&gt;
#*: ''Note: For an example of a usage message, see [https://en.wikipedia.org/wiki/Usage_message#Examples this link.]''&lt;br /&gt;
#* Output is correct for all test cases (15 points)&lt;br /&gt;
#*: ''This includes sorting and rounding.''&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 4]]&lt;br /&gt;
[[Category:Modules]]&lt;/div&gt;</summary>
		<author><name>Alex</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Module_4&amp;diff=2532</id>
		<title>Module 4</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Module_4&amp;diff=2532"/>
		<updated>2018-02-21T16:57:47Z</updated>

		<summary type="html">&lt;p&gt;Alex: /* Grading */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;__NOTOC__&lt;br /&gt;
In Module 4, you will learn the fundamentals of Python, a popular scripting language, and Regular Expressions, which give you power in text processing.&lt;br /&gt;
&lt;br /&gt;
This article contains your assignments for Module 4.&lt;br /&gt;
&lt;br /&gt;
== Reading ==&lt;br /&gt;
&lt;br /&gt;
The following articles on the online class wiki textbook contain information that will help you complete the assignments.&lt;br /&gt;
&lt;br /&gt;
* [[Python]]&lt;br /&gt;
* [[Regular Expressions]]&lt;br /&gt;
&lt;br /&gt;
== Individual Assignments ==&lt;br /&gt;
&lt;br /&gt;
=== Learn Python and Regular Expressions ===&lt;br /&gt;
&lt;br /&gt;
Up to this point in CSE 330, you have used only one programming language: PHP.  In Module 4, you will learn a new language: Python.  Before starting this assignment, you should look over the [[Python|online textbook article about Python]].  You should be using version 3 (or greater) of Python. Additionally, you may find it helpful to look over the [[Regular Expressions|online textbook article about Regular Expressions]].&lt;br /&gt;
&lt;br /&gt;
=== Write some Regular Expressions ===&lt;br /&gt;
&lt;br /&gt;
Please write regular expressions that do each the following:&lt;br /&gt;
&lt;br /&gt;
# Match the substring &amp;quot;hello world&amp;quot; in string.&lt;br /&gt;
# Find all words in an input string that contains three consecutive vowels, regardless of case.&lt;br /&gt;
# Match an input string that is '''entirely''' a flight code, of the format AA####, where '''AA''' is a two-letter uppercase airline code, and '''####''' is a three- or four-digit flight number.&lt;br /&gt;
Examples:&lt;br /&gt;
   Note: text in ''[[red]]'' is matched by the regular expression. Each line is a separate test input string.&lt;br /&gt;
   Regex 1:  Programmers will often write ''[[hello world]]'' as their first project with a programming language.&lt;br /&gt;
   Regex 2:  The ''[[gooey]]'' peanut butter and jelly sandwich was a ''[[beauty]]''.&lt;br /&gt;
   Regex 3:  ''[[AA312]]''&lt;br /&gt;
             ''[[AA1298]]''&lt;br /&gt;
             ''[[NW1234]]''&lt;br /&gt;
             ''[[US443]]''&lt;br /&gt;
             US31344&lt;br /&gt;
             AA123 extratext&lt;br /&gt;
&lt;br /&gt;
            &lt;br /&gt;
&lt;br /&gt;
Save your regexes to text files – one each.&lt;br /&gt;
&lt;br /&gt;
=== Baseball Stats Counter ===&lt;br /&gt;
&lt;br /&gt;
The St. Louis Cardinals are the most legendary baseball team in the national league.  In this exercise, you will be creating a Python script that reads box scores from a file and computes the Cardinals' players' batting averages in a particular season.&lt;br /&gt;
&lt;br /&gt;
==== Tips and Instructions ====&lt;br /&gt;
&lt;br /&gt;
* You should write a Python script file to solve this problem.&lt;br /&gt;
* You should use a regular expression to parse players' names, at-bats, hits, and runs from the input file.&lt;br /&gt;
* You may want to create a class to hold and compute information about each player.&lt;br /&gt;
* Your file should take one command-line argument: the path to an input file.  If no path is given, your program should print a usage message.&lt;br /&gt;
&lt;br /&gt;
==== Input ====&lt;br /&gt;
&lt;br /&gt;
Sample input files may be found here: http://classes.engineering.wustl.edu/cse330/content/cardinals/&lt;br /&gt;
&lt;br /&gt;
The top of the file contains a citation, and what follows is an entire season of Cardinals Baseball box scores.  Each game starts with a title; for example:&lt;br /&gt;
&lt;br /&gt;
 === St.Louis Cardinals vs. Chicago Cubs, 1940-04-19 ===&lt;br /&gt;
&lt;br /&gt;
What follows are the performance of each player in that game.  The format of each line is as follows:&lt;br /&gt;
&lt;br /&gt;
 XXX batted # times with # hits and # runs&lt;br /&gt;
&lt;br /&gt;
where '''XXX''' is the player's name (you may assume that the name is unique), and each '''#''' are integers representing the number of &amp;quot;at bats&amp;quot;, the number of &amp;quot;hits&amp;quot;, and the number of &amp;quot;runs&amp;quot;, respectively.&lt;br /&gt;
&lt;br /&gt;
==== Output ====&lt;br /&gt;
&lt;br /&gt;
Your script needs to output all players' batting average across the season.  A player's batting average is that player's total hits divided by that player's total at-bats throughout the entire season.  For example, Johnny Hopp was at bat 149 times in 1940, and he had 41 hits, so his batting average was 0.275.&lt;br /&gt;
&lt;br /&gt;
Each line in the output should have the format:&lt;br /&gt;
&lt;br /&gt;
 XXX: #.###&lt;br /&gt;
&lt;br /&gt;
where '''XXX''' is the player's name, and '''#.###''' is the player's batting average, '''rounded''' (not truncated) to three decimal places.&lt;br /&gt;
&lt;br /&gt;
The players should be sorted by batting average, with the highest batting average on top.  If two players have the exact same batting average (before rounding occurs), the order between those two players is unimportant.&lt;br /&gt;
&lt;br /&gt;
For example, the correct output for the 1940 season is:&lt;br /&gt;
&amp;lt;!-- Jimmy Brown was 0.280 and Ira Hutchinson was 0.125 --&amp;gt;&lt;br /&gt;
&amp;lt;source lang=&amp;quot;text&amp;quot;&amp;gt;&lt;br /&gt;
Pepper Martin: 0.316&lt;br /&gt;
Walker Cooper: 0.316&lt;br /&gt;
Johnny Mize: 0.314&lt;br /&gt;
Ernie Koy: 0.310&lt;br /&gt;
Enos Slaughter: 0.306&lt;br /&gt;
Joe Medwick: 0.304&lt;br /&gt;
Terry Moore: 0.304&lt;br /&gt;
Joe Orengo: 0.286&lt;br /&gt;
Jimmy Brown: 0.280&lt;br /&gt;
Marty Marion: 0.279&lt;br /&gt;
Don Gutteridge: 0.276&lt;br /&gt;
Johnny Hopp: 0.275&lt;br /&gt;
Creepy Crespi: 0.273&lt;br /&gt;
Mickey Owen: 0.265&lt;br /&gt;
Bill DeLancey: 0.250&lt;br /&gt;
Don Padgett: 0.242&lt;br /&gt;
Stu Martin: 0.238&lt;br /&gt;
Eddie Lake: 0.222&lt;br /&gt;
Hal Epps: 0.214&lt;br /&gt;
Lon Warneke: 0.209&lt;br /&gt;
Harry Walker: 0.185&lt;br /&gt;
Max Lanier: 0.179&lt;br /&gt;
Bill McGee: 0.178&lt;br /&gt;
Carl Doyle: 0.174&lt;br /&gt;
Mort Cooper: 0.157&lt;br /&gt;
Clyde Shoun: 0.145&lt;br /&gt;
Carden Gillenwater: 0.130&lt;br /&gt;
Bob Bowman: 0.067&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Grading ==&lt;br /&gt;
&lt;br /&gt;
We will be grading the following aspects of your work.  There are 50 points total.&lt;br /&gt;
&lt;br /&gt;
'''Assignments (including code) must be committed to Bitbucket by the end of class on the due date (commit early and often). Failing to commit by the end of class on the due date will result in a 0. ''' &lt;br /&gt;
&lt;br /&gt;
Upload your baseball code and a file with your Regular expressions.&lt;br /&gt;
&lt;br /&gt;
# '''Regular Expressions (15 Points):'''&lt;br /&gt;
#* Regular Expression 1 Correct and saved in a file named &amp;lt;code&amp;gt;regex1.txt&amp;lt;/code&amp;gt; (5 points)&lt;br /&gt;
#* Regular Expression 2 Correct and saved in a file named &amp;lt;code&amp;gt;regex2.txt&amp;lt;/code&amp;gt;(5 points)&lt;br /&gt;
#* Regular Expression 3 Correct and saved in a file named &amp;lt;code&amp;gt;regex3.txt&amp;lt;/code&amp;gt;(5 points)&lt;br /&gt;
# '''Baseball Stats Counter (35 Points):'''&lt;br /&gt;
#* Solution is written entirely in Python and saved in a file named &amp;lt;code&amp;gt;baseball.py&amp;lt;/code&amp;gt; (8 points)&lt;br /&gt;
#*: ''Note: Failing to write your code in Python 3 will result is losing, at a minimum, points for this category.''&lt;br /&gt;
#* Correct usage of one or more regular expressions to parse and extract data from each line of the input file (8 points)&lt;br /&gt;
#*: ''Note: You should not be using &amp;lt;code&amp;gt;str.split&amp;lt;/code&amp;gt; to extract data.''&lt;br /&gt;
#* Script prints a usage message if a command line argument is not present (4 points)&lt;br /&gt;
#* Output is correct for all test cases (15 points)&lt;br /&gt;
#*: ''This includes sorting and rounding.''&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 4]]&lt;br /&gt;
[[Category:Modules]]&lt;/div&gt;</summary>
		<author><name>Alex</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Module_4&amp;diff=2531</id>
		<title>Module 4</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Module_4&amp;diff=2531"/>
		<updated>2018-02-21T16:55:44Z</updated>

		<summary type="html">&lt;p&gt;Alex: /* Write some Regular Expressions */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;__NOTOC__&lt;br /&gt;
In Module 4, you will learn the fundamentals of Python, a popular scripting language, and Regular Expressions, which give you power in text processing.&lt;br /&gt;
&lt;br /&gt;
This article contains your assignments for Module 4.&lt;br /&gt;
&lt;br /&gt;
== Reading ==&lt;br /&gt;
&lt;br /&gt;
The following articles on the online class wiki textbook contain information that will help you complete the assignments.&lt;br /&gt;
&lt;br /&gt;
* [[Python]]&lt;br /&gt;
* [[Regular Expressions]]&lt;br /&gt;
&lt;br /&gt;
== Individual Assignments ==&lt;br /&gt;
&lt;br /&gt;
=== Learn Python and Regular Expressions ===&lt;br /&gt;
&lt;br /&gt;
Up to this point in CSE 330, you have used only one programming language: PHP.  In Module 4, you will learn a new language: Python.  Before starting this assignment, you should look over the [[Python|online textbook article about Python]].  You should be using version 3 (or greater) of Python. Additionally, you may find it helpful to look over the [[Regular Expressions|online textbook article about Regular Expressions]].&lt;br /&gt;
&lt;br /&gt;
=== Write some Regular Expressions ===&lt;br /&gt;
&lt;br /&gt;
Please write regular expressions that do each the following:&lt;br /&gt;
&lt;br /&gt;
# Match the substring &amp;quot;hello world&amp;quot; in string.&lt;br /&gt;
# Find all words in an input string that contains three consecutive vowels, regardless of case.&lt;br /&gt;
# Match an input string that is '''entirely''' a flight code, of the format AA####, where '''AA''' is a two-letter uppercase airline code, and '''####''' is a three- or four-digit flight number.&lt;br /&gt;
Examples:&lt;br /&gt;
   Note: text in ''[[red]]'' is matched by the regular expression. Each line is a separate test input string.&lt;br /&gt;
   Regex 1:  Programmers will often write ''[[hello world]]'' as their first project with a programming language.&lt;br /&gt;
   Regex 2:  The ''[[gooey]]'' peanut butter and jelly sandwich was a ''[[beauty]]''.&lt;br /&gt;
   Regex 3:  ''[[AA312]]''&lt;br /&gt;
             ''[[AA1298]]''&lt;br /&gt;
             ''[[NW1234]]''&lt;br /&gt;
             ''[[US443]]''&lt;br /&gt;
             US31344&lt;br /&gt;
             AA123 extratext&lt;br /&gt;
&lt;br /&gt;
            &lt;br /&gt;
&lt;br /&gt;
Save your regexes to text files – one each.&lt;br /&gt;
&lt;br /&gt;
=== Baseball Stats Counter ===&lt;br /&gt;
&lt;br /&gt;
The St. Louis Cardinals are the most legendary baseball team in the national league.  In this exercise, you will be creating a Python script that reads box scores from a file and computes the Cardinals' players' batting averages in a particular season.&lt;br /&gt;
&lt;br /&gt;
==== Tips and Instructions ====&lt;br /&gt;
&lt;br /&gt;
* You should write a Python script file to solve this problem.&lt;br /&gt;
* You should use a regular expression to parse players' names, at-bats, hits, and runs from the input file.&lt;br /&gt;
* You may want to create a class to hold and compute information about each player.&lt;br /&gt;
* Your file should take one command-line argument: the path to an input file.  If no path is given, your program should print a usage message.&lt;br /&gt;
&lt;br /&gt;
==== Input ====&lt;br /&gt;
&lt;br /&gt;
Sample input files may be found here: http://classes.engineering.wustl.edu/cse330/content/cardinals/&lt;br /&gt;
&lt;br /&gt;
The top of the file contains a citation, and what follows is an entire season of Cardinals Baseball box scores.  Each game starts with a title; for example:&lt;br /&gt;
&lt;br /&gt;
 === St.Louis Cardinals vs. Chicago Cubs, 1940-04-19 ===&lt;br /&gt;
&lt;br /&gt;
What follows are the performance of each player in that game.  The format of each line is as follows:&lt;br /&gt;
&lt;br /&gt;
 XXX batted # times with # hits and # runs&lt;br /&gt;
&lt;br /&gt;
where '''XXX''' is the player's name (you may assume that the name is unique), and each '''#''' are integers representing the number of &amp;quot;at bats&amp;quot;, the number of &amp;quot;hits&amp;quot;, and the number of &amp;quot;runs&amp;quot;, respectively.&lt;br /&gt;
&lt;br /&gt;
==== Output ====&lt;br /&gt;
&lt;br /&gt;
Your script needs to output all players' batting average across the season.  A player's batting average is that player's total hits divided by that player's total at-bats throughout the entire season.  For example, Johnny Hopp was at bat 149 times in 1940, and he had 41 hits, so his batting average was 0.275.&lt;br /&gt;
&lt;br /&gt;
Each line in the output should have the format:&lt;br /&gt;
&lt;br /&gt;
 XXX: #.###&lt;br /&gt;
&lt;br /&gt;
where '''XXX''' is the player's name, and '''#.###''' is the player's batting average, '''rounded''' (not truncated) to three decimal places.&lt;br /&gt;
&lt;br /&gt;
The players should be sorted by batting average, with the highest batting average on top.  If two players have the exact same batting average (before rounding occurs), the order between those two players is unimportant.&lt;br /&gt;
&lt;br /&gt;
For example, the correct output for the 1940 season is:&lt;br /&gt;
&amp;lt;!-- Jimmy Brown was 0.280 and Ira Hutchinson was 0.125 --&amp;gt;&lt;br /&gt;
&amp;lt;source lang=&amp;quot;text&amp;quot;&amp;gt;&lt;br /&gt;
Pepper Martin: 0.316&lt;br /&gt;
Walker Cooper: 0.316&lt;br /&gt;
Johnny Mize: 0.314&lt;br /&gt;
Ernie Koy: 0.310&lt;br /&gt;
Enos Slaughter: 0.306&lt;br /&gt;
Joe Medwick: 0.304&lt;br /&gt;
Terry Moore: 0.304&lt;br /&gt;
Joe Orengo: 0.286&lt;br /&gt;
Jimmy Brown: 0.280&lt;br /&gt;
Marty Marion: 0.279&lt;br /&gt;
Don Gutteridge: 0.276&lt;br /&gt;
Johnny Hopp: 0.275&lt;br /&gt;
Creepy Crespi: 0.273&lt;br /&gt;
Mickey Owen: 0.265&lt;br /&gt;
Bill DeLancey: 0.250&lt;br /&gt;
Don Padgett: 0.242&lt;br /&gt;
Stu Martin: 0.238&lt;br /&gt;
Eddie Lake: 0.222&lt;br /&gt;
Hal Epps: 0.214&lt;br /&gt;
Lon Warneke: 0.209&lt;br /&gt;
Harry Walker: 0.185&lt;br /&gt;
Max Lanier: 0.179&lt;br /&gt;
Bill McGee: 0.178&lt;br /&gt;
Carl Doyle: 0.174&lt;br /&gt;
Mort Cooper: 0.157&lt;br /&gt;
Clyde Shoun: 0.145&lt;br /&gt;
Carden Gillenwater: 0.130&lt;br /&gt;
Bob Bowman: 0.067&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Grading ==&lt;br /&gt;
&lt;br /&gt;
We will be grading the following aspects of your work.  There are 50 points total.&lt;br /&gt;
&lt;br /&gt;
'''Assignments (including code) must be committed to Bitbucket by the end of class on the due date (commit early and often). Failing to commit by the end of class on the due date will result in a 0. ''' &lt;br /&gt;
&lt;br /&gt;
Upload your baseball code and a file with your Regular expressions.&lt;br /&gt;
&lt;br /&gt;
# '''Regular Expressions (15 Points):'''&lt;br /&gt;
#* Regular Expression 1 Correct and saved in a file named &amp;lt;code&amp;gt;regex1.txt&amp;lt;/code&amp;gt; (5 points)&lt;br /&gt;
#* Regular Expression 2 Correct and saved in a file named &amp;lt;code&amp;gt;regex2.txt&amp;lt;/code&amp;gt;(5 points)&lt;br /&gt;
#* Regular Expression 3 Correct and saved in a file named &amp;lt;code&amp;gt;regex3.txt&amp;lt;/code&amp;gt;(5 points)&lt;br /&gt;
# '''Baseball Stats Counter (35 Points):'''&lt;br /&gt;
#* Solution is written entirely in Python and saved in a file named &amp;lt;code&amp;gt;baseball.py&amp;lt;/code&amp;gt; (8 points)&lt;br /&gt;
#* Correct usage of one or more regular expressions to parse and extract data from each line of the input file (8 points)&lt;br /&gt;
#* Script prints a usage message if a command line argument is not present (4 points)&lt;br /&gt;
#* Output is correct for all test cases (15 points)&lt;br /&gt;
#*: ''This includes sorting and rounding.''&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 4]]&lt;br /&gt;
[[Category:Modules]]&lt;/div&gt;</summary>
		<author><name>Alex</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Module_4&amp;diff=2530</id>
		<title>Module 4</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Module_4&amp;diff=2530"/>
		<updated>2018-02-21T16:55:31Z</updated>

		<summary type="html">&lt;p&gt;Alex: /* Write some Regular Expressions */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;__NOTOC__&lt;br /&gt;
In Module 4, you will learn the fundamentals of Python, a popular scripting language, and Regular Expressions, which give you power in text processing.&lt;br /&gt;
&lt;br /&gt;
This article contains your assignments for Module 4.&lt;br /&gt;
&lt;br /&gt;
== Reading ==&lt;br /&gt;
&lt;br /&gt;
The following articles on the online class wiki textbook contain information that will help you complete the assignments.&lt;br /&gt;
&lt;br /&gt;
* [[Python]]&lt;br /&gt;
* [[Regular Expressions]]&lt;br /&gt;
&lt;br /&gt;
== Individual Assignments ==&lt;br /&gt;
&lt;br /&gt;
=== Learn Python and Regular Expressions ===&lt;br /&gt;
&lt;br /&gt;
Up to this point in CSE 330, you have used only one programming language: PHP.  In Module 4, you will learn a new language: Python.  Before starting this assignment, you should look over the [[Python|online textbook article about Python]].  You should be using version 3 (or greater) of Python. Additionally, you may find it helpful to look over the [[Regular Expressions|online textbook article about Regular Expressions]].&lt;br /&gt;
&lt;br /&gt;
=== Write some Regular Expressions ===&lt;br /&gt;
&lt;br /&gt;
Please write regular expressions that do each the following:&lt;br /&gt;
&lt;br /&gt;
# Match the substring &amp;quot;hello world&amp;quot; in string&lt;br /&gt;
# Find all words in an input string that contains three consecutive vowels, regardless of case.&lt;br /&gt;
# Match an input string that is '''entirely''' a flight code, of the format AA####, where '''AA''' is a two-letter uppercase airline code, and '''####''' is a three- or four-digit flight number&lt;br /&gt;
Examples:&lt;br /&gt;
   Note: text in ''[[red]]'' is matched by the regular expression. Each line is a separate test input string.&lt;br /&gt;
   Regex 1:  Programmers will often write ''[[hello world]]'' as their first project with a programming language.&lt;br /&gt;
   Regex 2:  The ''[[gooey]]'' peanut butter and jelly sandwich was a ''[[beauty]]''.&lt;br /&gt;
   Regex 3:  ''[[AA312]]''&lt;br /&gt;
             ''[[AA1298]]''&lt;br /&gt;
             ''[[NW1234]]''&lt;br /&gt;
             ''[[US443]]''&lt;br /&gt;
             US31344&lt;br /&gt;
             AA123 extratext&lt;br /&gt;
&lt;br /&gt;
            &lt;br /&gt;
&lt;br /&gt;
Save your regexes to text files – one each.&lt;br /&gt;
&lt;br /&gt;
=== Baseball Stats Counter ===&lt;br /&gt;
&lt;br /&gt;
The St. Louis Cardinals are the most legendary baseball team in the national league.  In this exercise, you will be creating a Python script that reads box scores from a file and computes the Cardinals' players' batting averages in a particular season.&lt;br /&gt;
&lt;br /&gt;
==== Tips and Instructions ====&lt;br /&gt;
&lt;br /&gt;
* You should write a Python script file to solve this problem.&lt;br /&gt;
* You should use a regular expression to parse players' names, at-bats, hits, and runs from the input file.&lt;br /&gt;
* You may want to create a class to hold and compute information about each player.&lt;br /&gt;
* Your file should take one command-line argument: the path to an input file.  If no path is given, your program should print a usage message.&lt;br /&gt;
&lt;br /&gt;
==== Input ====&lt;br /&gt;
&lt;br /&gt;
Sample input files may be found here: http://classes.engineering.wustl.edu/cse330/content/cardinals/&lt;br /&gt;
&lt;br /&gt;
The top of the file contains a citation, and what follows is an entire season of Cardinals Baseball box scores.  Each game starts with a title; for example:&lt;br /&gt;
&lt;br /&gt;
 === St.Louis Cardinals vs. Chicago Cubs, 1940-04-19 ===&lt;br /&gt;
&lt;br /&gt;
What follows are the performance of each player in that game.  The format of each line is as follows:&lt;br /&gt;
&lt;br /&gt;
 XXX batted # times with # hits and # runs&lt;br /&gt;
&lt;br /&gt;
where '''XXX''' is the player's name (you may assume that the name is unique), and each '''#''' are integers representing the number of &amp;quot;at bats&amp;quot;, the number of &amp;quot;hits&amp;quot;, and the number of &amp;quot;runs&amp;quot;, respectively.&lt;br /&gt;
&lt;br /&gt;
==== Output ====&lt;br /&gt;
&lt;br /&gt;
Your script needs to output all players' batting average across the season.  A player's batting average is that player's total hits divided by that player's total at-bats throughout the entire season.  For example, Johnny Hopp was at bat 149 times in 1940, and he had 41 hits, so his batting average was 0.275.&lt;br /&gt;
&lt;br /&gt;
Each line in the output should have the format:&lt;br /&gt;
&lt;br /&gt;
 XXX: #.###&lt;br /&gt;
&lt;br /&gt;
where '''XXX''' is the player's name, and '''#.###''' is the player's batting average, '''rounded''' (not truncated) to three decimal places.&lt;br /&gt;
&lt;br /&gt;
The players should be sorted by batting average, with the highest batting average on top.  If two players have the exact same batting average (before rounding occurs), the order between those two players is unimportant.&lt;br /&gt;
&lt;br /&gt;
For example, the correct output for the 1940 season is:&lt;br /&gt;
&amp;lt;!-- Jimmy Brown was 0.280 and Ira Hutchinson was 0.125 --&amp;gt;&lt;br /&gt;
&amp;lt;source lang=&amp;quot;text&amp;quot;&amp;gt;&lt;br /&gt;
Pepper Martin: 0.316&lt;br /&gt;
Walker Cooper: 0.316&lt;br /&gt;
Johnny Mize: 0.314&lt;br /&gt;
Ernie Koy: 0.310&lt;br /&gt;
Enos Slaughter: 0.306&lt;br /&gt;
Joe Medwick: 0.304&lt;br /&gt;
Terry Moore: 0.304&lt;br /&gt;
Joe Orengo: 0.286&lt;br /&gt;
Jimmy Brown: 0.280&lt;br /&gt;
Marty Marion: 0.279&lt;br /&gt;
Don Gutteridge: 0.276&lt;br /&gt;
Johnny Hopp: 0.275&lt;br /&gt;
Creepy Crespi: 0.273&lt;br /&gt;
Mickey Owen: 0.265&lt;br /&gt;
Bill DeLancey: 0.250&lt;br /&gt;
Don Padgett: 0.242&lt;br /&gt;
Stu Martin: 0.238&lt;br /&gt;
Eddie Lake: 0.222&lt;br /&gt;
Hal Epps: 0.214&lt;br /&gt;
Lon Warneke: 0.209&lt;br /&gt;
Harry Walker: 0.185&lt;br /&gt;
Max Lanier: 0.179&lt;br /&gt;
Bill McGee: 0.178&lt;br /&gt;
Carl Doyle: 0.174&lt;br /&gt;
Mort Cooper: 0.157&lt;br /&gt;
Clyde Shoun: 0.145&lt;br /&gt;
Carden Gillenwater: 0.130&lt;br /&gt;
Bob Bowman: 0.067&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Grading ==&lt;br /&gt;
&lt;br /&gt;
We will be grading the following aspects of your work.  There are 50 points total.&lt;br /&gt;
&lt;br /&gt;
'''Assignments (including code) must be committed to Bitbucket by the end of class on the due date (commit early and often). Failing to commit by the end of class on the due date will result in a 0. ''' &lt;br /&gt;
&lt;br /&gt;
Upload your baseball code and a file with your Regular expressions.&lt;br /&gt;
&lt;br /&gt;
# '''Regular Expressions (15 Points):'''&lt;br /&gt;
#* Regular Expression 1 Correct and saved in a file named &amp;lt;code&amp;gt;regex1.txt&amp;lt;/code&amp;gt; (5 points)&lt;br /&gt;
#* Regular Expression 2 Correct and saved in a file named &amp;lt;code&amp;gt;regex2.txt&amp;lt;/code&amp;gt;(5 points)&lt;br /&gt;
#* Regular Expression 3 Correct and saved in a file named &amp;lt;code&amp;gt;regex3.txt&amp;lt;/code&amp;gt;(5 points)&lt;br /&gt;
# '''Baseball Stats Counter (35 Points):'''&lt;br /&gt;
#* Solution is written entirely in Python and saved in a file named &amp;lt;code&amp;gt;baseball.py&amp;lt;/code&amp;gt; (8 points)&lt;br /&gt;
#* Correct usage of one or more regular expressions to parse and extract data from each line of the input file (8 points)&lt;br /&gt;
#* Script prints a usage message if a command line argument is not present (4 points)&lt;br /&gt;
#* Output is correct for all test cases (15 points)&lt;br /&gt;
#*: ''This includes sorting and rounding.''&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 4]]&lt;br /&gt;
[[Category:Modules]]&lt;/div&gt;</summary>
		<author><name>Alex</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Module_4&amp;diff=2529</id>
		<title>Module 4</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Module_4&amp;diff=2529"/>
		<updated>2018-02-21T03:07:09Z</updated>

		<summary type="html">&lt;p&gt;Alex: /* Grading */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;__NOTOC__&lt;br /&gt;
In Module 4, you will learn the fundamentals of Python, a popular scripting language, and Regular Expressions, which give you power in text processing.&lt;br /&gt;
&lt;br /&gt;
This article contains your assignments for Module 4.&lt;br /&gt;
&lt;br /&gt;
== Reading ==&lt;br /&gt;
&lt;br /&gt;
The following articles on the online class wiki textbook contain information that will help you complete the assignments.&lt;br /&gt;
&lt;br /&gt;
* [[Python]]&lt;br /&gt;
* [[Regular Expressions]]&lt;br /&gt;
&lt;br /&gt;
== Individual Assignments ==&lt;br /&gt;
&lt;br /&gt;
=== Learn Python and Regular Expressions ===&lt;br /&gt;
&lt;br /&gt;
Up to this point in CSE 330, you have used only one programming language: PHP.  In Module 4, you will learn a new language: Python.  Before starting this assignment, you should look over the [[Python|online textbook article about Python]].  You should be using version 3 (or greater) of Python. Additionally, you may find it helpful to look over the [[Regular Expressions|online textbook article about Regular Expressions]].&lt;br /&gt;
&lt;br /&gt;
=== Write some Regular Expressions ===&lt;br /&gt;
&lt;br /&gt;
Please write regular expressions that do each the following:&lt;br /&gt;
&lt;br /&gt;
# Match the string &amp;quot;hello world&amp;quot; in a sentence&lt;br /&gt;
# Find all words in an input string that contains three consecutive vowels, regardless of case.&lt;br /&gt;
# Match an input string that is '''entirely''' a flight code, of the format AA####, where '''AA''' is a two-letter uppercase airline code, and '''####''' is a three- or four-digit flight number&lt;br /&gt;
Examples:&lt;br /&gt;
   Note: text in ''[[red]]'' is matched by the regular expression. Each line is a separate test input string.&lt;br /&gt;
   Regex 1:  Programmers will often write ''[[hello world]]'' as their first project with a programming language.&lt;br /&gt;
   Regex 2:  The ''[[gooey]]'' peanut butter and jelly sandwich was a ''[[beauty]]''.&lt;br /&gt;
   Regex 3:  ''[[AA312]]''&lt;br /&gt;
             ''[[AA1298]]''&lt;br /&gt;
             ''[[NW1234]]''&lt;br /&gt;
             ''[[US443]]''&lt;br /&gt;
             US31344&lt;br /&gt;
             AA123 extratext&lt;br /&gt;
&lt;br /&gt;
            &lt;br /&gt;
&lt;br /&gt;
Save your regexes to text files – one each.&lt;br /&gt;
&lt;br /&gt;
=== Baseball Stats Counter ===&lt;br /&gt;
&lt;br /&gt;
The St. Louis Cardinals are the most legendary baseball team in the national league.  In this exercise, you will be creating a Python script that reads box scores from a file and computes the Cardinals' players' batting averages in a particular season.&lt;br /&gt;
&lt;br /&gt;
==== Tips and Instructions ====&lt;br /&gt;
&lt;br /&gt;
* You should write a Python script file to solve this problem.&lt;br /&gt;
* You should use a regular expression to parse players' names, at-bats, hits, and runs from the input file.&lt;br /&gt;
* You may want to create a class to hold and compute information about each player.&lt;br /&gt;
* Your file should take one command-line argument: the path to an input file.  If no path is given, your program should print a usage message.&lt;br /&gt;
&lt;br /&gt;
==== Input ====&lt;br /&gt;
&lt;br /&gt;
Sample input files may be found here: http://classes.engineering.wustl.edu/cse330/content/cardinals/&lt;br /&gt;
&lt;br /&gt;
The top of the file contains a citation, and what follows is an entire season of Cardinals Baseball box scores.  Each game starts with a title; for example:&lt;br /&gt;
&lt;br /&gt;
 === St.Louis Cardinals vs. Chicago Cubs, 1940-04-19 ===&lt;br /&gt;
&lt;br /&gt;
What follows are the performance of each player in that game.  The format of each line is as follows:&lt;br /&gt;
&lt;br /&gt;
 XXX batted # times with # hits and # runs&lt;br /&gt;
&lt;br /&gt;
where '''XXX''' is the player's name (you may assume that the name is unique), and each '''#''' are integers representing the number of &amp;quot;at bats&amp;quot;, the number of &amp;quot;hits&amp;quot;, and the number of &amp;quot;runs&amp;quot;, respectively.&lt;br /&gt;
&lt;br /&gt;
==== Output ====&lt;br /&gt;
&lt;br /&gt;
Your script needs to output all players' batting average across the season.  A player's batting average is that player's total hits divided by that player's total at-bats throughout the entire season.  For example, Johnny Hopp was at bat 149 times in 1940, and he had 41 hits, so his batting average was 0.275.&lt;br /&gt;
&lt;br /&gt;
Each line in the output should have the format:&lt;br /&gt;
&lt;br /&gt;
 XXX: #.###&lt;br /&gt;
&lt;br /&gt;
where '''XXX''' is the player's name, and '''#.###''' is the player's batting average, '''rounded''' (not truncated) to three decimal places.&lt;br /&gt;
&lt;br /&gt;
The players should be sorted by batting average, with the highest batting average on top.  If two players have the exact same batting average (before rounding occurs), the order between those two players is unimportant.&lt;br /&gt;
&lt;br /&gt;
For example, the correct output for the 1940 season is:&lt;br /&gt;
&amp;lt;!-- Jimmy Brown was 0.280 and Ira Hutchinson was 0.125 --&amp;gt;&lt;br /&gt;
&amp;lt;source lang=&amp;quot;text&amp;quot;&amp;gt;&lt;br /&gt;
Pepper Martin: 0.316&lt;br /&gt;
Walker Cooper: 0.316&lt;br /&gt;
Johnny Mize: 0.314&lt;br /&gt;
Ernie Koy: 0.310&lt;br /&gt;
Enos Slaughter: 0.306&lt;br /&gt;
Joe Medwick: 0.304&lt;br /&gt;
Terry Moore: 0.304&lt;br /&gt;
Joe Orengo: 0.286&lt;br /&gt;
Jimmy Brown: 0.280&lt;br /&gt;
Marty Marion: 0.279&lt;br /&gt;
Don Gutteridge: 0.276&lt;br /&gt;
Johnny Hopp: 0.275&lt;br /&gt;
Creepy Crespi: 0.273&lt;br /&gt;
Mickey Owen: 0.265&lt;br /&gt;
Bill DeLancey: 0.250&lt;br /&gt;
Don Padgett: 0.242&lt;br /&gt;
Stu Martin: 0.238&lt;br /&gt;
Eddie Lake: 0.222&lt;br /&gt;
Hal Epps: 0.214&lt;br /&gt;
Lon Warneke: 0.209&lt;br /&gt;
Harry Walker: 0.185&lt;br /&gt;
Max Lanier: 0.179&lt;br /&gt;
Bill McGee: 0.178&lt;br /&gt;
Carl Doyle: 0.174&lt;br /&gt;
Mort Cooper: 0.157&lt;br /&gt;
Clyde Shoun: 0.145&lt;br /&gt;
Carden Gillenwater: 0.130&lt;br /&gt;
Bob Bowman: 0.067&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Grading ==&lt;br /&gt;
&lt;br /&gt;
We will be grading the following aspects of your work.  There are 50 points total.&lt;br /&gt;
&lt;br /&gt;
'''Assignments (including code) must be committed to Bitbucket by the end of class on the due date (commit early and often). Failing to commit by the end of class on the due date will result in a 0. ''' &lt;br /&gt;
&lt;br /&gt;
Upload your baseball code and a file with your Regular expressions.&lt;br /&gt;
&lt;br /&gt;
# '''Regular Expressions (15 Points):'''&lt;br /&gt;
#* Regular Expression 1 Correct and saved in a file named &amp;lt;code&amp;gt;regex1.txt&amp;lt;/code&amp;gt; (5 points)&lt;br /&gt;
#* Regular Expression 2 Correct and saved in a file named &amp;lt;code&amp;gt;regex2.txt&amp;lt;/code&amp;gt;(5 points)&lt;br /&gt;
#* Regular Expression 3 Correct and saved in a file named &amp;lt;code&amp;gt;regex3.txt&amp;lt;/code&amp;gt;(5 points)&lt;br /&gt;
# '''Baseball Stats Counter (35 Points):'''&lt;br /&gt;
#* Solution is written entirely in Python and saved in a file named &amp;lt;code&amp;gt;baseball.py&amp;lt;/code&amp;gt; (8 points)&lt;br /&gt;
#* Correct usage of one or more regular expressions to parse and extract data from each line of the input file (8 points)&lt;br /&gt;
#* Script prints a usage message if a command line argument is not present (4 points)&lt;br /&gt;
#* Output is correct for all test cases (15 points)&lt;br /&gt;
#*: ''This includes sorting and rounding.''&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 4]]&lt;br /&gt;
[[Category:Modules]]&lt;/div&gt;</summary>
		<author><name>Alex</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Module_4&amp;diff=2528</id>
		<title>Module 4</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Module_4&amp;diff=2528"/>
		<updated>2018-02-20T23:33:10Z</updated>

		<summary type="html">&lt;p&gt;Alex: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;__NOTOC__&lt;br /&gt;
In Module 4, you will learn the fundamentals of Python, a popular scripting language, and Regular Expressions, which give you power in text processing.&lt;br /&gt;
&lt;br /&gt;
This article contains your assignments for Module 4.&lt;br /&gt;
&lt;br /&gt;
== Reading ==&lt;br /&gt;
&lt;br /&gt;
The following articles on the online class wiki textbook contain information that will help you complete the assignments.&lt;br /&gt;
&lt;br /&gt;
* [[Python]]&lt;br /&gt;
* [[Regular Expressions]]&lt;br /&gt;
&lt;br /&gt;
== Individual Assignments ==&lt;br /&gt;
&lt;br /&gt;
=== Learn Python and Regular Expressions ===&lt;br /&gt;
&lt;br /&gt;
Up to this point in CSE 330, you have used only one programming language: PHP.  In Module 4, you will learn a new language: Python.  Before starting this assignment, you should look over the [[Python|online textbook article about Python]].  You should be using version 3 (or greater) of Python. Additionally, you may find it helpful to look over the [[Regular Expressions|online textbook article about Regular Expressions]].&lt;br /&gt;
&lt;br /&gt;
=== Write some Regular Expressions ===&lt;br /&gt;
&lt;br /&gt;
Please write regular expressions that do each the following:&lt;br /&gt;
&lt;br /&gt;
# Match the string &amp;quot;hello world&amp;quot; in a sentence&lt;br /&gt;
# Find all words in an input string that contains three consecutive vowels, regardless of case.&lt;br /&gt;
# Match an input string that is '''entirely''' a flight code, of the format AA####, where '''AA''' is a two-letter uppercase airline code, and '''####''' is a three- or four-digit flight number&lt;br /&gt;
Examples:&lt;br /&gt;
   Note: text in ''[[red]]'' is matched by the regular expression. Each line is a separate test input string.&lt;br /&gt;
   Regex 1:  Programmers will often write ''[[hello world]]'' as their first project with a programming language.&lt;br /&gt;
   Regex 2:  The ''[[gooey]]'' peanut butter and jelly sandwich was a ''[[beauty]]''.&lt;br /&gt;
   Regex 3:  ''[[AA312]]''&lt;br /&gt;
             ''[[AA1298]]''&lt;br /&gt;
             ''[[NW1234]]''&lt;br /&gt;
             ''[[US443]]''&lt;br /&gt;
             US31344&lt;br /&gt;
             AA123 extratext&lt;br /&gt;
&lt;br /&gt;
            &lt;br /&gt;
&lt;br /&gt;
Save your regexes to text files – one each.&lt;br /&gt;
&lt;br /&gt;
=== Baseball Stats Counter ===&lt;br /&gt;
&lt;br /&gt;
The St. Louis Cardinals are the most legendary baseball team in the national league.  In this exercise, you will be creating a Python script that reads box scores from a file and computes the Cardinals' players' batting averages in a particular season.&lt;br /&gt;
&lt;br /&gt;
==== Tips and Instructions ====&lt;br /&gt;
&lt;br /&gt;
* You should write a Python script file to solve this problem.&lt;br /&gt;
* You should use a regular expression to parse players' names, at-bats, hits, and runs from the input file.&lt;br /&gt;
* You may want to create a class to hold and compute information about each player.&lt;br /&gt;
* Your file should take one command-line argument: the path to an input file.  If no path is given, your program should print a usage message.&lt;br /&gt;
&lt;br /&gt;
==== Input ====&lt;br /&gt;
&lt;br /&gt;
Sample input files may be found here: http://classes.engineering.wustl.edu/cse330/content/cardinals/&lt;br /&gt;
&lt;br /&gt;
The top of the file contains a citation, and what follows is an entire season of Cardinals Baseball box scores.  Each game starts with a title; for example:&lt;br /&gt;
&lt;br /&gt;
 === St.Louis Cardinals vs. Chicago Cubs, 1940-04-19 ===&lt;br /&gt;
&lt;br /&gt;
What follows are the performance of each player in that game.  The format of each line is as follows:&lt;br /&gt;
&lt;br /&gt;
 XXX batted # times with # hits and # runs&lt;br /&gt;
&lt;br /&gt;
where '''XXX''' is the player's name (you may assume that the name is unique), and each '''#''' are integers representing the number of &amp;quot;at bats&amp;quot;, the number of &amp;quot;hits&amp;quot;, and the number of &amp;quot;runs&amp;quot;, respectively.&lt;br /&gt;
&lt;br /&gt;
==== Output ====&lt;br /&gt;
&lt;br /&gt;
Your script needs to output all players' batting average across the season.  A player's batting average is that player's total hits divided by that player's total at-bats throughout the entire season.  For example, Johnny Hopp was at bat 149 times in 1940, and he had 41 hits, so his batting average was 0.275.&lt;br /&gt;
&lt;br /&gt;
Each line in the output should have the format:&lt;br /&gt;
&lt;br /&gt;
 XXX: #.###&lt;br /&gt;
&lt;br /&gt;
where '''XXX''' is the player's name, and '''#.###''' is the player's batting average, '''rounded''' (not truncated) to three decimal places.&lt;br /&gt;
&lt;br /&gt;
The players should be sorted by batting average, with the highest batting average on top.  If two players have the exact same batting average (before rounding occurs), the order between those two players is unimportant.&lt;br /&gt;
&lt;br /&gt;
For example, the correct output for the 1940 season is:&lt;br /&gt;
&amp;lt;!-- Jimmy Brown was 0.280 and Ira Hutchinson was 0.125 --&amp;gt;&lt;br /&gt;
&amp;lt;source lang=&amp;quot;text&amp;quot;&amp;gt;&lt;br /&gt;
Pepper Martin: 0.316&lt;br /&gt;
Walker Cooper: 0.316&lt;br /&gt;
Johnny Mize: 0.314&lt;br /&gt;
Ernie Koy: 0.310&lt;br /&gt;
Enos Slaughter: 0.306&lt;br /&gt;
Joe Medwick: 0.304&lt;br /&gt;
Terry Moore: 0.304&lt;br /&gt;
Joe Orengo: 0.286&lt;br /&gt;
Jimmy Brown: 0.280&lt;br /&gt;
Marty Marion: 0.279&lt;br /&gt;
Don Gutteridge: 0.276&lt;br /&gt;
Johnny Hopp: 0.275&lt;br /&gt;
Creepy Crespi: 0.273&lt;br /&gt;
Mickey Owen: 0.265&lt;br /&gt;
Bill DeLancey: 0.250&lt;br /&gt;
Don Padgett: 0.242&lt;br /&gt;
Stu Martin: 0.238&lt;br /&gt;
Eddie Lake: 0.222&lt;br /&gt;
Hal Epps: 0.214&lt;br /&gt;
Lon Warneke: 0.209&lt;br /&gt;
Harry Walker: 0.185&lt;br /&gt;
Max Lanier: 0.179&lt;br /&gt;
Bill McGee: 0.178&lt;br /&gt;
Carl Doyle: 0.174&lt;br /&gt;
Mort Cooper: 0.157&lt;br /&gt;
Clyde Shoun: 0.145&lt;br /&gt;
Carden Gillenwater: 0.130&lt;br /&gt;
Bob Bowman: 0.067&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Grading ==&lt;br /&gt;
&lt;br /&gt;
We will be grading the following aspects of your work.  There are 50 points total.&lt;br /&gt;
&lt;br /&gt;
'''Assignments (including code) must be committed to Bitbucket by the end of class on the due date (commit early and often). Failing to commit by the end of class on the due date will result in a 0. ''' &lt;br /&gt;
&lt;br /&gt;
Upload your baseball code, a file with your Regular expressions, and a screenshot of your python output onto Bitbucket.&lt;br /&gt;
&lt;br /&gt;
# '''Regular Expressions (15 Points):'''&lt;br /&gt;
#* Regular Expression 1 Correct and saved in a file named &amp;lt;code&amp;gt;regex1.txt&amp;lt;/code&amp;gt; (5 points)&lt;br /&gt;
#* Regular Expression 2 Correct and saved in a file named &amp;lt;code&amp;gt;regex2.txt&amp;lt;/code&amp;gt;(5 points)&lt;br /&gt;
#* Regular Expression 3 Correct and saved in a file named &amp;lt;code&amp;gt;regex3.txt&amp;lt;/code&amp;gt;(5 points)&lt;br /&gt;
# '''Baseball Stats Counter (35 Points):'''&lt;br /&gt;
#* Solution is written entirely in Python and saved in a file named &amp;lt;code&amp;gt;baseball.py&amp;lt;/code&amp;gt; (8 points)&lt;br /&gt;
#* Correct usage of one or more regular expressions to parse and extract data from each line of the input file (8 points)&lt;br /&gt;
#* Script prints a usage message if a command line argument is not present (4 points)&lt;br /&gt;
#* Output is correct for all test cases (15 points)&lt;br /&gt;
#*: ''This includes sorting and rounding.''&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 4]]&lt;br /&gt;
[[Category:Modules]]&lt;/div&gt;</summary>
		<author><name>Alex</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Python&amp;diff=2527</id>
		<title>Python</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Python&amp;diff=2527"/>
		<updated>2018-02-19T18:24:46Z</updated>

		<summary type="html">&lt;p&gt;Alex: /* File I/O */  f-strings&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Languages like Java and C++ have lots of rules regarding variable types, syntax, return values, and so on. These can be cumbersome when you are trying to write short, quick scripts to perform tasks. This is where a ''scripting language'' comes into play.&lt;br /&gt;
&lt;br /&gt;
'''Python''' is a language well-suited to rapid prototype development. It is generally an ''interpreted language'', which means that, generally speaking, a Python program is converted line by line into instructions for the computer to execute as the program runs, instead of having a separate compilation step beforehand {{ref|interpreted}}. The syntax is clean, and it is usually clear at first glance what is going on when you write in Python.&lt;br /&gt;
&lt;br /&gt;
= Installation =&lt;br /&gt;
&lt;br /&gt;
Python may already be installed on your system. To see whether or not it is, enter the command&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ python3 --version&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If it tells you a version of Python '''greater than or equal to 3.6''' then you're good to go. If not, you need to do a quick package install to get it up and running. Using yum, it's just &amp;lt;code&amp;gt;sudo yum install python36&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
If you'd like to be able to just type &amp;lt;code&amp;gt;python&amp;lt;/code&amp;gt; instead of &amp;lt;code&amp;gt;python3&amp;lt;/code&amp;gt;, you can add the following line to the &amp;lt;code&amp;gt;~/.bashrc&amp;lt;/code&amp;gt; file on your instance:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
alias python=&amp;quot;/usr/bin/python3&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Python 2 vs Python 3 ====&lt;br /&gt;
&lt;br /&gt;
In 2008, a new version of Python – Python 3 – was released, with a number of changes that made it incompatible with the previous version, Python 2. For several years, the Python community was slow to make the change to Python 3, but today, Python 3 is ''the'' standard for new code. The ''only'' reason to write Python 2 code today is because you have to work in an environment or with libraries that do not support Python 3, and that situation is becoming increasingly rare.&lt;br /&gt;
&lt;br /&gt;
'''For CSE 330 (and this guide), you ''must'' use Python 3.6 or greater.'''&lt;br /&gt;
&lt;br /&gt;
=== Pip ===&lt;br /&gt;
&lt;br /&gt;
Linux distributions have package managers like ''Apt'', ''Yum'', and ''YaST''. PHP has a package manager named ''PEAR''. It's now time to introduce Python's leading package manager: '''pip'''.&lt;br /&gt;
&lt;br /&gt;
Once you have pip installed, you can use it to install Python packages. Use the &amp;lt;code&amp;gt;pip-3.6&amp;lt;/code&amp;gt; command:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ pip-3.6 install package_name # RHEL&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
If you'd like to be able to just type &amp;lt;code&amp;gt;pip&amp;lt;/code&amp;gt; instead of &amp;lt;code&amp;gt;pip-3.6&amp;lt;/code&amp;gt;, you can add the following line to the &amp;lt;code&amp;gt;~/.bashrc&amp;lt;/code&amp;gt; file on your instance:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
alias pip=&amp;quot;/usr/bin/pip-3.6&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Running Python =&lt;br /&gt;
&lt;br /&gt;
There are two common ways to run Python code: via the console, and via a Python script file.&lt;br /&gt;
&lt;br /&gt;
=== The Python Console ===&lt;br /&gt;
&lt;br /&gt;
The Python console enables you to experiment with code without opening a text editor. To enter the Python console, simply type the ''python'' command at the terminal:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ python3&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
To leave the interactive console, either type &amp;lt;code&amp;gt;quit()&amp;lt;/code&amp;gt; or press &amp;lt;code&amp;gt;Ctrl-D&amp;lt;/code&amp;gt; (on both Mac and Windows).&lt;br /&gt;
&lt;br /&gt;
=== Python Script Files ===&lt;br /&gt;
&lt;br /&gt;
You can also save Python script files for later use. The extension for Python scripts is &amp;lt;code&amp;gt;*.py&amp;lt;/code&amp;gt;. To run a script file, simply feed its path as an argument to the &amp;lt;code&amp;gt;python&amp;lt;/code&amp;gt; command in Terminal:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ python3 my_script.py&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Python Syntax and Language Components =&lt;br /&gt;
&lt;br /&gt;
This section contains a very brief overview of Python syntax. For a more comprehensive introduction, see [http://docs.python.org/tutorial/ the Python docs].&lt;br /&gt;
&lt;br /&gt;
=== Python's Type System ===&lt;br /&gt;
&lt;br /&gt;
Python is a dynamically-typed, strongly-typed, and duck-typed language. What does that mean? Well, let's take those categories one by one:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;ol&amp;gt;&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
'''Dynamic typing''', in contrast to ''static typing'' means that the types of objects can be changed. In Java, for instance, if you tried to write the following code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
int c = 2;&lt;br /&gt;
c = &amp;quot;fish&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Your code would fail to compile, because the Java compiler wouldn't allow you to change the type of the variable &amp;lt;code&amp;gt;c&amp;lt;/code&amp;gt; from &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt; to &amp;lt;code&amp;gt;String&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Python, however, is just fine with that. You can write:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
c = 2&lt;br /&gt;
c = &amp;quot;fish&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
And Python will happily do what you ask.&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
'''Strong typing''', in contrast to ''weak typing'', means, roughly, that a language won't implicitly convert types for you. So far, you've used a lot of PHP, which is very weakly typed. For example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;php&amp;quot;&amp;gt;&lt;br /&gt;
echo &amp;quot;10&amp;quot; . 2;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In PHP, this works just fine. The PHP interpreter sees that &amp;lt;code&amp;gt;2&amp;lt;/code&amp;gt; is an int, and silently converts it to a string for you, so that &amp;lt;code&amp;gt;&amp;quot;10&amp;quot;. 2&amp;lt;/code&amp;gt; equals &amp;lt;code&amp;gt;&amp;quot;102&amp;quot;&amp;lt;/code&amp;gt;. The problem with weak typing is that it can make it unclear to the programmer why things are happening the way they are. For instance, in PHP, the expression &amp;lt;code&amp;gt;&amp;quot;10&amp;quot; == 10&amp;lt;/code&amp;gt; is true, which can be less than obvious. Python, however, tries to disallow that sort of thing:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
&amp;quot;10&amp;quot; + &amp;quot;10&amp;quot; # Allowed – concatenates the two strings.&lt;br /&gt;
10   +  10  # Allowed – adds the two ints.&lt;br /&gt;
&amp;quot;10&amp;quot; +  10  # Not allowed – raises a TypeError&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Perhaps the one exception to this rule is the relationship between numeric types; it's perfectly fine to add a float to an int, for example.&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
'''Duck-typing''' is a little bit different than the other categories, because it doesn't really have a direct opposite. Essentially, duck-typing is the philosophy that &amp;quot;If it walks like a duck, and quacks like a duck, it's a duck.&amp;quot; In programming terms, that means that we often don't care what type an object is, as long as it can do the things we ask.&lt;br /&gt;
&lt;br /&gt;
Let's look at an example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
# This function doubles the value it's passed.&lt;br /&gt;
def double(thing):&lt;br /&gt;
    return thing + thing&lt;br /&gt;
double(10) # Returns 20&lt;br /&gt;
double(&amp;quot;fish&amp;quot;) # Returns &amp;quot;fishfish&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If this were Java, we'd have to write two different methods here: one for things of type &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt;, and one for things of type &amp;lt;code&amp;gt;String&amp;lt;/code&amp;gt;. Since this is Python, though, we don't have to do that. Instead, Python lets us say, essentially: &amp;quot;This function uses the &amp;lt;code&amp;gt;+&amp;lt;/code&amp;gt; operator, so you can pass whatever object you want to the function, as long as the function supports the &amp;lt;code&amp;gt;+&amp;lt;/code&amp;gt; operator&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
To quote [https://groups.google.com/forum/?hl=en#!msg/comp.lang.python/CCs2oJdyuzc/NYjla5HKMOIJ Alex Martelli], one of the key people in the Python project,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;blockquote&amp;gt;&lt;br /&gt;
&amp;quot;[Don't] check whether it IS-a duck: check whether it QUACKS-like-a duck, WALKS-like-a duck, etc, etc, depending on exactly what subset of duck-like behaviour you need.&amp;quot;&lt;br /&gt;
&amp;lt;/blockquote&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&amp;lt;/ol&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Basic Types ===&lt;br /&gt;
&lt;br /&gt;
In Python, the basic scalar types are:&lt;br /&gt;
&lt;br /&gt;
# &amp;lt;code&amp;gt;str&amp;lt;/code&amp;gt; – a string.&lt;br /&gt;
# &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt; – an integer object with unlimited digits.&lt;br /&gt;
# &amp;lt;code&amp;gt;bool&amp;lt;/code&amp;gt; – a Boolean value.&lt;br /&gt;
# &amp;lt;code&amp;gt;float&amp;lt;/code&amp;gt; – a floating point number; generally equivalent to &amp;lt;code&amp;gt;double&amp;lt;/code&amp;gt; in Java.&lt;br /&gt;
# &amp;lt;code&amp;gt;bytes&amp;lt;/code&amp;gt; – represents a collection of bytes; you're unlikely to use this often.&lt;br /&gt;
&lt;br /&gt;
Casting is done in the C style - to parse an &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt; from a string, for instance, you'd write &amp;lt;code&amp;gt;int(&amp;quot;123&amp;quot;)&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== Basic Control Flow ===&lt;br /&gt;
In Python, blocks of code are delineated using colons and indentation instead of curly braces. '''''That means that proper indentation is mandatory.''''' Every time you use a colon, you must indent one step further, and every time a block ends, you must unindent a step.&lt;br /&gt;
&lt;br /&gt;
Conditional statements are done using the &amp;lt;code&amp;gt;if&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;elif&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;else&amp;lt;/code&amp;gt; operators, like in the example below - pay attention to the indentation:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
cookies_left = 10&lt;br /&gt;
cake_slices_left = 3&lt;br /&gt;
if cookies_left &amp;gt; 10:&lt;br /&gt;
    print(&amp;quot;Lots of cookies!&amp;quot;)&lt;br /&gt;
elif cookies_left &amp;gt; 8:&lt;br /&gt;
    print(&amp;quot;Plenty left!&amp;quot;)&lt;br /&gt;
elif cookies_left == 5:&lt;br /&gt;
    print(&amp;quot;Halfway done!&amp;quot;)&lt;br /&gt;
else:&lt;br /&gt;
    if cake_slices_left == 3:&lt;br /&gt;
        print(&amp;quot;Lots of cake!&amp;quot;)&lt;br /&gt;
    elif cake_slices_left == 2:&lt;br /&gt;
        print(&amp;quot;One slice gone!&amp;quot;)&lt;br /&gt;
    else:&lt;br /&gt;
        print(&amp;quot;Little to no cake left!&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== An Example Python Script ===&lt;br /&gt;
&lt;br /&gt;
In my mind, there's no better way to learn Python than to be immersed in a simple example script.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
print(&amp;quot;Hello World&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
fruits = [&amp;quot;apple&amp;quot;, &amp;quot;banana&amp;quot;, &amp;quot;cherry&amp;quot;, &amp;quot;date&amp;quot;]&lt;br /&gt;
for fruit in fruits:&lt;br /&gt;
    print(f&amp;quot;I always love to eat a fresh {fruit}&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Map the fruits list over to a new list containing the length of the fruit strings:&lt;br /&gt;
fruit_size = [len(fruit) for fruit in fruits]&lt;br /&gt;
&lt;br /&gt;
avg_fruit_size = sum(fruit_size) / len(fruit_size)&lt;br /&gt;
print(f&amp;quot;The average fruit string length is {avg_fruit_size:.2f}.&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Some things to notice:&lt;br /&gt;
&lt;br /&gt;
* Printing is achieved using the &amp;lt;code&amp;gt;print()&amp;lt;/code&amp;gt; function.&lt;br /&gt;
* Comments start with a pound symbol &amp;lt;code&amp;gt;#&amp;lt;/code&amp;gt;.&lt;br /&gt;
* We can transform/map a list to a new list in just one line!&lt;br /&gt;
&lt;br /&gt;
For some more examples, see [https://wiki.python.org/moin/SimplePrograms the Python wiki].&lt;br /&gt;
&lt;br /&gt;
=== A Few Gotchas ===&lt;br /&gt;
&lt;br /&gt;
Here are a few things you may not expect when starting out with Python:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;ol&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
Strings can be delimited using either single quotes (&amp;lt;code&amp;gt;'&amp;lt;/code&amp;gt;) or double quotes (&amp;lt;code&amp;gt;&amp;quot;&amp;lt;/code&amp;gt;), so &amp;lt;code&amp;gt;'Python'&amp;lt;/code&amp;gt; is the same as &amp;lt;code&amp;gt;&amp;quot;Python&amp;quot;&amp;lt;/code. You can also use three sets of quotes (&amp;lt;code&amp;gt;'''&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;&amp;quot;&amp;quot;&amp;quot;&amp;lt;/code&amp;gt;) to delineate a multiple-line string, like so:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
long_string = &amp;quot;&amp;quot;&amp;quot;This&lt;br /&gt;
is my&lt;br /&gt;
very long&lt;br /&gt;
multiple-line&lt;br /&gt;
string&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
To compare the equality of two objects, use the &amp;lt;code&amp;gt;==&amp;lt;/code&amp;gt; operator. To compare the identity of two objects (i.e. whether or not they are literally the same object, at the same place in memory), use the &amp;lt;code&amp;gt;is&amp;lt;/code&amp;gt; operator. These correspond, respectively to &amp;lt;code&amp;gt;.equals()&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;==&amp;lt;/code&amp;gt; in Java.&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
The &amp;lt;code&amp;gt;/&amp;lt;/code&amp;gt; operator performs floating-point division, not integer division, even when both its arguments are integers. If you want to do integer division, use the &amp;lt;code&amp;gt;//&amp;lt;/code&amp;gt; operator. Let's look at an example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
9   / 10    == 0.9 # Floating-point division&lt;br /&gt;
9.0 / 10.0  == 0.9 # Floating-point division&lt;br /&gt;
9   // 10   == 0   # Integer division&lt;br /&gt;
9.0 // 10.0 == 0.0 # Integer division, even though the resulting value is a float&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
As discussed in the section [[#Python's_Type_System|Python's Type System]], you can't combine strings and numbers using the &amp;lt;code&amp;gt;+&amp;lt;/code&amp;gt; operator. Instead, you'll have to use one of the following methods of string formatting:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
  &lt;br /&gt;
# Technique 1 – printf-style Formatting&lt;br /&gt;
# This is a classic style of string formatting, used in many programming languages, including in Java's String.format.&lt;br /&gt;
&amp;quot;You scored %d out of %d!&amp;quot; % (score, questions)&lt;br /&gt;
&lt;br /&gt;
# Technique 2 – str.format&lt;br /&gt;
&amp;quot;You scored {} out of {}!&amp;quot;.format(score, questions)&lt;br /&gt;
&lt;br /&gt;
# Technique 3 – f-strings&lt;br /&gt;
# These were only introduced in Python 3.6 but they're very convenient.&lt;br /&gt;
f&amp;quot;You scored {score} out of {questions}!&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# Technique 4 - String Concatenation&lt;br /&gt;
# This is fine for small things, but for more complicated stuff, use one of the other techniques.&lt;br /&gt;
&amp;quot;You scored &amp;quot; + str(score) + &amp;quot; out of &amp;quot; + str(questions) + &amp;quot;!&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&amp;lt;/ol&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Functions ===&lt;br /&gt;
&lt;br /&gt;
Define functions using the &amp;lt;code&amp;gt;def&amp;lt;/code&amp;gt; keyword:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def hello(name):&lt;br /&gt;
    print(f&amp;quot;Hello, {name}!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Invoke functions using parentheses:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
hello(&amp;quot;Batman&amp;quot;)&lt;br /&gt;
hello(&amp;quot;Superman&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Functions can have optional arguments; however, these must come after any required arguments:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def hello(name=&amp;quot;User&amp;quot;):&lt;br /&gt;
    print(f&amp;quot;Hello, {name}!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
hello() # Prints &amp;quot;Hello, User!&amp;quot;&lt;br /&gt;
hello(&amp;quot;Sarah&amp;quot;) # Prints &amp;quot;Hello, Sarah!&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Functions are just regular objects in Python, meaning you can do stuff like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def hello(name=&amp;quot;User&amp;quot;):&lt;br /&gt;
    print(f&amp;quot;Hello, {name}!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
greeting = hello&lt;br /&gt;
&lt;br /&gt;
greeting(&amp;quot;Siwei&amp;quot;) # Prints &amp;quot;Hello, Siwei!&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Collection Types ===&lt;br /&gt;
Python has a few basic, built-in collection types. They each have their own special use cases, but they share a lot of similarities. All built-in data structures in Python are zero-indexed, for instance.&lt;br /&gt;
&lt;br /&gt;
To obtain the number of elements in a collection, use the &amp;lt;code&amp;gt;len()&amp;lt;/code&amp;gt; function, like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish'] # This is a list; you'll learn about them below.&lt;br /&gt;
&lt;br /&gt;
len(pets) # Returns 3&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To check if a collection contains an item, use the &amp;lt;code&amp;gt;in&amp;lt;/code&amp;gt; operator:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish'] # This is a list; you'll learn about them below.&lt;br /&gt;
&lt;br /&gt;
'Dog' in pets # Returns True&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Helpfully, the Python Software Foundation maintains a page containing the asymptotic complexities of important operations on major Python data structures. It's available [https://wiki.python.org/moin/TimeComplexity here].&lt;br /&gt;
&lt;br /&gt;
==== Lists ====&lt;br /&gt;
&lt;br /&gt;
Unlike languages like Java and C, Python's array-like type doesn't have fixed length. Instead, a &amp;lt;code&amp;gt;list&amp;lt;/code&amp;gt; is a dynamic array (like Java's &amp;lt;code&amp;gt;ArrayList&amp;lt;/code&amp;gt;) of objects of any type. Here's an example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = [&amp;quot;Apple&amp;quot;, &amp;quot;Pear&amp;quot;, &amp;quot;Orange&amp;quot;] # Lists can be creating by placing their items between square brackets&lt;br /&gt;
&lt;br /&gt;
random_items = ['Apple', 12312, 2.0, [1, 2, 3]] # Lists can contain objects of different types - even other lists!&lt;br /&gt;
&lt;br /&gt;
pets.append('Turtle') # Adds 'Turtle' to the end of pets&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For the next few examples, we'll be using the following list:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish', 'Turtle', 'Lizard', 'Snake']&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access or assign elements of a list, use the &amp;lt;code&amp;gt;[]&amp;lt;/code&amp;gt; operator.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[0] # Returns 'Dog'&lt;br /&gt;
pets[1] = 'Cow' # Sets pets[1] to 'Cow'&lt;br /&gt;
pets[1] = 'Cat' # Sets pets[1] back to 'Cat' &lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You can also access or assign lists using negative indices, which will return elements starting from the end of the list:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[-1] # Returns 'Snake'&lt;br /&gt;
pets[-2] # Returns 'Lizard'&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You can also use 'slice notation' to obtain or assign subsets of lists:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[start:end] # Returns items from index start to index end - 1.&lt;br /&gt;
pets[start:]    # Returns items from index start to the end of the list, inclusive.&lt;br /&gt;
pets[:end]      # Returns items from the beginning of the list to index end - 1.&lt;br /&gt;
pets[:]         # Returns every item in the list&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
There's also a third, optional argument: &amp;lt;code&amp;gt;step&amp;lt;/code&amp;gt;, which lets you jump over values:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[start:end:step] # Returns items from index start to index end - 1, jumping step values at a time&lt;br /&gt;
&lt;br /&gt;
# Examples:&lt;br /&gt;
pets[1:5:2] # Returns items from index 1 to index 4, jumping 2 at a time, so ['Cat', 'Turtle']&lt;br /&gt;
pets[::3] # Returns all items in the list, jumping 3 at a time, so ['Dog', 'Turtle']&lt;br /&gt;
pets[::-1] # Returns all items in the list, jumping -1 at a time. This reverses the list, so ['Snake', 'Lizard', 'Turtle', 'Fish', 'Cat', 'Dog']&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Lists have all the performance characteristics you'd expect of a dynamic array - constant-time indexing, amortized constant-time appends, and so on.&lt;br /&gt;
&lt;br /&gt;
==== Tuples ====&lt;br /&gt;
&lt;br /&gt;
Python has a special data type called &amp;lt;code&amp;gt;tuple&amp;lt;/code&amp;gt;, which is exactly the same as a list except for the fact that it cannot be modified, so you can't append or replace items.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
cities = ('St. Louis', 'Los Angeles', 'Seattle') # Tuples are defined using parentheses.&lt;br /&gt;
numbers = 1, 2, 3 # You can also omit the parentheses if it's unambiguous&lt;br /&gt;
single_item_tuple = (1,) # To make a tuple with only one item, put a comma after it&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Tuples also enable you to have multiple return values from a function:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def compute_length(string):&lt;br /&gt;
    str_len = len(string)&lt;br /&gt;
    if str_len &amp;lt; 5:&lt;br /&gt;
        return str_len, &amp;quot;short&amp;quot;&lt;br /&gt;
    elif str_len &amp;lt; 40:&lt;br /&gt;
        return str_len, &amp;quot;medium&amp;quot;&lt;br /&gt;
    return str_len, &amp;quot;long&amp;quot;&lt;br /&gt;
&lt;br /&gt;
length, description = compute_length(&amp;quot;Four score and seven years ago&amp;quot;)&lt;br /&gt;
print(f&amp;quot;The {description} string is {length} characters long.&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
The above example also demonstrates Python's if...elif...else conditional structure.&lt;br /&gt;
&lt;br /&gt;
==== Dictionaries ====&lt;br /&gt;
&lt;br /&gt;
Python has another datatype called a '''dictionary''' (or &amp;lt;code&amp;gt;dict&amp;lt;/code&amp;gt;, for short), which are like ''Maps'' in Java, ''associative arrays'' in PHP, and ''object literals'' in JavaScript (coming up soon in Module 6). Essentially, they enable you to use any immutable object as the key in your data structure. &amp;lt;code&amp;gt;dict&amp;lt;/code&amp;gt; objects can be created using either the &amp;lt;code&amp;gt;dict&amp;lt;/code&amp;gt; function, or by placing items between curly braces, separating keys and values using colons:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits_in_bowl = {&lt;br /&gt;
    'apple': 4,&lt;br /&gt;
    'banana': 2,&lt;br /&gt;
    'cherry': 0,&lt;br /&gt;
    'date': 12&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
apple_count = fruits_in_bowl['apple'] # Equals 4&lt;br /&gt;
&lt;br /&gt;
fruits_in_bowl['pear'] = 9 # Sets 'pear' in the dictionary to 9.&lt;br /&gt;
&lt;br /&gt;
for fruit, num in fruits_in_bowl.items():&lt;br /&gt;
    print(f&amp;quot;There are {num} {fruit}(s) in the bowl.&amp;quot; % (num, fruit))&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If you only want the keys from a dictionary, you can just iterate over it directly, like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
for fruit in fruits_in_bowl:&lt;br /&gt;
    print(fruit)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If you want only the values but not the keys from a dictionary, use &amp;lt;code&amp;gt;my_dictionary.values()&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
==== Sets ==== &lt;br /&gt;
A &amp;lt;code&amp;gt;set&amp;lt;/code&amp;gt; is an unordered collection of unique items, with constant-time membership checking. &lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = {'Apple', 'Apple', 'Apple', 'Pear'} # The set removes duplicates, so it will only contain {'Apple', 'Pear'}&lt;br /&gt;
fruits = set(['Apple', 'Apple', 'Apple', 'Pear']) # This line transforms a list into a set&lt;br /&gt;
print('Apple' in fruits) # Constant-time!&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Loops ===&lt;br /&gt;
&lt;br /&gt;
In Python, while loops are written like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
i = 0&lt;br /&gt;
while i &amp;lt; 10:&lt;br /&gt;
    i += 1&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
For loops are written like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish']&lt;br /&gt;
&lt;br /&gt;
for pet in pets:&lt;br /&gt;
    print(pet)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
To iterate over a range of numbers, you can use the convenient &amp;lt;code&amp;gt;range&amp;lt;/code&amp;gt; function, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
for i in range(20, 30): # If you omit the first argument to range, it's assumed to be zero.&lt;br /&gt;
    print(i)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Note that &amp;lt;code&amp;gt;range&amp;lt;/code&amp;gt; provides a closed-open range. That is to say, it is inclusive of its lower bound and exclusive of its upper bound. To be very explicit about it:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
list(range(3, 6)) == [3, 4, 5]&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Unlike in other languages you may know, the following is not good practice in Python:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish']&lt;br /&gt;
&lt;br /&gt;
# BAD PRACTICE. DO NOT USE.&lt;br /&gt;
for i in range(len(pets)):&lt;br /&gt;
    pet = pets[i]&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Instead, if you need to access both a variable and its index, use the &amp;lt;code&amp;gt;enumerate&amp;lt;/code&amp;gt; function, which allows you to iterate through a group of items, along with their indexes, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish']&lt;br /&gt;
&lt;br /&gt;
for index, pet in enumerate(pets):&lt;br /&gt;
    print(f&amp;quot;{pet} at index {index}&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Generator Expressions and Comprehensions ===&lt;br /&gt;
&lt;br /&gt;
A generator is a special kind of object that, basically, represents a collection of items using a value and a function for generating the next value in the collection. In other words, it's a way of creating something that behaves like a list, but which only generates one value at a time, and discards a value when it's done with it. Say, for example, you wanted to do an operation on 10,000,000,000,000 numbers. You could put them all in a list, then iterate over the list, but that would take a lot of memory, plus you'd have to create and fill the entire list before beginning to actually work on your problem. Instead, you'd probably be better off using a generator; telling the computer, essentially: “The starting value is 0. When I ask for the next number in the collection, add 1 to current value and give me that.”&lt;br /&gt;
&lt;br /&gt;
A generator expression is an expression that is evaluated to create a generator. They're super useful. Generator expressions can take two forms – they can be used with and without a condition:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
(EXPRESSION for VARIABLE in ITERABLE) # Unconditional&lt;br /&gt;
(EXPRESSION for VARIABLE in ITERABLE if CONDITION) # Conditional&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
For our purposes, you can think of an iterable as anything you can do a for loop over. Let's take a look at a generator expression in use:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
double_even_digits = (number * 2 for number in range(10) if number % 2 == 0)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
That line says that &amp;lt;code&amp;gt;double_even_digits&amp;lt;/code&amp;gt; is every even number between 0 and 10 multiplied by two. Simple enough, right? If we wanted to use all of the numbers, not just the even ones, we could simply remove the if statement at the end of the expression.&lt;br /&gt;
&lt;br /&gt;
Here's the thing, though: if you were to print &amp;lt;code&amp;gt;double_even_digits&amp;lt;/code&amp;gt;, instead of a nice bunch of numbers, you'd get something that looks like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&amp;lt;generator object &amp;lt;genexpr&amp;gt;&amp;lt;code&amp;gt;at 0x107fc92b0&amp;gt;&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
That's because generators are lazy! They don't generate their values until those values are needed, and they discard values once they're no longer needed. As a result, '''you can only iterate over a generator once'''. In this case, you can't print out the whole generator, because it hasn't generated all the values yet. You can, however, iterate over the generator, and print its values one at a time, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
for number in double_even_digits:&lt;br /&gt;
    print(number)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
You can also make a list out of the generator, which will go through all the items in the generator and put them in a list, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
even_number_list = list(double_even_digits)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
That's actually a great segue to the second topic of this section: comprehensions. A comprehension is just a prettier way to make lists, sets, and dicts out of a generator expressions.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
# If you want a list:&lt;br /&gt;
list(i for i in range(10) if i % 2 == 0) # Don't do this&lt;br /&gt;
[i for i in range(10) if i % 2 == 0] # Use a list comprehension instead!&lt;br /&gt;
&lt;br /&gt;
# If you want a set:&lt;br /&gt;
set(i for i in range(10) if i % 2 == 0) # Don't do this&lt;br /&gt;
{i for i in range(10) if i % 2 == 0} # Use a set comprehension instead!&lt;br /&gt;
&lt;br /&gt;
# If you want a dict:&lt;br /&gt;
dict((i, i + 1) for i in range(10) if i % 2 == 0) # Don't do this&lt;br /&gt;
{i : i + 1 for i in range(10) if i % 2 == 0} # Use a dict comprehension instead!&lt;br /&gt;
&lt;br /&gt;
# If you want a tuple:&lt;br /&gt;
tuple(i for i in range(10) if i % 2 == 0) # Unfortunately, there's no better way to do this&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
In general, generators and comprehensions should be used whenever possible - they're the fastest and easiest way to build collections. If you ever see yourself writing code like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
# BAD PRACTICE! DO NOT USE!&lt;br /&gt;
digits = []&lt;br /&gt;
for digit in range(10):&lt;br /&gt;
    digits.append(digit)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Don't do it! Instead, use a generator expression or comprehension, as appropriate. A good way to decide whether a generator expression or comprehension is better for this situation is that, if you're just going to be iterating over your collection once, you should use an generator expression. If not, use a comprehension.&lt;br /&gt;
&lt;br /&gt;
=== Sorting ===&lt;br /&gt;
&lt;br /&gt;
Sorting in Python is frequently performed using the &amp;lt;code&amp;gt;sorted&amp;lt;/code&amp;gt; function, which takes two arguments: an iterable (anything you can do a for-loop over, including lists and tuples) and a function used to evaluate each item. If the function is omitted, Python will try to sort the lists by value.&lt;br /&gt;
&lt;br /&gt;
The following example demonstrates using an inline function, which Python calls a ''lambda''.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = ['apple', 'banana', 'cherry', 'date']&lt;br /&gt;
&lt;br /&gt;
# sort the fruits by string length&lt;br /&gt;
new_fruits = sorted(fruits, key=lambda v: len(v) // 2)&lt;br /&gt;
&lt;br /&gt;
print(new_fruits) # ['date', 'apple', 'banana', 'cherry']&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Alternatively, you can sort a &amp;lt;code&amp;gt;list&amp;lt;/code&amp;gt; using the &amp;lt;code&amp;gt;.sort&amp;lt;/code&amp;gt; method. This is faster than calling &amp;lt;code&amp;gt;sorted&amp;lt;/code&amp;gt;, but it modifies the list in-place and returns &amp;lt;code&amp;gt;None&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = ['apple', 'banana', 'cherry', 'date']&lt;br /&gt;
fruits.sort()&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
=== Import ===&lt;br /&gt;
&lt;br /&gt;
If you want to use functions from other libraries (including ones that you install using pip), use &amp;lt;code&amp;gt;import&amp;lt;/code&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
import time&lt;br /&gt;
&lt;br /&gt;
current_time = time.localtime()&lt;br /&gt;
print(time.strftime('%a, %d %b %Y %H:%M:%S', current_time))&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If you want to pull the functions out of their namespace, you can use &amp;lt;code&amp;gt;from ___ import ___&amp;lt;/code&amp;gt; syntax:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
from time import localtime, strftime&lt;br /&gt;
&lt;br /&gt;
current_time = localtime()&lt;br /&gt;
print(strftime('%a, %d %b %Y %H:%M:%S', current_time))&lt;br /&gt;
&lt;br /&gt;
# Be aware that this technique, although convenient, may cause unexpected behavior if the function names that you're pulling out of the namespace are already used for other purposes in Python.&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
=== File I/O ===&lt;br /&gt;
&lt;br /&gt;
You can read an entire file into a variable like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
f = open(&amp;quot;example.txt&amp;quot;)&lt;br /&gt;
file_contents = f.read()&lt;br /&gt;
&lt;br /&gt;
f.close() # free up memory when we're finished with the file&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
A better option is to use a with-block, which handles opening and closing the file for you automatically:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
with open(&amp;quot;example.txt&amp;quot;) as f:&lt;br /&gt;
    file_contents = f.read()&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
You can read a file line-by-line like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
with open(&amp;quot;example.txt&amp;quot;) as f:&lt;br /&gt;
    for line in f:&lt;br /&gt;
        print(f&amp;quot;Read line: {line.strip()}&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
You can write to a file like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
with open(&amp;quot;example.txt&amp;quot;, &amp;quot;w&amp;quot;) as f:&lt;br /&gt;
    f.write(&amp;quot;Hello\nWorld\n&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Command-Line Arguments ===&lt;br /&gt;
&lt;br /&gt;
Command line arguments are accessible in the variable &amp;lt;code&amp;gt;sys.argv&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
The following example shows a program that expects a filename as its argument, and it prints a usage message if the argument is not present ([https://stackoverflow.com/questions/983201/python-and-sys-argv source]).&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
import sys, os&lt;br /&gt;
&lt;br /&gt;
if len(sys.argv) &amp;lt; 2:&lt;br /&gt;
    sys.exit(f&amp;quot;Usage: {sys.argv[0]} filename&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
filename = sys.argv[1]&lt;br /&gt;
&lt;br /&gt;
if not os.path.exists(filename):&lt;br /&gt;
    sys.exit(f&amp;quot;Error: File '{sys.argv[1]}' not found&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Object-Oriented Programming ===&lt;br /&gt;
&lt;br /&gt;
You can define and use a class like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
class Food:&lt;br /&gt;
    # constructor:&lt;br /&gt;
    def __init__(self, name):&lt;br /&gt;
        self.name = name&lt;br /&gt;
   &lt;br /&gt;
    def format_name(self):&lt;br /&gt;
        return f&amp;quot;Gotta love to eat {self.name}&amp;quot;&lt;br /&gt;
&lt;br /&gt;
class Fruit(Food):&lt;br /&gt;
    def get_definition(self):&lt;br /&gt;
        return f&amp;quot;{self.format_name()} (fruit)&amp;quot;&lt;br /&gt;
&lt;br /&gt;
fruit = Fruit(&amp;quot;Cherry&amp;quot;)&lt;br /&gt;
print(fruit.format_name())&lt;br /&gt;
print(fruit.get_definition())&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
This is the same example as in [[PHP#Object-Oriented_Programming|the PHP guide]].&lt;br /&gt;
&lt;br /&gt;
Some things to notice:&lt;br /&gt;
&lt;br /&gt;
* Instance methods ''always'' take &amp;lt;code&amp;gt;self&amp;lt;/code&amp;gt; as their first argument, followed by any number of additional parameters. This can be misleading for programmers familiar with other languages, because the number of arguments you feed to the method is actually ''one less than'' the number of declared parameters. Whenever you call a method on a class instance, that instance is implicitly fed into the explicitly-declared &amp;lt;code&amp;gt;self&amp;lt;/code&amp;gt; parameter of the method.&lt;br /&gt;
*: Note that the &amp;lt;code&amp;gt;self&amp;lt;/code&amp;gt; variable has the same purpose as the &amp;lt;code&amp;gt;this&amp;lt;/code&amp;gt; variable in languages like PHP, Java, JavaScript, and C++.&lt;br /&gt;
*There is no need for a &amp;lt;code&amp;gt;new&amp;lt;/code&amp;gt; keyword in Python.&lt;br /&gt;
&lt;br /&gt;
= Footnotes =&lt;br /&gt;
# {{note|interpreted}}This is an oversimplification. If you're interested, here's a quick explanation of how: In CPython (the reference implementation of Python) programs are compiled to bytecode, an intermediate representation, which is then interpreted.&lt;br /&gt;
[[Category:Module 4]]&lt;/div&gt;</summary>
		<author><name>Alex</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Python&amp;diff=2526</id>
		<title>Python</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Python&amp;diff=2526"/>
		<updated>2018-02-19T18:23:51Z</updated>

		<summary type="html">&lt;p&gt;Alex: /* Object-Oriented Programming */  Fixed compilation error in example&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Languages like Java and C++ have lots of rules regarding variable types, syntax, return values, and so on. These can be cumbersome when you are trying to write short, quick scripts to perform tasks. This is where a ''scripting language'' comes into play.&lt;br /&gt;
&lt;br /&gt;
'''Python''' is a language well-suited to rapid prototype development. It is generally an ''interpreted language'', which means that, generally speaking, a Python program is converted line by line into instructions for the computer to execute as the program runs, instead of having a separate compilation step beforehand {{ref|interpreted}}. The syntax is clean, and it is usually clear at first glance what is going on when you write in Python.&lt;br /&gt;
&lt;br /&gt;
= Installation =&lt;br /&gt;
&lt;br /&gt;
Python may already be installed on your system. To see whether or not it is, enter the command&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ python3 --version&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If it tells you a version of Python '''greater than or equal to 3.6''' then you're good to go. If not, you need to do a quick package install to get it up and running. Using yum, it's just &amp;lt;code&amp;gt;sudo yum install python36&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
If you'd like to be able to just type &amp;lt;code&amp;gt;python&amp;lt;/code&amp;gt; instead of &amp;lt;code&amp;gt;python3&amp;lt;/code&amp;gt;, you can add the following line to the &amp;lt;code&amp;gt;~/.bashrc&amp;lt;/code&amp;gt; file on your instance:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
alias python=&amp;quot;/usr/bin/python3&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Python 2 vs Python 3 ====&lt;br /&gt;
&lt;br /&gt;
In 2008, a new version of Python – Python 3 – was released, with a number of changes that made it incompatible with the previous version, Python 2. For several years, the Python community was slow to make the change to Python 3, but today, Python 3 is ''the'' standard for new code. The ''only'' reason to write Python 2 code today is because you have to work in an environment or with libraries that do not support Python 3, and that situation is becoming increasingly rare.&lt;br /&gt;
&lt;br /&gt;
'''For CSE 330 (and this guide), you ''must'' use Python 3.6 or greater.'''&lt;br /&gt;
&lt;br /&gt;
=== Pip ===&lt;br /&gt;
&lt;br /&gt;
Linux distributions have package managers like ''Apt'', ''Yum'', and ''YaST''. PHP has a package manager named ''PEAR''. It's now time to introduce Python's leading package manager: '''pip'''.&lt;br /&gt;
&lt;br /&gt;
Once you have pip installed, you can use it to install Python packages. Use the &amp;lt;code&amp;gt;pip-3.6&amp;lt;/code&amp;gt; command:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ pip-3.6 install package_name # RHEL&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
If you'd like to be able to just type &amp;lt;code&amp;gt;pip&amp;lt;/code&amp;gt; instead of &amp;lt;code&amp;gt;pip-3.6&amp;lt;/code&amp;gt;, you can add the following line to the &amp;lt;code&amp;gt;~/.bashrc&amp;lt;/code&amp;gt; file on your instance:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
alias pip=&amp;quot;/usr/bin/pip-3.6&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Running Python =&lt;br /&gt;
&lt;br /&gt;
There are two common ways to run Python code: via the console, and via a Python script file.&lt;br /&gt;
&lt;br /&gt;
=== The Python Console ===&lt;br /&gt;
&lt;br /&gt;
The Python console enables you to experiment with code without opening a text editor. To enter the Python console, simply type the ''python'' command at the terminal:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ python3&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
To leave the interactive console, either type &amp;lt;code&amp;gt;quit()&amp;lt;/code&amp;gt; or press &amp;lt;code&amp;gt;Ctrl-D&amp;lt;/code&amp;gt; (on both Mac and Windows).&lt;br /&gt;
&lt;br /&gt;
=== Python Script Files ===&lt;br /&gt;
&lt;br /&gt;
You can also save Python script files for later use. The extension for Python scripts is &amp;lt;code&amp;gt;*.py&amp;lt;/code&amp;gt;. To run a script file, simply feed its path as an argument to the &amp;lt;code&amp;gt;python&amp;lt;/code&amp;gt; command in Terminal:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ python3 my_script.py&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Python Syntax and Language Components =&lt;br /&gt;
&lt;br /&gt;
This section contains a very brief overview of Python syntax. For a more comprehensive introduction, see [http://docs.python.org/tutorial/ the Python docs].&lt;br /&gt;
&lt;br /&gt;
=== Python's Type System ===&lt;br /&gt;
&lt;br /&gt;
Python is a dynamically-typed, strongly-typed, and duck-typed language. What does that mean? Well, let's take those categories one by one:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;ol&amp;gt;&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
'''Dynamic typing''', in contrast to ''static typing'' means that the types of objects can be changed. In Java, for instance, if you tried to write the following code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
int c = 2;&lt;br /&gt;
c = &amp;quot;fish&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Your code would fail to compile, because the Java compiler wouldn't allow you to change the type of the variable &amp;lt;code&amp;gt;c&amp;lt;/code&amp;gt; from &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt; to &amp;lt;code&amp;gt;String&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Python, however, is just fine with that. You can write:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
c = 2&lt;br /&gt;
c = &amp;quot;fish&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
And Python will happily do what you ask.&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
'''Strong typing''', in contrast to ''weak typing'', means, roughly, that a language won't implicitly convert types for you. So far, you've used a lot of PHP, which is very weakly typed. For example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;php&amp;quot;&amp;gt;&lt;br /&gt;
echo &amp;quot;10&amp;quot; . 2;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In PHP, this works just fine. The PHP interpreter sees that &amp;lt;code&amp;gt;2&amp;lt;/code&amp;gt; is an int, and silently converts it to a string for you, so that &amp;lt;code&amp;gt;&amp;quot;10&amp;quot;. 2&amp;lt;/code&amp;gt; equals &amp;lt;code&amp;gt;&amp;quot;102&amp;quot;&amp;lt;/code&amp;gt;. The problem with weak typing is that it can make it unclear to the programmer why things are happening the way they are. For instance, in PHP, the expression &amp;lt;code&amp;gt;&amp;quot;10&amp;quot; == 10&amp;lt;/code&amp;gt; is true, which can be less than obvious. Python, however, tries to disallow that sort of thing:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
&amp;quot;10&amp;quot; + &amp;quot;10&amp;quot; # Allowed – concatenates the two strings.&lt;br /&gt;
10   +  10  # Allowed – adds the two ints.&lt;br /&gt;
&amp;quot;10&amp;quot; +  10  # Not allowed – raises a TypeError&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Perhaps the one exception to this rule is the relationship between numeric types; it's perfectly fine to add a float to an int, for example.&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
'''Duck-typing''' is a little bit different than the other categories, because it doesn't really have a direct opposite. Essentially, duck-typing is the philosophy that &amp;quot;If it walks like a duck, and quacks like a duck, it's a duck.&amp;quot; In programming terms, that means that we often don't care what type an object is, as long as it can do the things we ask.&lt;br /&gt;
&lt;br /&gt;
Let's look at an example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
# This function doubles the value it's passed.&lt;br /&gt;
def double(thing):&lt;br /&gt;
    return thing + thing&lt;br /&gt;
double(10) # Returns 20&lt;br /&gt;
double(&amp;quot;fish&amp;quot;) # Returns &amp;quot;fishfish&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If this were Java, we'd have to write two different methods here: one for things of type &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt;, and one for things of type &amp;lt;code&amp;gt;String&amp;lt;/code&amp;gt;. Since this is Python, though, we don't have to do that. Instead, Python lets us say, essentially: &amp;quot;This function uses the &amp;lt;code&amp;gt;+&amp;lt;/code&amp;gt; operator, so you can pass whatever object you want to the function, as long as the function supports the &amp;lt;code&amp;gt;+&amp;lt;/code&amp;gt; operator&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
To quote [https://groups.google.com/forum/?hl=en#!msg/comp.lang.python/CCs2oJdyuzc/NYjla5HKMOIJ Alex Martelli], one of the key people in the Python project,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;blockquote&amp;gt;&lt;br /&gt;
&amp;quot;[Don't] check whether it IS-a duck: check whether it QUACKS-like-a duck, WALKS-like-a duck, etc, etc, depending on exactly what subset of duck-like behaviour you need.&amp;quot;&lt;br /&gt;
&amp;lt;/blockquote&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&amp;lt;/ol&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Basic Types ===&lt;br /&gt;
&lt;br /&gt;
In Python, the basic scalar types are:&lt;br /&gt;
&lt;br /&gt;
# &amp;lt;code&amp;gt;str&amp;lt;/code&amp;gt; – a string.&lt;br /&gt;
# &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt; – an integer object with unlimited digits.&lt;br /&gt;
# &amp;lt;code&amp;gt;bool&amp;lt;/code&amp;gt; – a Boolean value.&lt;br /&gt;
# &amp;lt;code&amp;gt;float&amp;lt;/code&amp;gt; – a floating point number; generally equivalent to &amp;lt;code&amp;gt;double&amp;lt;/code&amp;gt; in Java.&lt;br /&gt;
# &amp;lt;code&amp;gt;bytes&amp;lt;/code&amp;gt; – represents a collection of bytes; you're unlikely to use this often.&lt;br /&gt;
&lt;br /&gt;
Casting is done in the C style - to parse an &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt; from a string, for instance, you'd write &amp;lt;code&amp;gt;int(&amp;quot;123&amp;quot;)&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== Basic Control Flow ===&lt;br /&gt;
In Python, blocks of code are delineated using colons and indentation instead of curly braces. '''''That means that proper indentation is mandatory.''''' Every time you use a colon, you must indent one step further, and every time a block ends, you must unindent a step.&lt;br /&gt;
&lt;br /&gt;
Conditional statements are done using the &amp;lt;code&amp;gt;if&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;elif&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;else&amp;lt;/code&amp;gt; operators, like in the example below - pay attention to the indentation:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
cookies_left = 10&lt;br /&gt;
cake_slices_left = 3&lt;br /&gt;
if cookies_left &amp;gt; 10:&lt;br /&gt;
    print(&amp;quot;Lots of cookies!&amp;quot;)&lt;br /&gt;
elif cookies_left &amp;gt; 8:&lt;br /&gt;
    print(&amp;quot;Plenty left!&amp;quot;)&lt;br /&gt;
elif cookies_left == 5:&lt;br /&gt;
    print(&amp;quot;Halfway done!&amp;quot;)&lt;br /&gt;
else:&lt;br /&gt;
    if cake_slices_left == 3:&lt;br /&gt;
        print(&amp;quot;Lots of cake!&amp;quot;)&lt;br /&gt;
    elif cake_slices_left == 2:&lt;br /&gt;
        print(&amp;quot;One slice gone!&amp;quot;)&lt;br /&gt;
    else:&lt;br /&gt;
        print(&amp;quot;Little to no cake left!&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== An Example Python Script ===&lt;br /&gt;
&lt;br /&gt;
In my mind, there's no better way to learn Python than to be immersed in a simple example script.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
print(&amp;quot;Hello World&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
fruits = [&amp;quot;apple&amp;quot;, &amp;quot;banana&amp;quot;, &amp;quot;cherry&amp;quot;, &amp;quot;date&amp;quot;]&lt;br /&gt;
for fruit in fruits:&lt;br /&gt;
    print(f&amp;quot;I always love to eat a fresh {fruit}&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Map the fruits list over to a new list containing the length of the fruit strings:&lt;br /&gt;
fruit_size = [len(fruit) for fruit in fruits]&lt;br /&gt;
&lt;br /&gt;
avg_fruit_size = sum(fruit_size) / len(fruit_size)&lt;br /&gt;
print(f&amp;quot;The average fruit string length is {avg_fruit_size:.2f}.&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Some things to notice:&lt;br /&gt;
&lt;br /&gt;
* Printing is achieved using the &amp;lt;code&amp;gt;print()&amp;lt;/code&amp;gt; function.&lt;br /&gt;
* Comments start with a pound symbol &amp;lt;code&amp;gt;#&amp;lt;/code&amp;gt;.&lt;br /&gt;
* We can transform/map a list to a new list in just one line!&lt;br /&gt;
&lt;br /&gt;
For some more examples, see [https://wiki.python.org/moin/SimplePrograms the Python wiki].&lt;br /&gt;
&lt;br /&gt;
=== A Few Gotchas ===&lt;br /&gt;
&lt;br /&gt;
Here are a few things you may not expect when starting out with Python:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;ol&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
Strings can be delimited using either single quotes (&amp;lt;code&amp;gt;'&amp;lt;/code&amp;gt;) or double quotes (&amp;lt;code&amp;gt;&amp;quot;&amp;lt;/code&amp;gt;), so &amp;lt;code&amp;gt;'Python'&amp;lt;/code&amp;gt; is the same as &amp;lt;code&amp;gt;&amp;quot;Python&amp;quot;&amp;lt;/code. You can also use three sets of quotes (&amp;lt;code&amp;gt;'''&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;&amp;quot;&amp;quot;&amp;quot;&amp;lt;/code&amp;gt;) to delineate a multiple-line string, like so:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
long_string = &amp;quot;&amp;quot;&amp;quot;This&lt;br /&gt;
is my&lt;br /&gt;
very long&lt;br /&gt;
multiple-line&lt;br /&gt;
string&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
To compare the equality of two objects, use the &amp;lt;code&amp;gt;==&amp;lt;/code&amp;gt; operator. To compare the identity of two objects (i.e. whether or not they are literally the same object, at the same place in memory), use the &amp;lt;code&amp;gt;is&amp;lt;/code&amp;gt; operator. These correspond, respectively to &amp;lt;code&amp;gt;.equals()&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;==&amp;lt;/code&amp;gt; in Java.&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
The &amp;lt;code&amp;gt;/&amp;lt;/code&amp;gt; operator performs floating-point division, not integer division, even when both its arguments are integers. If you want to do integer division, use the &amp;lt;code&amp;gt;//&amp;lt;/code&amp;gt; operator. Let's look at an example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
9   / 10    == 0.9 # Floating-point division&lt;br /&gt;
9.0 / 10.0  == 0.9 # Floating-point division&lt;br /&gt;
9   // 10   == 0   # Integer division&lt;br /&gt;
9.0 // 10.0 == 0.0 # Integer division, even though the resulting value is a float&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
As discussed in the section [[#Python's_Type_System|Python's Type System]], you can't combine strings and numbers using the &amp;lt;code&amp;gt;+&amp;lt;/code&amp;gt; operator. Instead, you'll have to use one of the following methods of string formatting:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
  &lt;br /&gt;
# Technique 1 – printf-style Formatting&lt;br /&gt;
# This is a classic style of string formatting, used in many programming languages, including in Java's String.format.&lt;br /&gt;
&amp;quot;You scored %d out of %d!&amp;quot; % (score, questions)&lt;br /&gt;
&lt;br /&gt;
# Technique 2 – str.format&lt;br /&gt;
&amp;quot;You scored {} out of {}!&amp;quot;.format(score, questions)&lt;br /&gt;
&lt;br /&gt;
# Technique 3 – f-strings&lt;br /&gt;
# These were only introduced in Python 3.6 but they're very convenient.&lt;br /&gt;
f&amp;quot;You scored {score} out of {questions}!&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# Technique 4 - String Concatenation&lt;br /&gt;
# This is fine for small things, but for more complicated stuff, use one of the other techniques.&lt;br /&gt;
&amp;quot;You scored &amp;quot; + str(score) + &amp;quot; out of &amp;quot; + str(questions) + &amp;quot;!&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&amp;lt;/ol&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Functions ===&lt;br /&gt;
&lt;br /&gt;
Define functions using the &amp;lt;code&amp;gt;def&amp;lt;/code&amp;gt; keyword:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def hello(name):&lt;br /&gt;
    print(f&amp;quot;Hello, {name}!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Invoke functions using parentheses:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
hello(&amp;quot;Batman&amp;quot;)&lt;br /&gt;
hello(&amp;quot;Superman&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Functions can have optional arguments; however, these must come after any required arguments:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def hello(name=&amp;quot;User&amp;quot;):&lt;br /&gt;
    print(f&amp;quot;Hello, {name}!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
hello() # Prints &amp;quot;Hello, User!&amp;quot;&lt;br /&gt;
hello(&amp;quot;Sarah&amp;quot;) # Prints &amp;quot;Hello, Sarah!&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Functions are just regular objects in Python, meaning you can do stuff like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def hello(name=&amp;quot;User&amp;quot;):&lt;br /&gt;
    print(f&amp;quot;Hello, {name}!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
greeting = hello&lt;br /&gt;
&lt;br /&gt;
greeting(&amp;quot;Siwei&amp;quot;) # Prints &amp;quot;Hello, Siwei!&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Collection Types ===&lt;br /&gt;
Python has a few basic, built-in collection types. They each have their own special use cases, but they share a lot of similarities. All built-in data structures in Python are zero-indexed, for instance.&lt;br /&gt;
&lt;br /&gt;
To obtain the number of elements in a collection, use the &amp;lt;code&amp;gt;len()&amp;lt;/code&amp;gt; function, like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish'] # This is a list; you'll learn about them below.&lt;br /&gt;
&lt;br /&gt;
len(pets) # Returns 3&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To check if a collection contains an item, use the &amp;lt;code&amp;gt;in&amp;lt;/code&amp;gt; operator:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish'] # This is a list; you'll learn about them below.&lt;br /&gt;
&lt;br /&gt;
'Dog' in pets # Returns True&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Helpfully, the Python Software Foundation maintains a page containing the asymptotic complexities of important operations on major Python data structures. It's available [https://wiki.python.org/moin/TimeComplexity here].&lt;br /&gt;
&lt;br /&gt;
==== Lists ====&lt;br /&gt;
&lt;br /&gt;
Unlike languages like Java and C, Python's array-like type doesn't have fixed length. Instead, a &amp;lt;code&amp;gt;list&amp;lt;/code&amp;gt; is a dynamic array (like Java's &amp;lt;code&amp;gt;ArrayList&amp;lt;/code&amp;gt;) of objects of any type. Here's an example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = [&amp;quot;Apple&amp;quot;, &amp;quot;Pear&amp;quot;, &amp;quot;Orange&amp;quot;] # Lists can be creating by placing their items between square brackets&lt;br /&gt;
&lt;br /&gt;
random_items = ['Apple', 12312, 2.0, [1, 2, 3]] # Lists can contain objects of different types - even other lists!&lt;br /&gt;
&lt;br /&gt;
pets.append('Turtle') # Adds 'Turtle' to the end of pets&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For the next few examples, we'll be using the following list:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish', 'Turtle', 'Lizard', 'Snake']&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access or assign elements of a list, use the &amp;lt;code&amp;gt;[]&amp;lt;/code&amp;gt; operator.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[0] # Returns 'Dog'&lt;br /&gt;
pets[1] = 'Cow' # Sets pets[1] to 'Cow'&lt;br /&gt;
pets[1] = 'Cat' # Sets pets[1] back to 'Cat' &lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You can also access or assign lists using negative indices, which will return elements starting from the end of the list:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[-1] # Returns 'Snake'&lt;br /&gt;
pets[-2] # Returns 'Lizard'&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You can also use 'slice notation' to obtain or assign subsets of lists:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[start:end] # Returns items from index start to index end - 1.&lt;br /&gt;
pets[start:]    # Returns items from index start to the end of the list, inclusive.&lt;br /&gt;
pets[:end]      # Returns items from the beginning of the list to index end - 1.&lt;br /&gt;
pets[:]         # Returns every item in the list&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
There's also a third, optional argument: &amp;lt;code&amp;gt;step&amp;lt;/code&amp;gt;, which lets you jump over values:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[start:end:step] # Returns items from index start to index end - 1, jumping step values at a time&lt;br /&gt;
&lt;br /&gt;
# Examples:&lt;br /&gt;
pets[1:5:2] # Returns items from index 1 to index 4, jumping 2 at a time, so ['Cat', 'Turtle']&lt;br /&gt;
pets[::3] # Returns all items in the list, jumping 3 at a time, so ['Dog', 'Turtle']&lt;br /&gt;
pets[::-1] # Returns all items in the list, jumping -1 at a time. This reverses the list, so ['Snake', 'Lizard', 'Turtle', 'Fish', 'Cat', 'Dog']&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Lists have all the performance characteristics you'd expect of a dynamic array - constant-time indexing, amortized constant-time appends, and so on.&lt;br /&gt;
&lt;br /&gt;
==== Tuples ====&lt;br /&gt;
&lt;br /&gt;
Python has a special data type called &amp;lt;code&amp;gt;tuple&amp;lt;/code&amp;gt;, which is exactly the same as a list except for the fact that it cannot be modified, so you can't append or replace items.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
cities = ('St. Louis', 'Los Angeles', 'Seattle') # Tuples are defined using parentheses.&lt;br /&gt;
numbers = 1, 2, 3 # You can also omit the parentheses if it's unambiguous&lt;br /&gt;
single_item_tuple = (1,) # To make a tuple with only one item, put a comma after it&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Tuples also enable you to have multiple return values from a function:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def compute_length(string):&lt;br /&gt;
    str_len = len(string)&lt;br /&gt;
    if str_len &amp;lt; 5:&lt;br /&gt;
        return str_len, &amp;quot;short&amp;quot;&lt;br /&gt;
    elif str_len &amp;lt; 40:&lt;br /&gt;
        return str_len, &amp;quot;medium&amp;quot;&lt;br /&gt;
    return str_len, &amp;quot;long&amp;quot;&lt;br /&gt;
&lt;br /&gt;
length, description = compute_length(&amp;quot;Four score and seven years ago&amp;quot;)&lt;br /&gt;
print(f&amp;quot;The {description} string is {length} characters long.&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
The above example also demonstrates Python's if...elif...else conditional structure.&lt;br /&gt;
&lt;br /&gt;
==== Dictionaries ====&lt;br /&gt;
&lt;br /&gt;
Python has another datatype called a '''dictionary''' (or &amp;lt;code&amp;gt;dict&amp;lt;/code&amp;gt;, for short), which are like ''Maps'' in Java, ''associative arrays'' in PHP, and ''object literals'' in JavaScript (coming up soon in Module 6). Essentially, they enable you to use any immutable object as the key in your data structure. &amp;lt;code&amp;gt;dict&amp;lt;/code&amp;gt; objects can be created using either the &amp;lt;code&amp;gt;dict&amp;lt;/code&amp;gt; function, or by placing items between curly braces, separating keys and values using colons:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits_in_bowl = {&lt;br /&gt;
    'apple': 4,&lt;br /&gt;
    'banana': 2,&lt;br /&gt;
    'cherry': 0,&lt;br /&gt;
    'date': 12&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
apple_count = fruits_in_bowl['apple'] # Equals 4&lt;br /&gt;
&lt;br /&gt;
fruits_in_bowl['pear'] = 9 # Sets 'pear' in the dictionary to 9.&lt;br /&gt;
&lt;br /&gt;
for fruit, num in fruits_in_bowl.items():&lt;br /&gt;
    print(f&amp;quot;There are {num} {fruit}(s) in the bowl.&amp;quot; % (num, fruit))&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If you only want the keys from a dictionary, you can just iterate over it directly, like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
for fruit in fruits_in_bowl:&lt;br /&gt;
    print(fruit)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If you want only the values but not the keys from a dictionary, use &amp;lt;code&amp;gt;my_dictionary.values()&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
==== Sets ==== &lt;br /&gt;
A &amp;lt;code&amp;gt;set&amp;lt;/code&amp;gt; is an unordered collection of unique items, with constant-time membership checking. &lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = {'Apple', 'Apple', 'Apple', 'Pear'} # The set removes duplicates, so it will only contain {'Apple', 'Pear'}&lt;br /&gt;
fruits = set(['Apple', 'Apple', 'Apple', 'Pear']) # This line transforms a list into a set&lt;br /&gt;
print('Apple' in fruits) # Constant-time!&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Loops ===&lt;br /&gt;
&lt;br /&gt;
In Python, while loops are written like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
i = 0&lt;br /&gt;
while i &amp;lt; 10:&lt;br /&gt;
    i += 1&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
For loops are written like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish']&lt;br /&gt;
&lt;br /&gt;
for pet in pets:&lt;br /&gt;
    print(pet)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
To iterate over a range of numbers, you can use the convenient &amp;lt;code&amp;gt;range&amp;lt;/code&amp;gt; function, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
for i in range(20, 30): # If you omit the first argument to range, it's assumed to be zero.&lt;br /&gt;
    print(i)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Note that &amp;lt;code&amp;gt;range&amp;lt;/code&amp;gt; provides a closed-open range. That is to say, it is inclusive of its lower bound and exclusive of its upper bound. To be very explicit about it:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
list(range(3, 6)) == [3, 4, 5]&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Unlike in other languages you may know, the following is not good practice in Python:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish']&lt;br /&gt;
&lt;br /&gt;
# BAD PRACTICE. DO NOT USE.&lt;br /&gt;
for i in range(len(pets)):&lt;br /&gt;
    pet = pets[i]&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Instead, if you need to access both a variable and its index, use the &amp;lt;code&amp;gt;enumerate&amp;lt;/code&amp;gt; function, which allows you to iterate through a group of items, along with their indexes, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish']&lt;br /&gt;
&lt;br /&gt;
for index, pet in enumerate(pets):&lt;br /&gt;
    print(f&amp;quot;{pet} at index {index}&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Generator Expressions and Comprehensions ===&lt;br /&gt;
&lt;br /&gt;
A generator is a special kind of object that, basically, represents a collection of items using a value and a function for generating the next value in the collection. In other words, it's a way of creating something that behaves like a list, but which only generates one value at a time, and discards a value when it's done with it. Say, for example, you wanted to do an operation on 10,000,000,000,000 numbers. You could put them all in a list, then iterate over the list, but that would take a lot of memory, plus you'd have to create and fill the entire list before beginning to actually work on your problem. Instead, you'd probably be better off using a generator; telling the computer, essentially: “The starting value is 0. When I ask for the next number in the collection, add 1 to current value and give me that.”&lt;br /&gt;
&lt;br /&gt;
A generator expression is an expression that is evaluated to create a generator. They're super useful. Generator expressions can take two forms – they can be used with and without a condition:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
(EXPRESSION for VARIABLE in ITERABLE) # Unconditional&lt;br /&gt;
(EXPRESSION for VARIABLE in ITERABLE if CONDITION) # Conditional&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
For our purposes, you can think of an iterable as anything you can do a for loop over. Let's take a look at a generator expression in use:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
double_even_digits = (number * 2 for number in range(10) if number % 2 == 0)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
That line says that &amp;lt;code&amp;gt;double_even_digits&amp;lt;/code&amp;gt; is every even number between 0 and 10 multiplied by two. Simple enough, right? If we wanted to use all of the numbers, not just the even ones, we could simply remove the if statement at the end of the expression.&lt;br /&gt;
&lt;br /&gt;
Here's the thing, though: if you were to print &amp;lt;code&amp;gt;double_even_digits&amp;lt;/code&amp;gt;, instead of a nice bunch of numbers, you'd get something that looks like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&amp;lt;generator object &amp;lt;genexpr&amp;gt;&amp;lt;code&amp;gt;at 0x107fc92b0&amp;gt;&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
That's because generators are lazy! They don't generate their values until those values are needed, and they discard values once they're no longer needed. As a result, '''you can only iterate over a generator once'''. In this case, you can't print out the whole generator, because it hasn't generated all the values yet. You can, however, iterate over the generator, and print its values one at a time, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
for number in double_even_digits:&lt;br /&gt;
    print(number)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
You can also make a list out of the generator, which will go through all the items in the generator and put them in a list, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
even_number_list = list(double_even_digits)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
That's actually a great segue to the second topic of this section: comprehensions. A comprehension is just a prettier way to make lists, sets, and dicts out of a generator expressions.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
# If you want a list:&lt;br /&gt;
list(i for i in range(10) if i % 2 == 0) # Don't do this&lt;br /&gt;
[i for i in range(10) if i % 2 == 0] # Use a list comprehension instead!&lt;br /&gt;
&lt;br /&gt;
# If you want a set:&lt;br /&gt;
set(i for i in range(10) if i % 2 == 0) # Don't do this&lt;br /&gt;
{i for i in range(10) if i % 2 == 0} # Use a set comprehension instead!&lt;br /&gt;
&lt;br /&gt;
# If you want a dict:&lt;br /&gt;
dict((i, i + 1) for i in range(10) if i % 2 == 0) # Don't do this&lt;br /&gt;
{i : i + 1 for i in range(10) if i % 2 == 0} # Use a dict comprehension instead!&lt;br /&gt;
&lt;br /&gt;
# If you want a tuple:&lt;br /&gt;
tuple(i for i in range(10) if i % 2 == 0) # Unfortunately, there's no better way to do this&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
In general, generators and comprehensions should be used whenever possible - they're the fastest and easiest way to build collections. If you ever see yourself writing code like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
# BAD PRACTICE! DO NOT USE!&lt;br /&gt;
digits = []&lt;br /&gt;
for digit in range(10):&lt;br /&gt;
    digits.append(digit)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Don't do it! Instead, use a generator expression or comprehension, as appropriate. A good way to decide whether a generator expression or comprehension is better for this situation is that, if you're just going to be iterating over your collection once, you should use an generator expression. If not, use a comprehension.&lt;br /&gt;
&lt;br /&gt;
=== Sorting ===&lt;br /&gt;
&lt;br /&gt;
Sorting in Python is frequently performed using the &amp;lt;code&amp;gt;sorted&amp;lt;/code&amp;gt; function, which takes two arguments: an iterable (anything you can do a for-loop over, including lists and tuples) and a function used to evaluate each item. If the function is omitted, Python will try to sort the lists by value.&lt;br /&gt;
&lt;br /&gt;
The following example demonstrates using an inline function, which Python calls a ''lambda''.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = ['apple', 'banana', 'cherry', 'date']&lt;br /&gt;
&lt;br /&gt;
# sort the fruits by string length&lt;br /&gt;
new_fruits = sorted(fruits, key=lambda v: len(v) // 2)&lt;br /&gt;
&lt;br /&gt;
print(new_fruits) # ['date', 'apple', 'banana', 'cherry']&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Alternatively, you can sort a &amp;lt;code&amp;gt;list&amp;lt;/code&amp;gt; using the &amp;lt;code&amp;gt;.sort&amp;lt;/code&amp;gt; method. This is faster than calling &amp;lt;code&amp;gt;sorted&amp;lt;/code&amp;gt;, but it modifies the list in-place and returns &amp;lt;code&amp;gt;None&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = ['apple', 'banana', 'cherry', 'date']&lt;br /&gt;
fruits.sort()&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
=== Import ===&lt;br /&gt;
&lt;br /&gt;
If you want to use functions from other libraries (including ones that you install using pip), use &amp;lt;code&amp;gt;import&amp;lt;/code&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
import time&lt;br /&gt;
&lt;br /&gt;
current_time = time.localtime()&lt;br /&gt;
print(time.strftime('%a, %d %b %Y %H:%M:%S', current_time))&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If you want to pull the functions out of their namespace, you can use &amp;lt;code&amp;gt;from ___ import ___&amp;lt;/code&amp;gt; syntax:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
from time import localtime, strftime&lt;br /&gt;
&lt;br /&gt;
current_time = localtime()&lt;br /&gt;
print(strftime('%a, %d %b %Y %H:%M:%S', current_time))&lt;br /&gt;
&lt;br /&gt;
# Be aware that this technique, although convenient, may cause unexpected behavior if the function names that you're pulling out of the namespace are already used for other purposes in Python.&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
=== File I/O ===&lt;br /&gt;
&lt;br /&gt;
You can read an entire file into a variable like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
f = open(&amp;quot;example.txt&amp;quot;)&lt;br /&gt;
file_contents = f.read()&lt;br /&gt;
&lt;br /&gt;
f.close() # free up memory when we're finished with the file&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
A better option is to use a with-block, which handles opening and closing the file for you automatically:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
with open(&amp;quot;example.txt&amp;quot;) as f:&lt;br /&gt;
    file_contents = f.read()&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
You can read a file line-by-line like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
with open(&amp;quot;example.txt&amp;quot;) as f:&lt;br /&gt;
    for line in f:&lt;br /&gt;
        print(&amp;quot;Read line: %s&amp;quot; % line.rstrip())&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
You can write to a file like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
with open(&amp;quot;example.txt&amp;quot;, &amp;quot;w&amp;quot;) as f:&lt;br /&gt;
    f.write(&amp;quot;Hello\nWorld\n&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
=== Command-Line Arguments ===&lt;br /&gt;
&lt;br /&gt;
Command line arguments are accessible in the variable &amp;lt;code&amp;gt;sys.argv&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
The following example shows a program that expects a filename as its argument, and it prints a usage message if the argument is not present ([https://stackoverflow.com/questions/983201/python-and-sys-argv source]).&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
import sys, os&lt;br /&gt;
&lt;br /&gt;
if len(sys.argv) &amp;lt; 2:&lt;br /&gt;
    sys.exit(f&amp;quot;Usage: {sys.argv[0]} filename&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
filename = sys.argv[1]&lt;br /&gt;
&lt;br /&gt;
if not os.path.exists(filename):&lt;br /&gt;
    sys.exit(f&amp;quot;Error: File '{sys.argv[1]}' not found&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Object-Oriented Programming ===&lt;br /&gt;
&lt;br /&gt;
You can define and use a class like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
class Food:&lt;br /&gt;
    # constructor:&lt;br /&gt;
    def __init__(self, name):&lt;br /&gt;
        self.name = name&lt;br /&gt;
   &lt;br /&gt;
    def format_name(self):&lt;br /&gt;
        return f&amp;quot;Gotta love to eat {self.name}&amp;quot;&lt;br /&gt;
&lt;br /&gt;
class Fruit(Food):&lt;br /&gt;
    def get_definition(self):&lt;br /&gt;
        return f&amp;quot;{self.format_name()} (fruit)&amp;quot;&lt;br /&gt;
&lt;br /&gt;
fruit = Fruit(&amp;quot;Cherry&amp;quot;)&lt;br /&gt;
print(fruit.format_name())&lt;br /&gt;
print(fruit.get_definition())&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
This is the same example as in [[PHP#Object-Oriented_Programming|the PHP guide]].&lt;br /&gt;
&lt;br /&gt;
Some things to notice:&lt;br /&gt;
&lt;br /&gt;
* Instance methods ''always'' take &amp;lt;code&amp;gt;self&amp;lt;/code&amp;gt; as their first argument, followed by any number of additional parameters. This can be misleading for programmers familiar with other languages, because the number of arguments you feed to the method is actually ''one less than'' the number of declared parameters. Whenever you call a method on a class instance, that instance is implicitly fed into the explicitly-declared &amp;lt;code&amp;gt;self&amp;lt;/code&amp;gt; parameter of the method.&lt;br /&gt;
*: Note that the &amp;lt;code&amp;gt;self&amp;lt;/code&amp;gt; variable has the same purpose as the &amp;lt;code&amp;gt;this&amp;lt;/code&amp;gt; variable in languages like PHP, Java, JavaScript, and C++.&lt;br /&gt;
*There is no need for a &amp;lt;code&amp;gt;new&amp;lt;/code&amp;gt; keyword in Python.&lt;br /&gt;
&lt;br /&gt;
= Footnotes =&lt;br /&gt;
# {{note|interpreted}}This is an oversimplification. If you're interested, here's a quick explanation of how: In CPython (the reference implementation of Python) programs are compiled to bytecode, an intermediate representation, which is then interpreted.&lt;br /&gt;
[[Category:Module 4]]&lt;/div&gt;</summary>
		<author><name>Alex</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Python&amp;diff=2525</id>
		<title>Python</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Python&amp;diff=2525"/>
		<updated>2018-02-19T18:22:16Z</updated>

		<summary type="html">&lt;p&gt;Alex: /* Object-Oriented Programming */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Languages like Java and C++ have lots of rules regarding variable types, syntax, return values, and so on. These can be cumbersome when you are trying to write short, quick scripts to perform tasks. This is where a ''scripting language'' comes into play.&lt;br /&gt;
&lt;br /&gt;
'''Python''' is a language well-suited to rapid prototype development. It is generally an ''interpreted language'', which means that, generally speaking, a Python program is converted line by line into instructions for the computer to execute as the program runs, instead of having a separate compilation step beforehand {{ref|interpreted}}. The syntax is clean, and it is usually clear at first glance what is going on when you write in Python.&lt;br /&gt;
&lt;br /&gt;
= Installation =&lt;br /&gt;
&lt;br /&gt;
Python may already be installed on your system. To see whether or not it is, enter the command&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ python3 --version&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If it tells you a version of Python '''greater than or equal to 3.6''' then you're good to go. If not, you need to do a quick package install to get it up and running. Using yum, it's just &amp;lt;code&amp;gt;sudo yum install python36&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
If you'd like to be able to just type &amp;lt;code&amp;gt;python&amp;lt;/code&amp;gt; instead of &amp;lt;code&amp;gt;python3&amp;lt;/code&amp;gt;, you can add the following line to the &amp;lt;code&amp;gt;~/.bashrc&amp;lt;/code&amp;gt; file on your instance:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
alias python=&amp;quot;/usr/bin/python3&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Python 2 vs Python 3 ====&lt;br /&gt;
&lt;br /&gt;
In 2008, a new version of Python – Python 3 – was released, with a number of changes that made it incompatible with the previous version, Python 2. For several years, the Python community was slow to make the change to Python 3, but today, Python 3 is ''the'' standard for new code. The ''only'' reason to write Python 2 code today is because you have to work in an environment or with libraries that do not support Python 3, and that situation is becoming increasingly rare.&lt;br /&gt;
&lt;br /&gt;
'''For CSE 330 (and this guide), you ''must'' use Python 3.6 or greater.'''&lt;br /&gt;
&lt;br /&gt;
=== Pip ===&lt;br /&gt;
&lt;br /&gt;
Linux distributions have package managers like ''Apt'', ''Yum'', and ''YaST''. PHP has a package manager named ''PEAR''. It's now time to introduce Python's leading package manager: '''pip'''.&lt;br /&gt;
&lt;br /&gt;
Once you have pip installed, you can use it to install Python packages. Use the &amp;lt;code&amp;gt;pip-3.6&amp;lt;/code&amp;gt; command:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ pip-3.6 install package_name # RHEL&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
If you'd like to be able to just type &amp;lt;code&amp;gt;pip&amp;lt;/code&amp;gt; instead of &amp;lt;code&amp;gt;pip-3.6&amp;lt;/code&amp;gt;, you can add the following line to the &amp;lt;code&amp;gt;~/.bashrc&amp;lt;/code&amp;gt; file on your instance:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
alias pip=&amp;quot;/usr/bin/pip-3.6&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Running Python =&lt;br /&gt;
&lt;br /&gt;
There are two common ways to run Python code: via the console, and via a Python script file.&lt;br /&gt;
&lt;br /&gt;
=== The Python Console ===&lt;br /&gt;
&lt;br /&gt;
The Python console enables you to experiment with code without opening a text editor. To enter the Python console, simply type the ''python'' command at the terminal:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ python3&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
To leave the interactive console, either type &amp;lt;code&amp;gt;quit()&amp;lt;/code&amp;gt; or press &amp;lt;code&amp;gt;Ctrl-D&amp;lt;/code&amp;gt; (on both Mac and Windows).&lt;br /&gt;
&lt;br /&gt;
=== Python Script Files ===&lt;br /&gt;
&lt;br /&gt;
You can also save Python script files for later use. The extension for Python scripts is &amp;lt;code&amp;gt;*.py&amp;lt;/code&amp;gt;. To run a script file, simply feed its path as an argument to the &amp;lt;code&amp;gt;python&amp;lt;/code&amp;gt; command in Terminal:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ python3 my_script.py&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Python Syntax and Language Components =&lt;br /&gt;
&lt;br /&gt;
This section contains a very brief overview of Python syntax. For a more comprehensive introduction, see [http://docs.python.org/tutorial/ the Python docs].&lt;br /&gt;
&lt;br /&gt;
=== Python's Type System ===&lt;br /&gt;
&lt;br /&gt;
Python is a dynamically-typed, strongly-typed, and duck-typed language. What does that mean? Well, let's take those categories one by one:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;ol&amp;gt;&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
'''Dynamic typing''', in contrast to ''static typing'' means that the types of objects can be changed. In Java, for instance, if you tried to write the following code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
int c = 2;&lt;br /&gt;
c = &amp;quot;fish&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Your code would fail to compile, because the Java compiler wouldn't allow you to change the type of the variable &amp;lt;code&amp;gt;c&amp;lt;/code&amp;gt; from &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt; to &amp;lt;code&amp;gt;String&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Python, however, is just fine with that. You can write:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
c = 2&lt;br /&gt;
c = &amp;quot;fish&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
And Python will happily do what you ask.&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
'''Strong typing''', in contrast to ''weak typing'', means, roughly, that a language won't implicitly convert types for you. So far, you've used a lot of PHP, which is very weakly typed. For example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;php&amp;quot;&amp;gt;&lt;br /&gt;
echo &amp;quot;10&amp;quot; . 2;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In PHP, this works just fine. The PHP interpreter sees that &amp;lt;code&amp;gt;2&amp;lt;/code&amp;gt; is an int, and silently converts it to a string for you, so that &amp;lt;code&amp;gt;&amp;quot;10&amp;quot;. 2&amp;lt;/code&amp;gt; equals &amp;lt;code&amp;gt;&amp;quot;102&amp;quot;&amp;lt;/code&amp;gt;. The problem with weak typing is that it can make it unclear to the programmer why things are happening the way they are. For instance, in PHP, the expression &amp;lt;code&amp;gt;&amp;quot;10&amp;quot; == 10&amp;lt;/code&amp;gt; is true, which can be less than obvious. Python, however, tries to disallow that sort of thing:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
&amp;quot;10&amp;quot; + &amp;quot;10&amp;quot; # Allowed – concatenates the two strings.&lt;br /&gt;
10   +  10  # Allowed – adds the two ints.&lt;br /&gt;
&amp;quot;10&amp;quot; +  10  # Not allowed – raises a TypeError&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Perhaps the one exception to this rule is the relationship between numeric types; it's perfectly fine to add a float to an int, for example.&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
'''Duck-typing''' is a little bit different than the other categories, because it doesn't really have a direct opposite. Essentially, duck-typing is the philosophy that &amp;quot;If it walks like a duck, and quacks like a duck, it's a duck.&amp;quot; In programming terms, that means that we often don't care what type an object is, as long as it can do the things we ask.&lt;br /&gt;
&lt;br /&gt;
Let's look at an example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
# This function doubles the value it's passed.&lt;br /&gt;
def double(thing):&lt;br /&gt;
    return thing + thing&lt;br /&gt;
double(10) # Returns 20&lt;br /&gt;
double(&amp;quot;fish&amp;quot;) # Returns &amp;quot;fishfish&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If this were Java, we'd have to write two different methods here: one for things of type &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt;, and one for things of type &amp;lt;code&amp;gt;String&amp;lt;/code&amp;gt;. Since this is Python, though, we don't have to do that. Instead, Python lets us say, essentially: &amp;quot;This function uses the &amp;lt;code&amp;gt;+&amp;lt;/code&amp;gt; operator, so you can pass whatever object you want to the function, as long as the function supports the &amp;lt;code&amp;gt;+&amp;lt;/code&amp;gt; operator&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
To quote [https://groups.google.com/forum/?hl=en#!msg/comp.lang.python/CCs2oJdyuzc/NYjla5HKMOIJ Alex Martelli], one of the key people in the Python project,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;blockquote&amp;gt;&lt;br /&gt;
&amp;quot;[Don't] check whether it IS-a duck: check whether it QUACKS-like-a duck, WALKS-like-a duck, etc, etc, depending on exactly what subset of duck-like behaviour you need.&amp;quot;&lt;br /&gt;
&amp;lt;/blockquote&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&amp;lt;/ol&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Basic Types ===&lt;br /&gt;
&lt;br /&gt;
In Python, the basic scalar types are:&lt;br /&gt;
&lt;br /&gt;
# &amp;lt;code&amp;gt;str&amp;lt;/code&amp;gt; – a string.&lt;br /&gt;
# &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt; – an integer object with unlimited digits.&lt;br /&gt;
# &amp;lt;code&amp;gt;bool&amp;lt;/code&amp;gt; – a Boolean value.&lt;br /&gt;
# &amp;lt;code&amp;gt;float&amp;lt;/code&amp;gt; – a floating point number; generally equivalent to &amp;lt;code&amp;gt;double&amp;lt;/code&amp;gt; in Java.&lt;br /&gt;
# &amp;lt;code&amp;gt;bytes&amp;lt;/code&amp;gt; – represents a collection of bytes; you're unlikely to use this often.&lt;br /&gt;
&lt;br /&gt;
Casting is done in the C style - to parse an &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt; from a string, for instance, you'd write &amp;lt;code&amp;gt;int(&amp;quot;123&amp;quot;)&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== Basic Control Flow ===&lt;br /&gt;
In Python, blocks of code are delineated using colons and indentation instead of curly braces. '''''That means that proper indentation is mandatory.''''' Every time you use a colon, you must indent one step further, and every time a block ends, you must unindent a step.&lt;br /&gt;
&lt;br /&gt;
Conditional statements are done using the &amp;lt;code&amp;gt;if&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;elif&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;else&amp;lt;/code&amp;gt; operators, like in the example below - pay attention to the indentation:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
cookies_left = 10&lt;br /&gt;
cake_slices_left = 3&lt;br /&gt;
if cookies_left &amp;gt; 10:&lt;br /&gt;
    print(&amp;quot;Lots of cookies!&amp;quot;)&lt;br /&gt;
elif cookies_left &amp;gt; 8:&lt;br /&gt;
    print(&amp;quot;Plenty left!&amp;quot;)&lt;br /&gt;
elif cookies_left == 5:&lt;br /&gt;
    print(&amp;quot;Halfway done!&amp;quot;)&lt;br /&gt;
else:&lt;br /&gt;
    if cake_slices_left == 3:&lt;br /&gt;
        print(&amp;quot;Lots of cake!&amp;quot;)&lt;br /&gt;
    elif cake_slices_left == 2:&lt;br /&gt;
        print(&amp;quot;One slice gone!&amp;quot;)&lt;br /&gt;
    else:&lt;br /&gt;
        print(&amp;quot;Little to no cake left!&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== An Example Python Script ===&lt;br /&gt;
&lt;br /&gt;
In my mind, there's no better way to learn Python than to be immersed in a simple example script.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
print(&amp;quot;Hello World&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
fruits = [&amp;quot;apple&amp;quot;, &amp;quot;banana&amp;quot;, &amp;quot;cherry&amp;quot;, &amp;quot;date&amp;quot;]&lt;br /&gt;
for fruit in fruits:&lt;br /&gt;
    print(f&amp;quot;I always love to eat a fresh {fruit}&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Map the fruits list over to a new list containing the length of the fruit strings:&lt;br /&gt;
fruit_size = [len(fruit) for fruit in fruits]&lt;br /&gt;
&lt;br /&gt;
avg_fruit_size = sum(fruit_size) / len(fruit_size)&lt;br /&gt;
print(f&amp;quot;The average fruit string length is {avg_fruit_size:.2f}.&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Some things to notice:&lt;br /&gt;
&lt;br /&gt;
* Printing is achieved using the &amp;lt;code&amp;gt;print()&amp;lt;/code&amp;gt; function.&lt;br /&gt;
* Comments start with a pound symbol &amp;lt;code&amp;gt;#&amp;lt;/code&amp;gt;.&lt;br /&gt;
* We can transform/map a list to a new list in just one line!&lt;br /&gt;
&lt;br /&gt;
For some more examples, see [https://wiki.python.org/moin/SimplePrograms the Python wiki].&lt;br /&gt;
&lt;br /&gt;
=== A Few Gotchas ===&lt;br /&gt;
&lt;br /&gt;
Here are a few things you may not expect when starting out with Python:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;ol&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
Strings can be delimited using either single quotes (&amp;lt;code&amp;gt;'&amp;lt;/code&amp;gt;) or double quotes (&amp;lt;code&amp;gt;&amp;quot;&amp;lt;/code&amp;gt;), so &amp;lt;code&amp;gt;'Python'&amp;lt;/code&amp;gt; is the same as &amp;lt;code&amp;gt;&amp;quot;Python&amp;quot;&amp;lt;/code. You can also use three sets of quotes (&amp;lt;code&amp;gt;'''&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;&amp;quot;&amp;quot;&amp;quot;&amp;lt;/code&amp;gt;) to delineate a multiple-line string, like so:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
long_string = &amp;quot;&amp;quot;&amp;quot;This&lt;br /&gt;
is my&lt;br /&gt;
very long&lt;br /&gt;
multiple-line&lt;br /&gt;
string&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
To compare the equality of two objects, use the &amp;lt;code&amp;gt;==&amp;lt;/code&amp;gt; operator. To compare the identity of two objects (i.e. whether or not they are literally the same object, at the same place in memory), use the &amp;lt;code&amp;gt;is&amp;lt;/code&amp;gt; operator. These correspond, respectively to &amp;lt;code&amp;gt;.equals()&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;==&amp;lt;/code&amp;gt; in Java.&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
The &amp;lt;code&amp;gt;/&amp;lt;/code&amp;gt; operator performs floating-point division, not integer division, even when both its arguments are integers. If you want to do integer division, use the &amp;lt;code&amp;gt;//&amp;lt;/code&amp;gt; operator. Let's look at an example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
9   / 10    == 0.9 # Floating-point division&lt;br /&gt;
9.0 / 10.0  == 0.9 # Floating-point division&lt;br /&gt;
9   // 10   == 0   # Integer division&lt;br /&gt;
9.0 // 10.0 == 0.0 # Integer division, even though the resulting value is a float&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
As discussed in the section [[#Python's_Type_System|Python's Type System]], you can't combine strings and numbers using the &amp;lt;code&amp;gt;+&amp;lt;/code&amp;gt; operator. Instead, you'll have to use one of the following methods of string formatting:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
  &lt;br /&gt;
# Technique 1 – printf-style Formatting&lt;br /&gt;
# This is a classic style of string formatting, used in many programming languages, including in Java's String.format.&lt;br /&gt;
&amp;quot;You scored %d out of %d!&amp;quot; % (score, questions)&lt;br /&gt;
&lt;br /&gt;
# Technique 2 – str.format&lt;br /&gt;
&amp;quot;You scored {} out of {}!&amp;quot;.format(score, questions)&lt;br /&gt;
&lt;br /&gt;
# Technique 3 – f-strings&lt;br /&gt;
# These were only introduced in Python 3.6 but they're very convenient.&lt;br /&gt;
f&amp;quot;You scored {score} out of {questions}!&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# Technique 4 - String Concatenation&lt;br /&gt;
# This is fine for small things, but for more complicated stuff, use one of the other techniques.&lt;br /&gt;
&amp;quot;You scored &amp;quot; + str(score) + &amp;quot; out of &amp;quot; + str(questions) + &amp;quot;!&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&amp;lt;/ol&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Functions ===&lt;br /&gt;
&lt;br /&gt;
Define functions using the &amp;lt;code&amp;gt;def&amp;lt;/code&amp;gt; keyword:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def hello(name):&lt;br /&gt;
    print(f&amp;quot;Hello, {name}!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Invoke functions using parentheses:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
hello(&amp;quot;Batman&amp;quot;)&lt;br /&gt;
hello(&amp;quot;Superman&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Functions can have optional arguments; however, these must come after any required arguments:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def hello(name=&amp;quot;User&amp;quot;):&lt;br /&gt;
    print(f&amp;quot;Hello, {name}!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
hello() # Prints &amp;quot;Hello, User!&amp;quot;&lt;br /&gt;
hello(&amp;quot;Sarah&amp;quot;) # Prints &amp;quot;Hello, Sarah!&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Functions are just regular objects in Python, meaning you can do stuff like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def hello(name=&amp;quot;User&amp;quot;):&lt;br /&gt;
    print(f&amp;quot;Hello, {name}!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
greeting = hello&lt;br /&gt;
&lt;br /&gt;
greeting(&amp;quot;Siwei&amp;quot;) # Prints &amp;quot;Hello, Siwei!&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Collection Types ===&lt;br /&gt;
Python has a few basic, built-in collection types. They each have their own special use cases, but they share a lot of similarities. All built-in data structures in Python are zero-indexed, for instance.&lt;br /&gt;
&lt;br /&gt;
To obtain the number of elements in a collection, use the &amp;lt;code&amp;gt;len()&amp;lt;/code&amp;gt; function, like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish'] # This is a list; you'll learn about them below.&lt;br /&gt;
&lt;br /&gt;
len(pets) # Returns 3&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To check if a collection contains an item, use the &amp;lt;code&amp;gt;in&amp;lt;/code&amp;gt; operator:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish'] # This is a list; you'll learn about them below.&lt;br /&gt;
&lt;br /&gt;
'Dog' in pets # Returns True&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Helpfully, the Python Software Foundation maintains a page containing the asymptotic complexities of important operations on major Python data structures. It's available [https://wiki.python.org/moin/TimeComplexity here].&lt;br /&gt;
&lt;br /&gt;
==== Lists ====&lt;br /&gt;
&lt;br /&gt;
Unlike languages like Java and C, Python's array-like type doesn't have fixed length. Instead, a &amp;lt;code&amp;gt;list&amp;lt;/code&amp;gt; is a dynamic array (like Java's &amp;lt;code&amp;gt;ArrayList&amp;lt;/code&amp;gt;) of objects of any type. Here's an example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = [&amp;quot;Apple&amp;quot;, &amp;quot;Pear&amp;quot;, &amp;quot;Orange&amp;quot;] # Lists can be creating by placing their items between square brackets&lt;br /&gt;
&lt;br /&gt;
random_items = ['Apple', 12312, 2.0, [1, 2, 3]] # Lists can contain objects of different types - even other lists!&lt;br /&gt;
&lt;br /&gt;
pets.append('Turtle') # Adds 'Turtle' to the end of pets&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For the next few examples, we'll be using the following list:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish', 'Turtle', 'Lizard', 'Snake']&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access or assign elements of a list, use the &amp;lt;code&amp;gt;[]&amp;lt;/code&amp;gt; operator.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[0] # Returns 'Dog'&lt;br /&gt;
pets[1] = 'Cow' # Sets pets[1] to 'Cow'&lt;br /&gt;
pets[1] = 'Cat' # Sets pets[1] back to 'Cat' &lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You can also access or assign lists using negative indices, which will return elements starting from the end of the list:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[-1] # Returns 'Snake'&lt;br /&gt;
pets[-2] # Returns 'Lizard'&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You can also use 'slice notation' to obtain or assign subsets of lists:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[start:end] # Returns items from index start to index end - 1.&lt;br /&gt;
pets[start:]    # Returns items from index start to the end of the list, inclusive.&lt;br /&gt;
pets[:end]      # Returns items from the beginning of the list to index end - 1.&lt;br /&gt;
pets[:]         # Returns every item in the list&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
There's also a third, optional argument: &amp;lt;code&amp;gt;step&amp;lt;/code&amp;gt;, which lets you jump over values:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[start:end:step] # Returns items from index start to index end - 1, jumping step values at a time&lt;br /&gt;
&lt;br /&gt;
# Examples:&lt;br /&gt;
pets[1:5:2] # Returns items from index 1 to index 4, jumping 2 at a time, so ['Cat', 'Turtle']&lt;br /&gt;
pets[::3] # Returns all items in the list, jumping 3 at a time, so ['Dog', 'Turtle']&lt;br /&gt;
pets[::-1] # Returns all items in the list, jumping -1 at a time. This reverses the list, so ['Snake', 'Lizard', 'Turtle', 'Fish', 'Cat', 'Dog']&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Lists have all the performance characteristics you'd expect of a dynamic array - constant-time indexing, amortized constant-time appends, and so on.&lt;br /&gt;
&lt;br /&gt;
==== Tuples ====&lt;br /&gt;
&lt;br /&gt;
Python has a special data type called &amp;lt;code&amp;gt;tuple&amp;lt;/code&amp;gt;, which is exactly the same as a list except for the fact that it cannot be modified, so you can't append or replace items.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
cities = ('St. Louis', 'Los Angeles', 'Seattle') # Tuples are defined using parentheses.&lt;br /&gt;
numbers = 1, 2, 3 # You can also omit the parentheses if it's unambiguous&lt;br /&gt;
single_item_tuple = (1,) # To make a tuple with only one item, put a comma after it&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Tuples also enable you to have multiple return values from a function:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def compute_length(string):&lt;br /&gt;
    str_len = len(string)&lt;br /&gt;
    if str_len &amp;lt; 5:&lt;br /&gt;
        return str_len, &amp;quot;short&amp;quot;&lt;br /&gt;
    elif str_len &amp;lt; 40:&lt;br /&gt;
        return str_len, &amp;quot;medium&amp;quot;&lt;br /&gt;
    return str_len, &amp;quot;long&amp;quot;&lt;br /&gt;
&lt;br /&gt;
length, description = compute_length(&amp;quot;Four score and seven years ago&amp;quot;)&lt;br /&gt;
print(f&amp;quot;The {description} string is {length} characters long.&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
The above example also demonstrates Python's if...elif...else conditional structure.&lt;br /&gt;
&lt;br /&gt;
==== Dictionaries ====&lt;br /&gt;
&lt;br /&gt;
Python has another datatype called a '''dictionary''' (or &amp;lt;code&amp;gt;dict&amp;lt;/code&amp;gt;, for short), which are like ''Maps'' in Java, ''associative arrays'' in PHP, and ''object literals'' in JavaScript (coming up soon in Module 6). Essentially, they enable you to use any immutable object as the key in your data structure. &amp;lt;code&amp;gt;dict&amp;lt;/code&amp;gt; objects can be created using either the &amp;lt;code&amp;gt;dict&amp;lt;/code&amp;gt; function, or by placing items between curly braces, separating keys and values using colons:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits_in_bowl = {&lt;br /&gt;
    'apple': 4,&lt;br /&gt;
    'banana': 2,&lt;br /&gt;
    'cherry': 0,&lt;br /&gt;
    'date': 12&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
apple_count = fruits_in_bowl['apple'] # Equals 4&lt;br /&gt;
&lt;br /&gt;
fruits_in_bowl['pear'] = 9 # Sets 'pear' in the dictionary to 9.&lt;br /&gt;
&lt;br /&gt;
for fruit, num in fruits_in_bowl.items():&lt;br /&gt;
    print(f&amp;quot;There are {num} {fruit}(s) in the bowl.&amp;quot; % (num, fruit))&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If you only want the keys from a dictionary, you can just iterate over it directly, like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
for fruit in fruits_in_bowl:&lt;br /&gt;
    print(fruit)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If you want only the values but not the keys from a dictionary, use &amp;lt;code&amp;gt;my_dictionary.values()&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
==== Sets ==== &lt;br /&gt;
A &amp;lt;code&amp;gt;set&amp;lt;/code&amp;gt; is an unordered collection of unique items, with constant-time membership checking. &lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = {'Apple', 'Apple', 'Apple', 'Pear'} # The set removes duplicates, so it will only contain {'Apple', 'Pear'}&lt;br /&gt;
fruits = set(['Apple', 'Apple', 'Apple', 'Pear']) # This line transforms a list into a set&lt;br /&gt;
print('Apple' in fruits) # Constant-time!&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Loops ===&lt;br /&gt;
&lt;br /&gt;
In Python, while loops are written like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
i = 0&lt;br /&gt;
while i &amp;lt; 10:&lt;br /&gt;
    i += 1&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
For loops are written like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish']&lt;br /&gt;
&lt;br /&gt;
for pet in pets:&lt;br /&gt;
    print(pet)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
To iterate over a range of numbers, you can use the convenient &amp;lt;code&amp;gt;range&amp;lt;/code&amp;gt; function, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
for i in range(20, 30): # If you omit the first argument to range, it's assumed to be zero.&lt;br /&gt;
    print(i)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Note that &amp;lt;code&amp;gt;range&amp;lt;/code&amp;gt; provides a closed-open range. That is to say, it is inclusive of its lower bound and exclusive of its upper bound. To be very explicit about it:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
list(range(3, 6)) == [3, 4, 5]&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Unlike in other languages you may know, the following is not good practice in Python:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish']&lt;br /&gt;
&lt;br /&gt;
# BAD PRACTICE. DO NOT USE.&lt;br /&gt;
for i in range(len(pets)):&lt;br /&gt;
    pet = pets[i]&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Instead, if you need to access both a variable and its index, use the &amp;lt;code&amp;gt;enumerate&amp;lt;/code&amp;gt; function, which allows you to iterate through a group of items, along with their indexes, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish']&lt;br /&gt;
&lt;br /&gt;
for index, pet in enumerate(pets):&lt;br /&gt;
    print(f&amp;quot;{pet} at index {index}&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Generator Expressions and Comprehensions ===&lt;br /&gt;
&lt;br /&gt;
A generator is a special kind of object that, basically, represents a collection of items using a value and a function for generating the next value in the collection. In other words, it's a way of creating something that behaves like a list, but which only generates one value at a time, and discards a value when it's done with it. Say, for example, you wanted to do an operation on 10,000,000,000,000 numbers. You could put them all in a list, then iterate over the list, but that would take a lot of memory, plus you'd have to create and fill the entire list before beginning to actually work on your problem. Instead, you'd probably be better off using a generator; telling the computer, essentially: “The starting value is 0. When I ask for the next number in the collection, add 1 to current value and give me that.”&lt;br /&gt;
&lt;br /&gt;
A generator expression is an expression that is evaluated to create a generator. They're super useful. Generator expressions can take two forms – they can be used with and without a condition:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
(EXPRESSION for VARIABLE in ITERABLE) # Unconditional&lt;br /&gt;
(EXPRESSION for VARIABLE in ITERABLE if CONDITION) # Conditional&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
For our purposes, you can think of an iterable as anything you can do a for loop over. Let's take a look at a generator expression in use:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
double_even_digits = (number * 2 for number in range(10) if number % 2 == 0)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
That line says that &amp;lt;code&amp;gt;double_even_digits&amp;lt;/code&amp;gt; is every even number between 0 and 10 multiplied by two. Simple enough, right? If we wanted to use all of the numbers, not just the even ones, we could simply remove the if statement at the end of the expression.&lt;br /&gt;
&lt;br /&gt;
Here's the thing, though: if you were to print &amp;lt;code&amp;gt;double_even_digits&amp;lt;/code&amp;gt;, instead of a nice bunch of numbers, you'd get something that looks like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&amp;lt;generator object &amp;lt;genexpr&amp;gt;&amp;lt;code&amp;gt;at 0x107fc92b0&amp;gt;&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
That's because generators are lazy! They don't generate their values until those values are needed, and they discard values once they're no longer needed. As a result, '''you can only iterate over a generator once'''. In this case, you can't print out the whole generator, because it hasn't generated all the values yet. You can, however, iterate over the generator, and print its values one at a time, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
for number in double_even_digits:&lt;br /&gt;
    print(number)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
You can also make a list out of the generator, which will go through all the items in the generator and put them in a list, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
even_number_list = list(double_even_digits)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
That's actually a great segue to the second topic of this section: comprehensions. A comprehension is just a prettier way to make lists, sets, and dicts out of a generator expressions.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
# If you want a list:&lt;br /&gt;
list(i for i in range(10) if i % 2 == 0) # Don't do this&lt;br /&gt;
[i for i in range(10) if i % 2 == 0] # Use a list comprehension instead!&lt;br /&gt;
&lt;br /&gt;
# If you want a set:&lt;br /&gt;
set(i for i in range(10) if i % 2 == 0) # Don't do this&lt;br /&gt;
{i for i in range(10) if i % 2 == 0} # Use a set comprehension instead!&lt;br /&gt;
&lt;br /&gt;
# If you want a dict:&lt;br /&gt;
dict((i, i + 1) for i in range(10) if i % 2 == 0) # Don't do this&lt;br /&gt;
{i : i + 1 for i in range(10) if i % 2 == 0} # Use a dict comprehension instead!&lt;br /&gt;
&lt;br /&gt;
# If you want a tuple:&lt;br /&gt;
tuple(i for i in range(10) if i % 2 == 0) # Unfortunately, there's no better way to do this&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
In general, generators and comprehensions should be used whenever possible - they're the fastest and easiest way to build collections. If you ever see yourself writing code like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
# BAD PRACTICE! DO NOT USE!&lt;br /&gt;
digits = []&lt;br /&gt;
for digit in range(10):&lt;br /&gt;
    digits.append(digit)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Don't do it! Instead, use a generator expression or comprehension, as appropriate. A good way to decide whether a generator expression or comprehension is better for this situation is that, if you're just going to be iterating over your collection once, you should use an generator expression. If not, use a comprehension.&lt;br /&gt;
&lt;br /&gt;
=== Sorting ===&lt;br /&gt;
&lt;br /&gt;
Sorting in Python is frequently performed using the &amp;lt;code&amp;gt;sorted&amp;lt;/code&amp;gt; function, which takes two arguments: an iterable (anything you can do a for-loop over, including lists and tuples) and a function used to evaluate each item. If the function is omitted, Python will try to sort the lists by value.&lt;br /&gt;
&lt;br /&gt;
The following example demonstrates using an inline function, which Python calls a ''lambda''.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = ['apple', 'banana', 'cherry', 'date']&lt;br /&gt;
&lt;br /&gt;
# sort the fruits by string length&lt;br /&gt;
new_fruits = sorted(fruits, key=lambda v: len(v) // 2)&lt;br /&gt;
&lt;br /&gt;
print(new_fruits) # ['date', 'apple', 'banana', 'cherry']&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Alternatively, you can sort a &amp;lt;code&amp;gt;list&amp;lt;/code&amp;gt; using the &amp;lt;code&amp;gt;.sort&amp;lt;/code&amp;gt; method. This is faster than calling &amp;lt;code&amp;gt;sorted&amp;lt;/code&amp;gt;, but it modifies the list in-place and returns &amp;lt;code&amp;gt;None&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = ['apple', 'banana', 'cherry', 'date']&lt;br /&gt;
fruits.sort()&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
=== Import ===&lt;br /&gt;
&lt;br /&gt;
If you want to use functions from other libraries (including ones that you install using pip), use &amp;lt;code&amp;gt;import&amp;lt;/code&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
import time&lt;br /&gt;
&lt;br /&gt;
current_time = time.localtime()&lt;br /&gt;
print(time.strftime('%a, %d %b %Y %H:%M:%S', current_time))&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If you want to pull the functions out of their namespace, you can use &amp;lt;code&amp;gt;from ___ import ___&amp;lt;/code&amp;gt; syntax:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
from time import localtime, strftime&lt;br /&gt;
&lt;br /&gt;
current_time = localtime()&lt;br /&gt;
print(strftime('%a, %d %b %Y %H:%M:%S', current_time))&lt;br /&gt;
&lt;br /&gt;
# Be aware that this technique, although convenient, may cause unexpected behavior if the function names that you're pulling out of the namespace are already used for other purposes in Python.&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
=== File I/O ===&lt;br /&gt;
&lt;br /&gt;
You can read an entire file into a variable like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
f = open(&amp;quot;example.txt&amp;quot;)&lt;br /&gt;
file_contents = f.read()&lt;br /&gt;
&lt;br /&gt;
f.close() # free up memory when we're finished with the file&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
A better option is to use a with-block, which handles opening and closing the file for you automatically:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
with open(&amp;quot;example.txt&amp;quot;) as f:&lt;br /&gt;
    file_contents = f.read()&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
You can read a file line-by-line like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
with open(&amp;quot;example.txt&amp;quot;) as f:&lt;br /&gt;
    for line in f:&lt;br /&gt;
        print(&amp;quot;Read line: %s&amp;quot; % line.rstrip())&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
You can write to a file like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
with open(&amp;quot;example.txt&amp;quot;, &amp;quot;w&amp;quot;) as f:&lt;br /&gt;
    f.write(&amp;quot;Hello\nWorld\n&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
=== Command-Line Arguments ===&lt;br /&gt;
&lt;br /&gt;
Command line arguments are accessible in the variable &amp;lt;code&amp;gt;sys.argv&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
The following example shows a program that expects a filename as its argument, and it prints a usage message if the argument is not present ([https://stackoverflow.com/questions/983201/python-and-sys-argv source]).&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
import sys, os&lt;br /&gt;
&lt;br /&gt;
if len(sys.argv) &amp;lt; 2:&lt;br /&gt;
    sys.exit(f&amp;quot;Usage: {sys.argv[0]} filename&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
filename = sys.argv[1]&lt;br /&gt;
&lt;br /&gt;
if not os.path.exists(filename):&lt;br /&gt;
    sys.exit(f&amp;quot;Error: File '{sys.argv[1]}' not found&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Object-Oriented Programming ===&lt;br /&gt;
&lt;br /&gt;
You can define and use a class like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
class Food:&lt;br /&gt;
    # constructor:&lt;br /&gt;
    def __init__(self, name):&lt;br /&gt;
        self.name = name&lt;br /&gt;
    &lt;br /&gt;
    def format_name(self):&lt;br /&gt;
        return f&amp;quot;Gotta love to eat {self.name}&amp;quot;&lt;br /&gt;
&lt;br /&gt;
class Fruit(Food):&lt;br /&gt;
    def get_definition(self):&lt;br /&gt;
        return f&amp;quot;{Food.format_name(self)} (fruit)&amp;quot;&lt;br /&gt;
&lt;br /&gt;
fruit = Fruit(&amp;quot;Cherry&amp;quot;)&lt;br /&gt;
print(fruit.format_name())&lt;br /&gt;
print(Food.get_definition())&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
This is the same example as in [[PHP#Object-Oriented_Programming|the PHP guide]].&lt;br /&gt;
&lt;br /&gt;
Some things to notice:&lt;br /&gt;
&lt;br /&gt;
* Instance methods ''always'' take &amp;lt;code&amp;gt;self&amp;lt;/code&amp;gt; as their first argument, followed by any number of additional parameters. This can be misleading for programmers familiar with other languages, because the number of arguments you feed to the method is actually ''one less than'' the number of declared parameters. Whenever you call a method on a class instance, that instance is implicitly fed into the explicitly-declared &amp;lt;code&amp;gt;self&amp;lt;/code&amp;gt; parameter of the method.&lt;br /&gt;
*: Note that the &amp;lt;code&amp;gt;self&amp;lt;/code&amp;gt; variable has the same purpose as the &amp;lt;code&amp;gt;this&amp;lt;/code&amp;gt; variable in languages like PHP, Java, JavaScript, and C++.&lt;br /&gt;
*There is no need for a &amp;lt;code&amp;gt;new&amp;lt;/code&amp;gt; keyword in Python.&lt;br /&gt;
&lt;br /&gt;
= Footnotes =&lt;br /&gt;
# {{note|interpreted}}This is an oversimplification. If you're interested, here's a quick explanation of how: In CPython (the reference implementation of Python) programs are compiled to bytecode, an intermediate representation, which is then interpreted.&lt;br /&gt;
[[Category:Module 4]]&lt;/div&gt;</summary>
		<author><name>Alex</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Python&amp;diff=2524</id>
		<title>Python</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Python&amp;diff=2524"/>
		<updated>2018-02-19T18:20:50Z</updated>

		<summary type="html">&lt;p&gt;Alex: /* Installation */  Replaced bash_profile with bashrc&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Languages like Java and C++ have lots of rules regarding variable types, syntax, return values, and so on. These can be cumbersome when you are trying to write short, quick scripts to perform tasks. This is where a ''scripting language'' comes into play.&lt;br /&gt;
&lt;br /&gt;
'''Python''' is a language well-suited to rapid prototype development. It is generally an ''interpreted language'', which means that, generally speaking, a Python program is converted line by line into instructions for the computer to execute as the program runs, instead of having a separate compilation step beforehand {{ref|interpreted}}. The syntax is clean, and it is usually clear at first glance what is going on when you write in Python.&lt;br /&gt;
&lt;br /&gt;
= Installation =&lt;br /&gt;
&lt;br /&gt;
Python may already be installed on your system. To see whether or not it is, enter the command&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ python3 --version&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If it tells you a version of Python '''greater than or equal to 3.6''' then you're good to go. If not, you need to do a quick package install to get it up and running. Using yum, it's just &amp;lt;code&amp;gt;sudo yum install python36&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
If you'd like to be able to just type &amp;lt;code&amp;gt;python&amp;lt;/code&amp;gt; instead of &amp;lt;code&amp;gt;python3&amp;lt;/code&amp;gt;, you can add the following line to the &amp;lt;code&amp;gt;~/.bashrc&amp;lt;/code&amp;gt; file on your instance:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
alias python=&amp;quot;/usr/bin/python3&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Python 2 vs Python 3 ====&lt;br /&gt;
&lt;br /&gt;
In 2008, a new version of Python – Python 3 – was released, with a number of changes that made it incompatible with the previous version, Python 2. For several years, the Python community was slow to make the change to Python 3, but today, Python 3 is ''the'' standard for new code. The ''only'' reason to write Python 2 code today is because you have to work in an environment or with libraries that do not support Python 3, and that situation is becoming increasingly rare.&lt;br /&gt;
&lt;br /&gt;
'''For CSE 330 (and this guide), you ''must'' use Python 3.6 or greater.'''&lt;br /&gt;
&lt;br /&gt;
=== Pip ===&lt;br /&gt;
&lt;br /&gt;
Linux distributions have package managers like ''Apt'', ''Yum'', and ''YaST''. PHP has a package manager named ''PEAR''. It's now time to introduce Python's leading package manager: '''pip'''.&lt;br /&gt;
&lt;br /&gt;
Once you have pip installed, you can use it to install Python packages. Use the &amp;lt;code&amp;gt;pip-3.6&amp;lt;/code&amp;gt; command:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ pip-3.6 install package_name # RHEL&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
If you'd like to be able to just type &amp;lt;code&amp;gt;pip&amp;lt;/code&amp;gt; instead of &amp;lt;code&amp;gt;pip-3.6&amp;lt;/code&amp;gt;, you can add the following line to the &amp;lt;code&amp;gt;~/.bashrc&amp;lt;/code&amp;gt; file on your instance:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
alias pip=&amp;quot;/usr/bin/pip-3.6&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Running Python =&lt;br /&gt;
&lt;br /&gt;
There are two common ways to run Python code: via the console, and via a Python script file.&lt;br /&gt;
&lt;br /&gt;
=== The Python Console ===&lt;br /&gt;
&lt;br /&gt;
The Python console enables you to experiment with code without opening a text editor. To enter the Python console, simply type the ''python'' command at the terminal:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ python3&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
To leave the interactive console, either type &amp;lt;code&amp;gt;quit()&amp;lt;/code&amp;gt; or press &amp;lt;code&amp;gt;Ctrl-D&amp;lt;/code&amp;gt; (on both Mac and Windows).&lt;br /&gt;
&lt;br /&gt;
=== Python Script Files ===&lt;br /&gt;
&lt;br /&gt;
You can also save Python script files for later use. The extension for Python scripts is &amp;lt;code&amp;gt;*.py&amp;lt;/code&amp;gt;. To run a script file, simply feed its path as an argument to the &amp;lt;code&amp;gt;python&amp;lt;/code&amp;gt; command in Terminal:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ python3 my_script.py&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Python Syntax and Language Components =&lt;br /&gt;
&lt;br /&gt;
This section contains a very brief overview of Python syntax. For a more comprehensive introduction, see [http://docs.python.org/tutorial/ the Python docs].&lt;br /&gt;
&lt;br /&gt;
=== Python's Type System ===&lt;br /&gt;
&lt;br /&gt;
Python is a dynamically-typed, strongly-typed, and duck-typed language. What does that mean? Well, let's take those categories one by one:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;ol&amp;gt;&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
'''Dynamic typing''', in contrast to ''static typing'' means that the types of objects can be changed. In Java, for instance, if you tried to write the following code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
int c = 2;&lt;br /&gt;
c = &amp;quot;fish&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Your code would fail to compile, because the Java compiler wouldn't allow you to change the type of the variable &amp;lt;code&amp;gt;c&amp;lt;/code&amp;gt; from &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt; to &amp;lt;code&amp;gt;String&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Python, however, is just fine with that. You can write:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
c = 2&lt;br /&gt;
c = &amp;quot;fish&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
And Python will happily do what you ask.&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
'''Strong typing''', in contrast to ''weak typing'', means, roughly, that a language won't implicitly convert types for you. So far, you've used a lot of PHP, which is very weakly typed. For example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;php&amp;quot;&amp;gt;&lt;br /&gt;
echo &amp;quot;10&amp;quot; . 2;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In PHP, this works just fine. The PHP interpreter sees that &amp;lt;code&amp;gt;2&amp;lt;/code&amp;gt; is an int, and silently converts it to a string for you, so that &amp;lt;code&amp;gt;&amp;quot;10&amp;quot;. 2&amp;lt;/code&amp;gt; equals &amp;lt;code&amp;gt;&amp;quot;102&amp;quot;&amp;lt;/code&amp;gt;. The problem with weak typing is that it can make it unclear to the programmer why things are happening the way they are. For instance, in PHP, the expression &amp;lt;code&amp;gt;&amp;quot;10&amp;quot; == 10&amp;lt;/code&amp;gt; is true, which can be less than obvious. Python, however, tries to disallow that sort of thing:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
&amp;quot;10&amp;quot; + &amp;quot;10&amp;quot; # Allowed – concatenates the two strings.&lt;br /&gt;
10   +  10  # Allowed – adds the two ints.&lt;br /&gt;
&amp;quot;10&amp;quot; +  10  # Not allowed – raises a TypeError&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Perhaps the one exception to this rule is the relationship between numeric types; it's perfectly fine to add a float to an int, for example.&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
'''Duck-typing''' is a little bit different than the other categories, because it doesn't really have a direct opposite. Essentially, duck-typing is the philosophy that &amp;quot;If it walks like a duck, and quacks like a duck, it's a duck.&amp;quot; In programming terms, that means that we often don't care what type an object is, as long as it can do the things we ask.&lt;br /&gt;
&lt;br /&gt;
Let's look at an example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
# This function doubles the value it's passed.&lt;br /&gt;
def double(thing):&lt;br /&gt;
    return thing + thing&lt;br /&gt;
double(10) # Returns 20&lt;br /&gt;
double(&amp;quot;fish&amp;quot;) # Returns &amp;quot;fishfish&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If this were Java, we'd have to write two different methods here: one for things of type &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt;, and one for things of type &amp;lt;code&amp;gt;String&amp;lt;/code&amp;gt;. Since this is Python, though, we don't have to do that. Instead, Python lets us say, essentially: &amp;quot;This function uses the &amp;lt;code&amp;gt;+&amp;lt;/code&amp;gt; operator, so you can pass whatever object you want to the function, as long as the function supports the &amp;lt;code&amp;gt;+&amp;lt;/code&amp;gt; operator&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
To quote [https://groups.google.com/forum/?hl=en#!msg/comp.lang.python/CCs2oJdyuzc/NYjla5HKMOIJ Alex Martelli], one of the key people in the Python project,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;blockquote&amp;gt;&lt;br /&gt;
&amp;quot;[Don't] check whether it IS-a duck: check whether it QUACKS-like-a duck, WALKS-like-a duck, etc, etc, depending on exactly what subset of duck-like behaviour you need.&amp;quot;&lt;br /&gt;
&amp;lt;/blockquote&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&amp;lt;/ol&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Basic Types ===&lt;br /&gt;
&lt;br /&gt;
In Python, the basic scalar types are:&lt;br /&gt;
&lt;br /&gt;
# &amp;lt;code&amp;gt;str&amp;lt;/code&amp;gt; – a string.&lt;br /&gt;
# &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt; – an integer object with unlimited digits.&lt;br /&gt;
# &amp;lt;code&amp;gt;bool&amp;lt;/code&amp;gt; – a Boolean value.&lt;br /&gt;
# &amp;lt;code&amp;gt;float&amp;lt;/code&amp;gt; – a floating point number; generally equivalent to &amp;lt;code&amp;gt;double&amp;lt;/code&amp;gt; in Java.&lt;br /&gt;
# &amp;lt;code&amp;gt;bytes&amp;lt;/code&amp;gt; – represents a collection of bytes; you're unlikely to use this often.&lt;br /&gt;
&lt;br /&gt;
Casting is done in the C style - to parse an &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt; from a string, for instance, you'd write &amp;lt;code&amp;gt;int(&amp;quot;123&amp;quot;)&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== Basic Control Flow ===&lt;br /&gt;
In Python, blocks of code are delineated using colons and indentation instead of curly braces. '''''That means that proper indentation is mandatory.''''' Every time you use a colon, you must indent one step further, and every time a block ends, you must unindent a step.&lt;br /&gt;
&lt;br /&gt;
Conditional statements are done using the &amp;lt;code&amp;gt;if&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;elif&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;else&amp;lt;/code&amp;gt; operators, like in the example below - pay attention to the indentation:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
cookies_left = 10&lt;br /&gt;
cake_slices_left = 3&lt;br /&gt;
if cookies_left &amp;gt; 10:&lt;br /&gt;
    print(&amp;quot;Lots of cookies!&amp;quot;)&lt;br /&gt;
elif cookies_left &amp;gt; 8:&lt;br /&gt;
    print(&amp;quot;Plenty left!&amp;quot;)&lt;br /&gt;
elif cookies_left == 5:&lt;br /&gt;
    print(&amp;quot;Halfway done!&amp;quot;)&lt;br /&gt;
else:&lt;br /&gt;
    if cake_slices_left == 3:&lt;br /&gt;
        print(&amp;quot;Lots of cake!&amp;quot;)&lt;br /&gt;
    elif cake_slices_left == 2:&lt;br /&gt;
        print(&amp;quot;One slice gone!&amp;quot;)&lt;br /&gt;
    else:&lt;br /&gt;
        print(&amp;quot;Little to no cake left!&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== An Example Python Script ===&lt;br /&gt;
&lt;br /&gt;
In my mind, there's no better way to learn Python than to be immersed in a simple example script.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
print(&amp;quot;Hello World&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
fruits = [&amp;quot;apple&amp;quot;, &amp;quot;banana&amp;quot;, &amp;quot;cherry&amp;quot;, &amp;quot;date&amp;quot;]&lt;br /&gt;
for fruit in fruits:&lt;br /&gt;
    print(f&amp;quot;I always love to eat a fresh {fruit}&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Map the fruits list over to a new list containing the length of the fruit strings:&lt;br /&gt;
fruit_size = [len(fruit) for fruit in fruits]&lt;br /&gt;
&lt;br /&gt;
avg_fruit_size = sum(fruit_size) / len(fruit_size)&lt;br /&gt;
print(f&amp;quot;The average fruit string length is {avg_fruit_size:.2f}.&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Some things to notice:&lt;br /&gt;
&lt;br /&gt;
* Printing is achieved using the &amp;lt;code&amp;gt;print()&amp;lt;/code&amp;gt; function.&lt;br /&gt;
* Comments start with a pound symbol &amp;lt;code&amp;gt;#&amp;lt;/code&amp;gt;.&lt;br /&gt;
* We can transform/map a list to a new list in just one line!&lt;br /&gt;
&lt;br /&gt;
For some more examples, see [https://wiki.python.org/moin/SimplePrograms the Python wiki].&lt;br /&gt;
&lt;br /&gt;
=== A Few Gotchas ===&lt;br /&gt;
&lt;br /&gt;
Here are a few things you may not expect when starting out with Python:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;ol&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
Strings can be delimited using either single quotes (&amp;lt;code&amp;gt;'&amp;lt;/code&amp;gt;) or double quotes (&amp;lt;code&amp;gt;&amp;quot;&amp;lt;/code&amp;gt;), so &amp;lt;code&amp;gt;'Python'&amp;lt;/code&amp;gt; is the same as &amp;lt;code&amp;gt;&amp;quot;Python&amp;quot;&amp;lt;/code. You can also use three sets of quotes (&amp;lt;code&amp;gt;'''&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;&amp;quot;&amp;quot;&amp;quot;&amp;lt;/code&amp;gt;) to delineate a multiple-line string, like so:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
long_string = &amp;quot;&amp;quot;&amp;quot;This&lt;br /&gt;
is my&lt;br /&gt;
very long&lt;br /&gt;
multiple-line&lt;br /&gt;
string&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
To compare the equality of two objects, use the &amp;lt;code&amp;gt;==&amp;lt;/code&amp;gt; operator. To compare the identity of two objects (i.e. whether or not they are literally the same object, at the same place in memory), use the &amp;lt;code&amp;gt;is&amp;lt;/code&amp;gt; operator. These correspond, respectively to &amp;lt;code&amp;gt;.equals()&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;==&amp;lt;/code&amp;gt; in Java.&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
The &amp;lt;code&amp;gt;/&amp;lt;/code&amp;gt; operator performs floating-point division, not integer division, even when both its arguments are integers. If you want to do integer division, use the &amp;lt;code&amp;gt;//&amp;lt;/code&amp;gt; operator. Let's look at an example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
9   / 10    == 0.9 # Floating-point division&lt;br /&gt;
9.0 / 10.0  == 0.9 # Floating-point division&lt;br /&gt;
9   // 10   == 0   # Integer division&lt;br /&gt;
9.0 // 10.0 == 0.0 # Integer division, even though the resulting value is a float&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
As discussed in the section [[#Python's_Type_System|Python's Type System]], you can't combine strings and numbers using the &amp;lt;code&amp;gt;+&amp;lt;/code&amp;gt; operator. Instead, you'll have to use one of the following methods of string formatting:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
  &lt;br /&gt;
# Technique 1 – printf-style Formatting&lt;br /&gt;
# This is a classic style of string formatting, used in many programming languages, including in Java's String.format.&lt;br /&gt;
&amp;quot;You scored %d out of %d!&amp;quot; % (score, questions)&lt;br /&gt;
&lt;br /&gt;
# Technique 2 – str.format&lt;br /&gt;
&amp;quot;You scored {} out of {}!&amp;quot;.format(score, questions)&lt;br /&gt;
&lt;br /&gt;
# Technique 3 – f-strings&lt;br /&gt;
# These were only introduced in Python 3.6 but they're very convenient.&lt;br /&gt;
f&amp;quot;You scored {score} out of {questions}!&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# Technique 4 - String Concatenation&lt;br /&gt;
# This is fine for small things, but for more complicated stuff, use one of the other techniques.&lt;br /&gt;
&amp;quot;You scored &amp;quot; + str(score) + &amp;quot; out of &amp;quot; + str(questions) + &amp;quot;!&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&amp;lt;/ol&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Functions ===&lt;br /&gt;
&lt;br /&gt;
Define functions using the &amp;lt;code&amp;gt;def&amp;lt;/code&amp;gt; keyword:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def hello(name):&lt;br /&gt;
    print(f&amp;quot;Hello, {name}!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Invoke functions using parentheses:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
hello(&amp;quot;Batman&amp;quot;)&lt;br /&gt;
hello(&amp;quot;Superman&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Functions can have optional arguments; however, these must come after any required arguments:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def hello(name=&amp;quot;User&amp;quot;):&lt;br /&gt;
    print(f&amp;quot;Hello, {name}!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
hello() # Prints &amp;quot;Hello, User!&amp;quot;&lt;br /&gt;
hello(&amp;quot;Sarah&amp;quot;) # Prints &amp;quot;Hello, Sarah!&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Functions are just regular objects in Python, meaning you can do stuff like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def hello(name=&amp;quot;User&amp;quot;):&lt;br /&gt;
    print(f&amp;quot;Hello, {name}!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
greeting = hello&lt;br /&gt;
&lt;br /&gt;
greeting(&amp;quot;Siwei&amp;quot;) # Prints &amp;quot;Hello, Siwei!&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Collection Types ===&lt;br /&gt;
Python has a few basic, built-in collection types. They each have their own special use cases, but they share a lot of similarities. All built-in data structures in Python are zero-indexed, for instance.&lt;br /&gt;
&lt;br /&gt;
To obtain the number of elements in a collection, use the &amp;lt;code&amp;gt;len()&amp;lt;/code&amp;gt; function, like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish'] # This is a list; you'll learn about them below.&lt;br /&gt;
&lt;br /&gt;
len(pets) # Returns 3&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To check if a collection contains an item, use the &amp;lt;code&amp;gt;in&amp;lt;/code&amp;gt; operator:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish'] # This is a list; you'll learn about them below.&lt;br /&gt;
&lt;br /&gt;
'Dog' in pets # Returns True&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Helpfully, the Python Software Foundation maintains a page containing the asymptotic complexities of important operations on major Python data structures. It's available [https://wiki.python.org/moin/TimeComplexity here].&lt;br /&gt;
&lt;br /&gt;
==== Lists ====&lt;br /&gt;
&lt;br /&gt;
Unlike languages like Java and C, Python's array-like type doesn't have fixed length. Instead, a &amp;lt;code&amp;gt;list&amp;lt;/code&amp;gt; is a dynamic array (like Java's &amp;lt;code&amp;gt;ArrayList&amp;lt;/code&amp;gt;) of objects of any type. Here's an example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = [&amp;quot;Apple&amp;quot;, &amp;quot;Pear&amp;quot;, &amp;quot;Orange&amp;quot;] # Lists can be creating by placing their items between square brackets&lt;br /&gt;
&lt;br /&gt;
random_items = ['Apple', 12312, 2.0, [1, 2, 3]] # Lists can contain objects of different types - even other lists!&lt;br /&gt;
&lt;br /&gt;
pets.append('Turtle') # Adds 'Turtle' to the end of pets&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For the next few examples, we'll be using the following list:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish', 'Turtle', 'Lizard', 'Snake']&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access or assign elements of a list, use the &amp;lt;code&amp;gt;[]&amp;lt;/code&amp;gt; operator.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[0] # Returns 'Dog'&lt;br /&gt;
pets[1] = 'Cow' # Sets pets[1] to 'Cow'&lt;br /&gt;
pets[1] = 'Cat' # Sets pets[1] back to 'Cat' &lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You can also access or assign lists using negative indices, which will return elements starting from the end of the list:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[-1] # Returns 'Snake'&lt;br /&gt;
pets[-2] # Returns 'Lizard'&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You can also use 'slice notation' to obtain or assign subsets of lists:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[start:end] # Returns items from index start to index end - 1.&lt;br /&gt;
pets[start:]    # Returns items from index start to the end of the list, inclusive.&lt;br /&gt;
pets[:end]      # Returns items from the beginning of the list to index end - 1.&lt;br /&gt;
pets[:]         # Returns every item in the list&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
There's also a third, optional argument: &amp;lt;code&amp;gt;step&amp;lt;/code&amp;gt;, which lets you jump over values:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[start:end:step] # Returns items from index start to index end - 1, jumping step values at a time&lt;br /&gt;
&lt;br /&gt;
# Examples:&lt;br /&gt;
pets[1:5:2] # Returns items from index 1 to index 4, jumping 2 at a time, so ['Cat', 'Turtle']&lt;br /&gt;
pets[::3] # Returns all items in the list, jumping 3 at a time, so ['Dog', 'Turtle']&lt;br /&gt;
pets[::-1] # Returns all items in the list, jumping -1 at a time. This reverses the list, so ['Snake', 'Lizard', 'Turtle', 'Fish', 'Cat', 'Dog']&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Lists have all the performance characteristics you'd expect of a dynamic array - constant-time indexing, amortized constant-time appends, and so on.&lt;br /&gt;
&lt;br /&gt;
==== Tuples ====&lt;br /&gt;
&lt;br /&gt;
Python has a special data type called &amp;lt;code&amp;gt;tuple&amp;lt;/code&amp;gt;, which is exactly the same as a list except for the fact that it cannot be modified, so you can't append or replace items.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
cities = ('St. Louis', 'Los Angeles', 'Seattle') # Tuples are defined using parentheses.&lt;br /&gt;
numbers = 1, 2, 3 # You can also omit the parentheses if it's unambiguous&lt;br /&gt;
single_item_tuple = (1,) # To make a tuple with only one item, put a comma after it&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Tuples also enable you to have multiple return values from a function:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def compute_length(string):&lt;br /&gt;
    str_len = len(string)&lt;br /&gt;
    if str_len &amp;lt; 5:&lt;br /&gt;
        return str_len, &amp;quot;short&amp;quot;&lt;br /&gt;
    elif str_len &amp;lt; 40:&lt;br /&gt;
        return str_len, &amp;quot;medium&amp;quot;&lt;br /&gt;
    return str_len, &amp;quot;long&amp;quot;&lt;br /&gt;
&lt;br /&gt;
length, description = compute_length(&amp;quot;Four score and seven years ago&amp;quot;)&lt;br /&gt;
print(f&amp;quot;The {description} string is {length} characters long.&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
The above example also demonstrates Python's if...elif...else conditional structure.&lt;br /&gt;
&lt;br /&gt;
==== Dictionaries ====&lt;br /&gt;
&lt;br /&gt;
Python has another datatype called a '''dictionary''' (or &amp;lt;code&amp;gt;dict&amp;lt;/code&amp;gt;, for short), which are like ''Maps'' in Java, ''associative arrays'' in PHP, and ''object literals'' in JavaScript (coming up soon in Module 6). Essentially, they enable you to use any immutable object as the key in your data structure. &amp;lt;code&amp;gt;dict&amp;lt;/code&amp;gt; objects can be created using either the &amp;lt;code&amp;gt;dict&amp;lt;/code&amp;gt; function, or by placing items between curly braces, separating keys and values using colons:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits_in_bowl = {&lt;br /&gt;
    'apple': 4,&lt;br /&gt;
    'banana': 2,&lt;br /&gt;
    'cherry': 0,&lt;br /&gt;
    'date': 12&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
apple_count = fruits_in_bowl['apple'] # Equals 4&lt;br /&gt;
&lt;br /&gt;
fruits_in_bowl['pear'] = 9 # Sets 'pear' in the dictionary to 9.&lt;br /&gt;
&lt;br /&gt;
for fruit, num in fruits_in_bowl.items():&lt;br /&gt;
    print(f&amp;quot;There are {num} {fruit}(s) in the bowl.&amp;quot; % (num, fruit))&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If you only want the keys from a dictionary, you can just iterate over it directly, like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
for fruit in fruits_in_bowl:&lt;br /&gt;
    print(fruit)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If you want only the values but not the keys from a dictionary, use &amp;lt;code&amp;gt;my_dictionary.values()&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
==== Sets ==== &lt;br /&gt;
A &amp;lt;code&amp;gt;set&amp;lt;/code&amp;gt; is an unordered collection of unique items, with constant-time membership checking. &lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = {'Apple', 'Apple', 'Apple', 'Pear'} # The set removes duplicates, so it will only contain {'Apple', 'Pear'}&lt;br /&gt;
fruits = set(['Apple', 'Apple', 'Apple', 'Pear']) # This line transforms a list into a set&lt;br /&gt;
print('Apple' in fruits) # Constant-time!&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Loops ===&lt;br /&gt;
&lt;br /&gt;
In Python, while loops are written like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
i = 0&lt;br /&gt;
while i &amp;lt; 10:&lt;br /&gt;
    i += 1&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
For loops are written like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish']&lt;br /&gt;
&lt;br /&gt;
for pet in pets:&lt;br /&gt;
    print(pet)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
To iterate over a range of numbers, you can use the convenient &amp;lt;code&amp;gt;range&amp;lt;/code&amp;gt; function, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
for i in range(20, 30): # If you omit the first argument to range, it's assumed to be zero.&lt;br /&gt;
    print(i)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Note that &amp;lt;code&amp;gt;range&amp;lt;/code&amp;gt; provides a closed-open range. That is to say, it is inclusive of its lower bound and exclusive of its upper bound. To be very explicit about it:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
list(range(3, 6)) == [3, 4, 5]&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Unlike in other languages you may know, the following is not good practice in Python:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish']&lt;br /&gt;
&lt;br /&gt;
# BAD PRACTICE. DO NOT USE.&lt;br /&gt;
for i in range(len(pets)):&lt;br /&gt;
    pet = pets[i]&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Instead, if you need to access both a variable and its index, use the &amp;lt;code&amp;gt;enumerate&amp;lt;/code&amp;gt; function, which allows you to iterate through a group of items, along with their indexes, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish']&lt;br /&gt;
&lt;br /&gt;
for index, pet in enumerate(pets):&lt;br /&gt;
    print(f&amp;quot;{pet} at index {index}&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Generator Expressions and Comprehensions ===&lt;br /&gt;
&lt;br /&gt;
A generator is a special kind of object that, basically, represents a collection of items using a value and a function for generating the next value in the collection. In other words, it's a way of creating something that behaves like a list, but which only generates one value at a time, and discards a value when it's done with it. Say, for example, you wanted to do an operation on 10,000,000,000,000 numbers. You could put them all in a list, then iterate over the list, but that would take a lot of memory, plus you'd have to create and fill the entire list before beginning to actually work on your problem. Instead, you'd probably be better off using a generator; telling the computer, essentially: “The starting value is 0. When I ask for the next number in the collection, add 1 to current value and give me that.”&lt;br /&gt;
&lt;br /&gt;
A generator expression is an expression that is evaluated to create a generator. They're super useful. Generator expressions can take two forms – they can be used with and without a condition:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
(EXPRESSION for VARIABLE in ITERABLE) # Unconditional&lt;br /&gt;
(EXPRESSION for VARIABLE in ITERABLE if CONDITION) # Conditional&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
For our purposes, you can think of an iterable as anything you can do a for loop over. Let's take a look at a generator expression in use:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
double_even_digits = (number * 2 for number in range(10) if number % 2 == 0)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
That line says that &amp;lt;code&amp;gt;double_even_digits&amp;lt;/code&amp;gt; is every even number between 0 and 10 multiplied by two. Simple enough, right? If we wanted to use all of the numbers, not just the even ones, we could simply remove the if statement at the end of the expression.&lt;br /&gt;
&lt;br /&gt;
Here's the thing, though: if you were to print &amp;lt;code&amp;gt;double_even_digits&amp;lt;/code&amp;gt;, instead of a nice bunch of numbers, you'd get something that looks like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&amp;lt;generator object &amp;lt;genexpr&amp;gt;&amp;lt;code&amp;gt;at 0x107fc92b0&amp;gt;&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
That's because generators are lazy! They don't generate their values until those values are needed, and they discard values once they're no longer needed. As a result, '''you can only iterate over a generator once'''. In this case, you can't print out the whole generator, because it hasn't generated all the values yet. You can, however, iterate over the generator, and print its values one at a time, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
for number in double_even_digits:&lt;br /&gt;
    print(number)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
You can also make a list out of the generator, which will go through all the items in the generator and put them in a list, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
even_number_list = list(double_even_digits)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
That's actually a great segue to the second topic of this section: comprehensions. A comprehension is just a prettier way to make lists, sets, and dicts out of a generator expressions.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
# If you want a list:&lt;br /&gt;
list(i for i in range(10) if i % 2 == 0) # Don't do this&lt;br /&gt;
[i for i in range(10) if i % 2 == 0] # Use a list comprehension instead!&lt;br /&gt;
&lt;br /&gt;
# If you want a set:&lt;br /&gt;
set(i for i in range(10) if i % 2 == 0) # Don't do this&lt;br /&gt;
{i for i in range(10) if i % 2 == 0} # Use a set comprehension instead!&lt;br /&gt;
&lt;br /&gt;
# If you want a dict:&lt;br /&gt;
dict((i, i + 1) for i in range(10) if i % 2 == 0) # Don't do this&lt;br /&gt;
{i : i + 1 for i in range(10) if i % 2 == 0} # Use a dict comprehension instead!&lt;br /&gt;
&lt;br /&gt;
# If you want a tuple:&lt;br /&gt;
tuple(i for i in range(10) if i % 2 == 0) # Unfortunately, there's no better way to do this&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
In general, generators and comprehensions should be used whenever possible - they're the fastest and easiest way to build collections. If you ever see yourself writing code like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
# BAD PRACTICE! DO NOT USE!&lt;br /&gt;
digits = []&lt;br /&gt;
for digit in range(10):&lt;br /&gt;
    digits.append(digit)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Don't do it! Instead, use a generator expression or comprehension, as appropriate. A good way to decide whether a generator expression or comprehension is better for this situation is that, if you're just going to be iterating over your collection once, you should use an generator expression. If not, use a comprehension.&lt;br /&gt;
&lt;br /&gt;
=== Sorting ===&lt;br /&gt;
&lt;br /&gt;
Sorting in Python is frequently performed using the &amp;lt;code&amp;gt;sorted&amp;lt;/code&amp;gt; function, which takes two arguments: an iterable (anything you can do a for-loop over, including lists and tuples) and a function used to evaluate each item. If the function is omitted, Python will try to sort the lists by value.&lt;br /&gt;
&lt;br /&gt;
The following example demonstrates using an inline function, which Python calls a ''lambda''.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = ['apple', 'banana', 'cherry', 'date']&lt;br /&gt;
&lt;br /&gt;
# sort the fruits by string length&lt;br /&gt;
new_fruits = sorted(fruits, key=lambda v: len(v) // 2)&lt;br /&gt;
&lt;br /&gt;
print(new_fruits) # ['date', 'apple', 'banana', 'cherry']&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Alternatively, you can sort a &amp;lt;code&amp;gt;list&amp;lt;/code&amp;gt; using the &amp;lt;code&amp;gt;.sort&amp;lt;/code&amp;gt; method. This is faster than calling &amp;lt;code&amp;gt;sorted&amp;lt;/code&amp;gt;, but it modifies the list in-place and returns &amp;lt;code&amp;gt;None&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = ['apple', 'banana', 'cherry', 'date']&lt;br /&gt;
fruits.sort()&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
=== Import ===&lt;br /&gt;
&lt;br /&gt;
If you want to use functions from other libraries (including ones that you install using pip), use &amp;lt;code&amp;gt;import&amp;lt;/code&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
import time&lt;br /&gt;
&lt;br /&gt;
current_time = time.localtime()&lt;br /&gt;
print(time.strftime('%a, %d %b %Y %H:%M:%S', current_time))&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If you want to pull the functions out of their namespace, you can use &amp;lt;code&amp;gt;from ___ import ___&amp;lt;/code&amp;gt; syntax:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
from time import localtime, strftime&lt;br /&gt;
&lt;br /&gt;
current_time = localtime()&lt;br /&gt;
print(strftime('%a, %d %b %Y %H:%M:%S', current_time))&lt;br /&gt;
&lt;br /&gt;
# Be aware that this technique, although convenient, may cause unexpected behavior if the function names that you're pulling out of the namespace are already used for other purposes in Python.&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
=== File I/O ===&lt;br /&gt;
&lt;br /&gt;
You can read an entire file into a variable like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
f = open(&amp;quot;example.txt&amp;quot;)&lt;br /&gt;
file_contents = f.read()&lt;br /&gt;
&lt;br /&gt;
f.close() # free up memory when we're finished with the file&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
A better option is to use a with-block, which handles opening and closing the file for you automatically:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
with open(&amp;quot;example.txt&amp;quot;) as f:&lt;br /&gt;
    file_contents = f.read()&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
You can read a file line-by-line like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
with open(&amp;quot;example.txt&amp;quot;) as f:&lt;br /&gt;
    for line in f:&lt;br /&gt;
        print(&amp;quot;Read line: %s&amp;quot; % line.rstrip())&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
You can write to a file like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
with open(&amp;quot;example.txt&amp;quot;, &amp;quot;w&amp;quot;) as f:&lt;br /&gt;
    f.write(&amp;quot;Hello\nWorld\n&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
=== Command-Line Arguments ===&lt;br /&gt;
&lt;br /&gt;
Command line arguments are accessible in the variable &amp;lt;code&amp;gt;sys.argv&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
The following example shows a program that expects a filename as its argument, and it prints a usage message if the argument is not present ([https://stackoverflow.com/questions/983201/python-and-sys-argv source]).&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
import sys, os&lt;br /&gt;
&lt;br /&gt;
if len(sys.argv) &amp;lt; 2:&lt;br /&gt;
    sys.exit(f&amp;quot;Usage: {sys.argv[0]} filename&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
filename = sys.argv[1]&lt;br /&gt;
&lt;br /&gt;
if not os.path.exists(filename):&lt;br /&gt;
    sys.exit(f&amp;quot;Error: File '{sys.argv[1]}' not found&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Object-Oriented Programming ===&lt;br /&gt;
&lt;br /&gt;
You can define and use a class like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
class Food:&lt;br /&gt;
    # constructor:&lt;br /&gt;
    def __init__(self, name):&lt;br /&gt;
        self.name = name&lt;br /&gt;
    &lt;br /&gt;
    def format_name(self):&lt;br /&gt;
        return f&amp;quot;Gotta love to eat {self.name}&amp;quot;&lt;br /&gt;
&lt;br /&gt;
class Fruit(Food):&lt;br /&gt;
    def format_name(self):&lt;br /&gt;
        return f&amp;quot;{Food.format_name(self)} (fruit)&amp;quot;&lt;br /&gt;
&lt;br /&gt;
fruit = Fruit(&amp;quot;Cherry&amp;quot;)&lt;br /&gt;
print(fruit.format_name())&lt;br /&gt;
print(Food.get_definition())&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
This is the same example as in [[PHP#Object-Oriented_Programming|the PHP guide]].&lt;br /&gt;
&lt;br /&gt;
Some things to notice:&lt;br /&gt;
&lt;br /&gt;
* Instance methods ''always'' take &amp;lt;code&amp;gt;self&amp;lt;/code&amp;gt; as their first argument, followed by any number of additional parameters. This can be misleading for programmers familiar with other languages, because the number of arguments you feed to the method is actually ''one less than'' the number of declared parameters. Whenever you call a method on a class instance, that instance is implicitly fed into the explicitly-declared &amp;lt;code&amp;gt;self&amp;lt;/code&amp;gt; parameter of the method.&lt;br /&gt;
*: Note that the &amp;lt;code&amp;gt;self&amp;lt;/code&amp;gt; variable has the same purpose as the &amp;lt;code&amp;gt;this&amp;lt;/code&amp;gt; variable in languages like PHP, Java, JavaScript, and C++.&lt;br /&gt;
*There is no need for a &amp;lt;code&amp;gt;new&amp;lt;/code&amp;gt; keyword in Python.&lt;br /&gt;
&lt;br /&gt;
= Footnotes =&lt;br /&gt;
# {{note|interpreted}}This is an oversimplification. If you're interested, here's a quick explanation of how: In CPython (the reference implementation of Python) programs are compiled to bytecode, an intermediate representation, which is then interpreted.&lt;br /&gt;
[[Category:Module 4]]&lt;/div&gt;</summary>
		<author><name>Alex</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Python&amp;diff=2523</id>
		<title>Python</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Python&amp;diff=2523"/>
		<updated>2018-02-19T18:19:33Z</updated>

		<summary type="html">&lt;p&gt;Alex: Updated pip for Python 3.6&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Languages like Java and C++ have lots of rules regarding variable types, syntax, return values, and so on. These can be cumbersome when you are trying to write short, quick scripts to perform tasks. This is where a ''scripting language'' comes into play.&lt;br /&gt;
&lt;br /&gt;
'''Python''' is a language well-suited to rapid prototype development. It is generally an ''interpreted language'', which means that, generally speaking, a Python program is converted line by line into instructions for the computer to execute as the program runs, instead of having a separate compilation step beforehand {{ref|interpreted}}. The syntax is clean, and it is usually clear at first glance what is going on when you write in Python.&lt;br /&gt;
&lt;br /&gt;
= Installation =&lt;br /&gt;
&lt;br /&gt;
Python may already be installed on your system. To see whether or not it is, enter the command&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ python3 --version&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If it tells you a version of Python '''greater than or equal to 3.6''' then you're good to go. If not, you need to do a quick package install to get it up and running. Using yum, it's just &amp;lt;code&amp;gt;sudo yum install python36&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
If you'd like to be able to just type &amp;lt;code&amp;gt;python&amp;lt;/code&amp;gt; instead of &amp;lt;code&amp;gt;python3&amp;lt;/code&amp;gt;, you can add the following line to the &amp;lt;code&amp;gt;~/.bash_profile&amp;lt;/code&amp;gt; file on your instance:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
alias python=&amp;quot;/usr/bin/python3&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Python 2 vs Python 3 ====&lt;br /&gt;
&lt;br /&gt;
In 2008, a new version of Python – Python 3 – was released, with a number of changes that made it incompatible with the previous version, Python 2. For several years, the Python community was slow to make the change to Python 3, but today, Python 3 is ''the'' standard for new code. The ''only'' reason to write Python 2 code today is because you have to work in an environment or with libraries that do not support Python 3, and that situation is becoming increasingly rare.&lt;br /&gt;
&lt;br /&gt;
'''For CSE 330 (and this guide), you ''must'' use Python 3.6 or greater.'''&lt;br /&gt;
&lt;br /&gt;
=== Pip ===&lt;br /&gt;
&lt;br /&gt;
Linux distributions have package managers like ''Apt'', ''Yum'', and ''YaST''. PHP has a package manager named ''PEAR''. It's now time to introduce Python's leading package manager: '''pip'''.&lt;br /&gt;
&lt;br /&gt;
Once you have pip installed, you can use it to install Python packages. Use the &amp;lt;code&amp;gt;pip-3.6&amp;lt;/code&amp;gt; command:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ pip-3.6 install package_name # RHEL&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
If you'd like to be able to just type &amp;lt;code&amp;gt;pip&amp;lt;/code&amp;gt; instead of &amp;lt;code&amp;gt;pip-3.6&amp;lt;/code&amp;gt;, you can add the following line to the &amp;lt;code&amp;gt;~/.bash_profile&amp;lt;/code&amp;gt; file on your instance:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
alias pip=&amp;quot;/usr/bin/pip-3.6&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Running Python =&lt;br /&gt;
&lt;br /&gt;
There are two common ways to run Python code: via the console, and via a Python script file.&lt;br /&gt;
&lt;br /&gt;
=== The Python Console ===&lt;br /&gt;
&lt;br /&gt;
The Python console enables you to experiment with code without opening a text editor. To enter the Python console, simply type the ''python'' command at the terminal:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ python3&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
To leave the interactive console, either type &amp;lt;code&amp;gt;quit()&amp;lt;/code&amp;gt; or press &amp;lt;code&amp;gt;Ctrl-D&amp;lt;/code&amp;gt; (on both Mac and Windows).&lt;br /&gt;
&lt;br /&gt;
=== Python Script Files ===&lt;br /&gt;
&lt;br /&gt;
You can also save Python script files for later use. The extension for Python scripts is &amp;lt;code&amp;gt;*.py&amp;lt;/code&amp;gt;. To run a script file, simply feed its path as an argument to the &amp;lt;code&amp;gt;python&amp;lt;/code&amp;gt; command in Terminal:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ python3 my_script.py&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Python Syntax and Language Components =&lt;br /&gt;
&lt;br /&gt;
This section contains a very brief overview of Python syntax. For a more comprehensive introduction, see [http://docs.python.org/tutorial/ the Python docs].&lt;br /&gt;
&lt;br /&gt;
=== Python's Type System ===&lt;br /&gt;
&lt;br /&gt;
Python is a dynamically-typed, strongly-typed, and duck-typed language. What does that mean? Well, let's take those categories one by one:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;ol&amp;gt;&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
'''Dynamic typing''', in contrast to ''static typing'' means that the types of objects can be changed. In Java, for instance, if you tried to write the following code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
int c = 2;&lt;br /&gt;
c = &amp;quot;fish&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Your code would fail to compile, because the Java compiler wouldn't allow you to change the type of the variable &amp;lt;code&amp;gt;c&amp;lt;/code&amp;gt; from &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt; to &amp;lt;code&amp;gt;String&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Python, however, is just fine with that. You can write:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
c = 2&lt;br /&gt;
c = &amp;quot;fish&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
And Python will happily do what you ask.&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
'''Strong typing''', in contrast to ''weak typing'', means, roughly, that a language won't implicitly convert types for you. So far, you've used a lot of PHP, which is very weakly typed. For example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;php&amp;quot;&amp;gt;&lt;br /&gt;
echo &amp;quot;10&amp;quot; . 2;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In PHP, this works just fine. The PHP interpreter sees that &amp;lt;code&amp;gt;2&amp;lt;/code&amp;gt; is an int, and silently converts it to a string for you, so that &amp;lt;code&amp;gt;&amp;quot;10&amp;quot;. 2&amp;lt;/code&amp;gt; equals &amp;lt;code&amp;gt;&amp;quot;102&amp;quot;&amp;lt;/code&amp;gt;. The problem with weak typing is that it can make it unclear to the programmer why things are happening the way they are. For instance, in PHP, the expression &amp;lt;code&amp;gt;&amp;quot;10&amp;quot; == 10&amp;lt;/code&amp;gt; is true, which can be less than obvious. Python, however, tries to disallow that sort of thing:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
&amp;quot;10&amp;quot; + &amp;quot;10&amp;quot; # Allowed – concatenates the two strings.&lt;br /&gt;
10   +  10  # Allowed – adds the two ints.&lt;br /&gt;
&amp;quot;10&amp;quot; +  10  # Not allowed – raises a TypeError&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Perhaps the one exception to this rule is the relationship between numeric types; it's perfectly fine to add a float to an int, for example.&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
'''Duck-typing''' is a little bit different than the other categories, because it doesn't really have a direct opposite. Essentially, duck-typing is the philosophy that &amp;quot;If it walks like a duck, and quacks like a duck, it's a duck.&amp;quot; In programming terms, that means that we often don't care what type an object is, as long as it can do the things we ask.&lt;br /&gt;
&lt;br /&gt;
Let's look at an example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
# This function doubles the value it's passed.&lt;br /&gt;
def double(thing):&lt;br /&gt;
    return thing + thing&lt;br /&gt;
double(10) # Returns 20&lt;br /&gt;
double(&amp;quot;fish&amp;quot;) # Returns &amp;quot;fishfish&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If this were Java, we'd have to write two different methods here: one for things of type &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt;, and one for things of type &amp;lt;code&amp;gt;String&amp;lt;/code&amp;gt;. Since this is Python, though, we don't have to do that. Instead, Python lets us say, essentially: &amp;quot;This function uses the &amp;lt;code&amp;gt;+&amp;lt;/code&amp;gt; operator, so you can pass whatever object you want to the function, as long as the function supports the &amp;lt;code&amp;gt;+&amp;lt;/code&amp;gt; operator&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
To quote [https://groups.google.com/forum/?hl=en#!msg/comp.lang.python/CCs2oJdyuzc/NYjla5HKMOIJ Alex Martelli], one of the key people in the Python project,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;blockquote&amp;gt;&lt;br /&gt;
&amp;quot;[Don't] check whether it IS-a duck: check whether it QUACKS-like-a duck, WALKS-like-a duck, etc, etc, depending on exactly what subset of duck-like behaviour you need.&amp;quot;&lt;br /&gt;
&amp;lt;/blockquote&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&amp;lt;/ol&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Basic Types ===&lt;br /&gt;
&lt;br /&gt;
In Python, the basic scalar types are:&lt;br /&gt;
&lt;br /&gt;
# &amp;lt;code&amp;gt;str&amp;lt;/code&amp;gt; – a string.&lt;br /&gt;
# &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt; – an integer object with unlimited digits.&lt;br /&gt;
# &amp;lt;code&amp;gt;bool&amp;lt;/code&amp;gt; – a Boolean value.&lt;br /&gt;
# &amp;lt;code&amp;gt;float&amp;lt;/code&amp;gt; – a floating point number; generally equivalent to &amp;lt;code&amp;gt;double&amp;lt;/code&amp;gt; in Java.&lt;br /&gt;
# &amp;lt;code&amp;gt;bytes&amp;lt;/code&amp;gt; – represents a collection of bytes; you're unlikely to use this often.&lt;br /&gt;
&lt;br /&gt;
Casting is done in the C style - to parse an &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt; from a string, for instance, you'd write &amp;lt;code&amp;gt;int(&amp;quot;123&amp;quot;)&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== Basic Control Flow ===&lt;br /&gt;
In Python, blocks of code are delineated using colons and indentation instead of curly braces. '''''That means that proper indentation is mandatory.''''' Every time you use a colon, you must indent one step further, and every time a block ends, you must unindent a step.&lt;br /&gt;
&lt;br /&gt;
Conditional statements are done using the &amp;lt;code&amp;gt;if&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;elif&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;else&amp;lt;/code&amp;gt; operators, like in the example below - pay attention to the indentation:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
cookies_left = 10&lt;br /&gt;
cake_slices_left = 3&lt;br /&gt;
if cookies_left &amp;gt; 10:&lt;br /&gt;
    print(&amp;quot;Lots of cookies!&amp;quot;)&lt;br /&gt;
elif cookies_left &amp;gt; 8:&lt;br /&gt;
    print(&amp;quot;Plenty left!&amp;quot;)&lt;br /&gt;
elif cookies_left == 5:&lt;br /&gt;
    print(&amp;quot;Halfway done!&amp;quot;)&lt;br /&gt;
else:&lt;br /&gt;
    if cake_slices_left == 3:&lt;br /&gt;
        print(&amp;quot;Lots of cake!&amp;quot;)&lt;br /&gt;
    elif cake_slices_left == 2:&lt;br /&gt;
        print(&amp;quot;One slice gone!&amp;quot;)&lt;br /&gt;
    else:&lt;br /&gt;
        print(&amp;quot;Little to no cake left!&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== An Example Python Script ===&lt;br /&gt;
&lt;br /&gt;
In my mind, there's no better way to learn Python than to be immersed in a simple example script.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
print(&amp;quot;Hello World&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
fruits = [&amp;quot;apple&amp;quot;, &amp;quot;banana&amp;quot;, &amp;quot;cherry&amp;quot;, &amp;quot;date&amp;quot;]&lt;br /&gt;
for fruit in fruits:&lt;br /&gt;
    print(f&amp;quot;I always love to eat a fresh {fruit}&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Map the fruits list over to a new list containing the length of the fruit strings:&lt;br /&gt;
fruit_size = [len(fruit) for fruit in fruits]&lt;br /&gt;
&lt;br /&gt;
avg_fruit_size = sum(fruit_size) / len(fruit_size)&lt;br /&gt;
print(f&amp;quot;The average fruit string length is {avg_fruit_size:.2f}.&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Some things to notice:&lt;br /&gt;
&lt;br /&gt;
* Printing is achieved using the &amp;lt;code&amp;gt;print()&amp;lt;/code&amp;gt; function.&lt;br /&gt;
* Comments start with a pound symbol &amp;lt;code&amp;gt;#&amp;lt;/code&amp;gt;.&lt;br /&gt;
* We can transform/map a list to a new list in just one line!&lt;br /&gt;
&lt;br /&gt;
For some more examples, see [https://wiki.python.org/moin/SimplePrograms the Python wiki].&lt;br /&gt;
&lt;br /&gt;
=== A Few Gotchas ===&lt;br /&gt;
&lt;br /&gt;
Here are a few things you may not expect when starting out with Python:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;ol&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
Strings can be delimited using either single quotes (&amp;lt;code&amp;gt;'&amp;lt;/code&amp;gt;) or double quotes (&amp;lt;code&amp;gt;&amp;quot;&amp;lt;/code&amp;gt;), so &amp;lt;code&amp;gt;'Python'&amp;lt;/code&amp;gt; is the same as &amp;lt;code&amp;gt;&amp;quot;Python&amp;quot;&amp;lt;/code. You can also use three sets of quotes (&amp;lt;code&amp;gt;'''&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;&amp;quot;&amp;quot;&amp;quot;&amp;lt;/code&amp;gt;) to delineate a multiple-line string, like so:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
long_string = &amp;quot;&amp;quot;&amp;quot;This&lt;br /&gt;
is my&lt;br /&gt;
very long&lt;br /&gt;
multiple-line&lt;br /&gt;
string&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
To compare the equality of two objects, use the &amp;lt;code&amp;gt;==&amp;lt;/code&amp;gt; operator. To compare the identity of two objects (i.e. whether or not they are literally the same object, at the same place in memory), use the &amp;lt;code&amp;gt;is&amp;lt;/code&amp;gt; operator. These correspond, respectively to &amp;lt;code&amp;gt;.equals()&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;==&amp;lt;/code&amp;gt; in Java.&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
The &amp;lt;code&amp;gt;/&amp;lt;/code&amp;gt; operator performs floating-point division, not integer division, even when both its arguments are integers. If you want to do integer division, use the &amp;lt;code&amp;gt;//&amp;lt;/code&amp;gt; operator. Let's look at an example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
9   / 10    == 0.9 # Floating-point division&lt;br /&gt;
9.0 / 10.0  == 0.9 # Floating-point division&lt;br /&gt;
9   // 10   == 0   # Integer division&lt;br /&gt;
9.0 // 10.0 == 0.0 # Integer division, even though the resulting value is a float&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
As discussed in the section [[#Python's_Type_System|Python's Type System]], you can't combine strings and numbers using the &amp;lt;code&amp;gt;+&amp;lt;/code&amp;gt; operator. Instead, you'll have to use one of the following methods of string formatting:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
  &lt;br /&gt;
# Technique 1 – printf-style Formatting&lt;br /&gt;
# This is a classic style of string formatting, used in many programming languages, including in Java's String.format.&lt;br /&gt;
&amp;quot;You scored %d out of %d!&amp;quot; % (score, questions)&lt;br /&gt;
&lt;br /&gt;
# Technique 2 – str.format&lt;br /&gt;
&amp;quot;You scored {} out of {}!&amp;quot;.format(score, questions)&lt;br /&gt;
&lt;br /&gt;
# Technique 3 – f-strings&lt;br /&gt;
# These were only introduced in Python 3.6 but they're very convenient.&lt;br /&gt;
f&amp;quot;You scored {score} out of {questions}!&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# Technique 4 - String Concatenation&lt;br /&gt;
# This is fine for small things, but for more complicated stuff, use one of the other techniques.&lt;br /&gt;
&amp;quot;You scored &amp;quot; + str(score) + &amp;quot; out of &amp;quot; + str(questions) + &amp;quot;!&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&amp;lt;/ol&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Functions ===&lt;br /&gt;
&lt;br /&gt;
Define functions using the &amp;lt;code&amp;gt;def&amp;lt;/code&amp;gt; keyword:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def hello(name):&lt;br /&gt;
    print(f&amp;quot;Hello, {name}!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Invoke functions using parentheses:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
hello(&amp;quot;Batman&amp;quot;)&lt;br /&gt;
hello(&amp;quot;Superman&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Functions can have optional arguments; however, these must come after any required arguments:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def hello(name=&amp;quot;User&amp;quot;):&lt;br /&gt;
    print(f&amp;quot;Hello, {name}!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
hello() # Prints &amp;quot;Hello, User!&amp;quot;&lt;br /&gt;
hello(&amp;quot;Sarah&amp;quot;) # Prints &amp;quot;Hello, Sarah!&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Functions are just regular objects in Python, meaning you can do stuff like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def hello(name=&amp;quot;User&amp;quot;):&lt;br /&gt;
    print(f&amp;quot;Hello, {name}!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
greeting = hello&lt;br /&gt;
&lt;br /&gt;
greeting(&amp;quot;Siwei&amp;quot;) # Prints &amp;quot;Hello, Siwei!&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Collection Types ===&lt;br /&gt;
Python has a few basic, built-in collection types. They each have their own special use cases, but they share a lot of similarities. All built-in data structures in Python are zero-indexed, for instance.&lt;br /&gt;
&lt;br /&gt;
To obtain the number of elements in a collection, use the &amp;lt;code&amp;gt;len()&amp;lt;/code&amp;gt; function, like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish'] # This is a list; you'll learn about them below.&lt;br /&gt;
&lt;br /&gt;
len(pets) # Returns 3&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To check if a collection contains an item, use the &amp;lt;code&amp;gt;in&amp;lt;/code&amp;gt; operator:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish'] # This is a list; you'll learn about them below.&lt;br /&gt;
&lt;br /&gt;
'Dog' in pets # Returns True&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Helpfully, the Python Software Foundation maintains a page containing the asymptotic complexities of important operations on major Python data structures. It's available [https://wiki.python.org/moin/TimeComplexity here].&lt;br /&gt;
&lt;br /&gt;
==== Lists ====&lt;br /&gt;
&lt;br /&gt;
Unlike languages like Java and C, Python's array-like type doesn't have fixed length. Instead, a &amp;lt;code&amp;gt;list&amp;lt;/code&amp;gt; is a dynamic array (like Java's &amp;lt;code&amp;gt;ArrayList&amp;lt;/code&amp;gt;) of objects of any type. Here's an example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = [&amp;quot;Apple&amp;quot;, &amp;quot;Pear&amp;quot;, &amp;quot;Orange&amp;quot;] # Lists can be creating by placing their items between square brackets&lt;br /&gt;
&lt;br /&gt;
random_items = ['Apple', 12312, 2.0, [1, 2, 3]] # Lists can contain objects of different types - even other lists!&lt;br /&gt;
&lt;br /&gt;
pets.append('Turtle') # Adds 'Turtle' to the end of pets&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For the next few examples, we'll be using the following list:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish', 'Turtle', 'Lizard', 'Snake']&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access or assign elements of a list, use the &amp;lt;code&amp;gt;[]&amp;lt;/code&amp;gt; operator.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[0] # Returns 'Dog'&lt;br /&gt;
pets[1] = 'Cow' # Sets pets[1] to 'Cow'&lt;br /&gt;
pets[1] = 'Cat' # Sets pets[1] back to 'Cat' &lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You can also access or assign lists using negative indices, which will return elements starting from the end of the list:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[-1] # Returns 'Snake'&lt;br /&gt;
pets[-2] # Returns 'Lizard'&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You can also use 'slice notation' to obtain or assign subsets of lists:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[start:end] # Returns items from index start to index end - 1.&lt;br /&gt;
pets[start:]    # Returns items from index start to the end of the list, inclusive.&lt;br /&gt;
pets[:end]      # Returns items from the beginning of the list to index end - 1.&lt;br /&gt;
pets[:]         # Returns every item in the list&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
There's also a third, optional argument: &amp;lt;code&amp;gt;step&amp;lt;/code&amp;gt;, which lets you jump over values:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[start:end:step] # Returns items from index start to index end - 1, jumping step values at a time&lt;br /&gt;
&lt;br /&gt;
# Examples:&lt;br /&gt;
pets[1:5:2] # Returns items from index 1 to index 4, jumping 2 at a time, so ['Cat', 'Turtle']&lt;br /&gt;
pets[::3] # Returns all items in the list, jumping 3 at a time, so ['Dog', 'Turtle']&lt;br /&gt;
pets[::-1] # Returns all items in the list, jumping -1 at a time. This reverses the list, so ['Snake', 'Lizard', 'Turtle', 'Fish', 'Cat', 'Dog']&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Lists have all the performance characteristics you'd expect of a dynamic array - constant-time indexing, amortized constant-time appends, and so on.&lt;br /&gt;
&lt;br /&gt;
==== Tuples ====&lt;br /&gt;
&lt;br /&gt;
Python has a special data type called &amp;lt;code&amp;gt;tuple&amp;lt;/code&amp;gt;, which is exactly the same as a list except for the fact that it cannot be modified, so you can't append or replace items.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
cities = ('St. Louis', 'Los Angeles', 'Seattle') # Tuples are defined using parentheses.&lt;br /&gt;
numbers = 1, 2, 3 # You can also omit the parentheses if it's unambiguous&lt;br /&gt;
single_item_tuple = (1,) # To make a tuple with only one item, put a comma after it&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Tuples also enable you to have multiple return values from a function:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def compute_length(string):&lt;br /&gt;
    str_len = len(string)&lt;br /&gt;
    if str_len &amp;lt; 5:&lt;br /&gt;
        return str_len, &amp;quot;short&amp;quot;&lt;br /&gt;
    elif str_len &amp;lt; 40:&lt;br /&gt;
        return str_len, &amp;quot;medium&amp;quot;&lt;br /&gt;
    return str_len, &amp;quot;long&amp;quot;&lt;br /&gt;
&lt;br /&gt;
length, description = compute_length(&amp;quot;Four score and seven years ago&amp;quot;)&lt;br /&gt;
print(f&amp;quot;The {description} string is {length} characters long.&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
The above example also demonstrates Python's if...elif...else conditional structure.&lt;br /&gt;
&lt;br /&gt;
==== Dictionaries ====&lt;br /&gt;
&lt;br /&gt;
Python has another datatype called a '''dictionary''' (or &amp;lt;code&amp;gt;dict&amp;lt;/code&amp;gt;, for short), which are like ''Maps'' in Java, ''associative arrays'' in PHP, and ''object literals'' in JavaScript (coming up soon in Module 6). Essentially, they enable you to use any immutable object as the key in your data structure. &amp;lt;code&amp;gt;dict&amp;lt;/code&amp;gt; objects can be created using either the &amp;lt;code&amp;gt;dict&amp;lt;/code&amp;gt; function, or by placing items between curly braces, separating keys and values using colons:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits_in_bowl = {&lt;br /&gt;
    'apple': 4,&lt;br /&gt;
    'banana': 2,&lt;br /&gt;
    'cherry': 0,&lt;br /&gt;
    'date': 12&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
apple_count = fruits_in_bowl['apple'] # Equals 4&lt;br /&gt;
&lt;br /&gt;
fruits_in_bowl['pear'] = 9 # Sets 'pear' in the dictionary to 9.&lt;br /&gt;
&lt;br /&gt;
for fruit, num in fruits_in_bowl.items():&lt;br /&gt;
    print(f&amp;quot;There are {num} {fruit}(s) in the bowl.&amp;quot; % (num, fruit))&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If you only want the keys from a dictionary, you can just iterate over it directly, like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
for fruit in fruits_in_bowl:&lt;br /&gt;
    print(fruit)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If you want only the values but not the keys from a dictionary, use &amp;lt;code&amp;gt;my_dictionary.values()&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
==== Sets ==== &lt;br /&gt;
A &amp;lt;code&amp;gt;set&amp;lt;/code&amp;gt; is an unordered collection of unique items, with constant-time membership checking. &lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = {'Apple', 'Apple', 'Apple', 'Pear'} # The set removes duplicates, so it will only contain {'Apple', 'Pear'}&lt;br /&gt;
fruits = set(['Apple', 'Apple', 'Apple', 'Pear']) # This line transforms a list into a set&lt;br /&gt;
print('Apple' in fruits) # Constant-time!&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Loops ===&lt;br /&gt;
&lt;br /&gt;
In Python, while loops are written like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
i = 0&lt;br /&gt;
while i &amp;lt; 10:&lt;br /&gt;
    i += 1&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
For loops are written like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish']&lt;br /&gt;
&lt;br /&gt;
for pet in pets:&lt;br /&gt;
    print(pet)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
To iterate over a range of numbers, you can use the convenient &amp;lt;code&amp;gt;range&amp;lt;/code&amp;gt; function, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
for i in range(20, 30): # If you omit the first argument to range, it's assumed to be zero.&lt;br /&gt;
    print(i)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Note that &amp;lt;code&amp;gt;range&amp;lt;/code&amp;gt; provides a closed-open range. That is to say, it is inclusive of its lower bound and exclusive of its upper bound. To be very explicit about it:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
list(range(3, 6)) == [3, 4, 5]&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Unlike in other languages you may know, the following is not good practice in Python:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish']&lt;br /&gt;
&lt;br /&gt;
# BAD PRACTICE. DO NOT USE.&lt;br /&gt;
for i in range(len(pets)):&lt;br /&gt;
    pet = pets[i]&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Instead, if you need to access both a variable and its index, use the &amp;lt;code&amp;gt;enumerate&amp;lt;/code&amp;gt; function, which allows you to iterate through a group of items, along with their indexes, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish']&lt;br /&gt;
&lt;br /&gt;
for index, pet in enumerate(pets):&lt;br /&gt;
    print(f&amp;quot;{pet} at index {index}&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Generator Expressions and Comprehensions ===&lt;br /&gt;
&lt;br /&gt;
A generator is a special kind of object that, basically, represents a collection of items using a value and a function for generating the next value in the collection. In other words, it's a way of creating something that behaves like a list, but which only generates one value at a time, and discards a value when it's done with it. Say, for example, you wanted to do an operation on 10,000,000,000,000 numbers. You could put them all in a list, then iterate over the list, but that would take a lot of memory, plus you'd have to create and fill the entire list before beginning to actually work on your problem. Instead, you'd probably be better off using a generator; telling the computer, essentially: “The starting value is 0. When I ask for the next number in the collection, add 1 to current value and give me that.”&lt;br /&gt;
&lt;br /&gt;
A generator expression is an expression that is evaluated to create a generator. They're super useful. Generator expressions can take two forms – they can be used with and without a condition:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
(EXPRESSION for VARIABLE in ITERABLE) # Unconditional&lt;br /&gt;
(EXPRESSION for VARIABLE in ITERABLE if CONDITION) # Conditional&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
For our purposes, you can think of an iterable as anything you can do a for loop over. Let's take a look at a generator expression in use:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
double_even_digits = (number * 2 for number in range(10) if number % 2 == 0)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
That line says that &amp;lt;code&amp;gt;double_even_digits&amp;lt;/code&amp;gt; is every even number between 0 and 10 multiplied by two. Simple enough, right? If we wanted to use all of the numbers, not just the even ones, we could simply remove the if statement at the end of the expression.&lt;br /&gt;
&lt;br /&gt;
Here's the thing, though: if you were to print &amp;lt;code&amp;gt;double_even_digits&amp;lt;/code&amp;gt;, instead of a nice bunch of numbers, you'd get something that looks like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&amp;lt;generator object &amp;lt;genexpr&amp;gt;&amp;lt;code&amp;gt;at 0x107fc92b0&amp;gt;&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
That's because generators are lazy! They don't generate their values until those values are needed, and they discard values once they're no longer needed. As a result, '''you can only iterate over a generator once'''. In this case, you can't print out the whole generator, because it hasn't generated all the values yet. You can, however, iterate over the generator, and print its values one at a time, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
for number in double_even_digits:&lt;br /&gt;
    print(number)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
You can also make a list out of the generator, which will go through all the items in the generator and put them in a list, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
even_number_list = list(double_even_digits)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
That's actually a great segue to the second topic of this section: comprehensions. A comprehension is just a prettier way to make lists, sets, and dicts out of a generator expressions.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
# If you want a list:&lt;br /&gt;
list(i for i in range(10) if i % 2 == 0) # Don't do this&lt;br /&gt;
[i for i in range(10) if i % 2 == 0] # Use a list comprehension instead!&lt;br /&gt;
&lt;br /&gt;
# If you want a set:&lt;br /&gt;
set(i for i in range(10) if i % 2 == 0) # Don't do this&lt;br /&gt;
{i for i in range(10) if i % 2 == 0} # Use a set comprehension instead!&lt;br /&gt;
&lt;br /&gt;
# If you want a dict:&lt;br /&gt;
dict((i, i + 1) for i in range(10) if i % 2 == 0) # Don't do this&lt;br /&gt;
{i : i + 1 for i in range(10) if i % 2 == 0} # Use a dict comprehension instead!&lt;br /&gt;
&lt;br /&gt;
# If you want a tuple:&lt;br /&gt;
tuple(i for i in range(10) if i % 2 == 0) # Unfortunately, there's no better way to do this&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
In general, generators and comprehensions should be used whenever possible - they're the fastest and easiest way to build collections. If you ever see yourself writing code like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
# BAD PRACTICE! DO NOT USE!&lt;br /&gt;
digits = []&lt;br /&gt;
for digit in range(10):&lt;br /&gt;
    digits.append(digit)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Don't do it! Instead, use a generator expression or comprehension, as appropriate. A good way to decide whether a generator expression or comprehension is better for this situation is that, if you're just going to be iterating over your collection once, you should use an generator expression. If not, use a comprehension.&lt;br /&gt;
&lt;br /&gt;
=== Sorting ===&lt;br /&gt;
&lt;br /&gt;
Sorting in Python is frequently performed using the &amp;lt;code&amp;gt;sorted&amp;lt;/code&amp;gt; function, which takes two arguments: an iterable (anything you can do a for-loop over, including lists and tuples) and a function used to evaluate each item. If the function is omitted, Python will try to sort the lists by value.&lt;br /&gt;
&lt;br /&gt;
The following example demonstrates using an inline function, which Python calls a ''lambda''.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = ['apple', 'banana', 'cherry', 'date']&lt;br /&gt;
&lt;br /&gt;
# sort the fruits by string length&lt;br /&gt;
new_fruits = sorted(fruits, key=lambda v: len(v) // 2)&lt;br /&gt;
&lt;br /&gt;
print(new_fruits) # ['date', 'apple', 'banana', 'cherry']&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Alternatively, you can sort a &amp;lt;code&amp;gt;list&amp;lt;/code&amp;gt; using the &amp;lt;code&amp;gt;.sort&amp;lt;/code&amp;gt; method. This is faster than calling &amp;lt;code&amp;gt;sorted&amp;lt;/code&amp;gt;, but it modifies the list in-place and returns &amp;lt;code&amp;gt;None&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = ['apple', 'banana', 'cherry', 'date']&lt;br /&gt;
fruits.sort()&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
=== Import ===&lt;br /&gt;
&lt;br /&gt;
If you want to use functions from other libraries (including ones that you install using pip), use &amp;lt;code&amp;gt;import&amp;lt;/code&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
import time&lt;br /&gt;
&lt;br /&gt;
current_time = time.localtime()&lt;br /&gt;
print(time.strftime('%a, %d %b %Y %H:%M:%S', current_time))&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If you want to pull the functions out of their namespace, you can use &amp;lt;code&amp;gt;from ___ import ___&amp;lt;/code&amp;gt; syntax:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
from time import localtime, strftime&lt;br /&gt;
&lt;br /&gt;
current_time = localtime()&lt;br /&gt;
print(strftime('%a, %d %b %Y %H:%M:%S', current_time))&lt;br /&gt;
&lt;br /&gt;
# Be aware that this technique, although convenient, may cause unexpected behavior if the function names that you're pulling out of the namespace are already used for other purposes in Python.&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
=== File I/O ===&lt;br /&gt;
&lt;br /&gt;
You can read an entire file into a variable like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
f = open(&amp;quot;example.txt&amp;quot;)&lt;br /&gt;
file_contents = f.read()&lt;br /&gt;
&lt;br /&gt;
f.close() # free up memory when we're finished with the file&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
A better option is to use a with-block, which handles opening and closing the file for you automatically:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
with open(&amp;quot;example.txt&amp;quot;) as f:&lt;br /&gt;
    file_contents = f.read()&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
You can read a file line-by-line like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
with open(&amp;quot;example.txt&amp;quot;) as f:&lt;br /&gt;
    for line in f:&lt;br /&gt;
        print(&amp;quot;Read line: %s&amp;quot; % line.rstrip())&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
You can write to a file like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
with open(&amp;quot;example.txt&amp;quot;, &amp;quot;w&amp;quot;) as f:&lt;br /&gt;
    f.write(&amp;quot;Hello\nWorld\n&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
=== Command-Line Arguments ===&lt;br /&gt;
&lt;br /&gt;
Command line arguments are accessible in the variable &amp;lt;code&amp;gt;sys.argv&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
The following example shows a program that expects a filename as its argument, and it prints a usage message if the argument is not present ([https://stackoverflow.com/questions/983201/python-and-sys-argv source]).&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
import sys, os&lt;br /&gt;
&lt;br /&gt;
if len(sys.argv) &amp;lt; 2:&lt;br /&gt;
    sys.exit(f&amp;quot;Usage: {sys.argv[0]} filename&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
filename = sys.argv[1]&lt;br /&gt;
&lt;br /&gt;
if not os.path.exists(filename):&lt;br /&gt;
    sys.exit(f&amp;quot;Error: File '{sys.argv[1]}' not found&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Object-Oriented Programming ===&lt;br /&gt;
&lt;br /&gt;
You can define and use a class like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
class Food:&lt;br /&gt;
    # constructor:&lt;br /&gt;
    def __init__(self, name):&lt;br /&gt;
        self.name = name&lt;br /&gt;
    &lt;br /&gt;
    def format_name(self):&lt;br /&gt;
        return f&amp;quot;Gotta love to eat {self.name}&amp;quot;&lt;br /&gt;
&lt;br /&gt;
class Fruit(Food):&lt;br /&gt;
    def format_name(self):&lt;br /&gt;
        return f&amp;quot;{Food.format_name(self)} (fruit)&amp;quot;&lt;br /&gt;
&lt;br /&gt;
fruit = Fruit(&amp;quot;Cherry&amp;quot;)&lt;br /&gt;
print(fruit.format_name())&lt;br /&gt;
print(Food.get_definition())&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
This is the same example as in [[PHP#Object-Oriented_Programming|the PHP guide]].&lt;br /&gt;
&lt;br /&gt;
Some things to notice:&lt;br /&gt;
&lt;br /&gt;
* Instance methods ''always'' take &amp;lt;code&amp;gt;self&amp;lt;/code&amp;gt; as their first argument, followed by any number of additional parameters. This can be misleading for programmers familiar with other languages, because the number of arguments you feed to the method is actually ''one less than'' the number of declared parameters. Whenever you call a method on a class instance, that instance is implicitly fed into the explicitly-declared &amp;lt;code&amp;gt;self&amp;lt;/code&amp;gt; parameter of the method.&lt;br /&gt;
*: Note that the &amp;lt;code&amp;gt;self&amp;lt;/code&amp;gt; variable has the same purpose as the &amp;lt;code&amp;gt;this&amp;lt;/code&amp;gt; variable in languages like PHP, Java, JavaScript, and C++.&lt;br /&gt;
*There is no need for a &amp;lt;code&amp;gt;new&amp;lt;/code&amp;gt; keyword in Python.&lt;br /&gt;
&lt;br /&gt;
= Footnotes =&lt;br /&gt;
# {{note|interpreted}}This is an oversimplification. If you're interested, here's a quick explanation of how: In CPython (the reference implementation of Python) programs are compiled to bytecode, an intermediate representation, which is then interpreted.&lt;br /&gt;
[[Category:Module 4]]&lt;/div&gt;</summary>
		<author><name>Alex</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Python&amp;diff=2522</id>
		<title>Python</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Python&amp;diff=2522"/>
		<updated>2018-02-19T18:12:13Z</updated>

		<summary type="html">&lt;p&gt;Alex: /* Installation */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Languages like Java and C++ have lots of rules regarding variable types, syntax, return values, and so on. These can be cumbersome when you are trying to write short, quick scripts to perform tasks. This is where a ''scripting language'' comes into play.&lt;br /&gt;
&lt;br /&gt;
'''Python''' is a language well-suited to rapid prototype development. It is generally an ''interpreted language'', which means that, generally speaking, a Python program is converted line by line into instructions for the computer to execute as the program runs, instead of having a separate compilation step beforehand {{ref|interpreted}}. The syntax is clean, and it is usually clear at first glance what is going on when you write in Python.&lt;br /&gt;
&lt;br /&gt;
= Installation =&lt;br /&gt;
&lt;br /&gt;
Python may already be installed on your system. To see whether or not it is, enter the command&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ python3 --version&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If it tells you a version of Python '''greater than or equal to 3.6''' then you're good to go. If not, you need to do a quick package install to get it up and running. Using yum, it's just &amp;lt;code&amp;gt;sudo yum install python36&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
If you'd like to be able to just type &amp;lt;code&amp;gt;python&amp;lt;/code&amp;gt; instead of &amp;lt;code&amp;gt;python3&amp;lt;/code&amp;gt;, you can add the following line to the &amp;lt;code&amp;gt;~/.bash_profile&amp;lt;/code&amp;gt; file on your instance:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
alias python=&amp;quot;/usr/bin/python3&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Python 2 vs Python 3 ====&lt;br /&gt;
&lt;br /&gt;
In 2008, a new version of Python – Python 3 – was released, with a number of changes that made it incompatible with the previous version, Python 2. For several years, the Python community was slow to make the change to Python 3, but today, Python 3 is ''the'' standard for new code. The ''only'' reason to write Python 2 code today is because you have to work in an environment or with libraries that do not support Python 3, and that situation is becoming increasingly rare.&lt;br /&gt;
&lt;br /&gt;
'''For CSE 330 (and this guide), you ''must'' use Python 3.6 or greater.'''&lt;br /&gt;
&lt;br /&gt;
=== Pip ===&lt;br /&gt;
&lt;br /&gt;
Linux distributions have package managers like ''Apt'', ''Yum'', and ''YaST''. PHP has a package manager named ''PEAR''. It's now time to introduce Python's leading package manager: '''pip'''.&lt;br /&gt;
&lt;br /&gt;
You need to install Pip from Yum before you can use it. The package is called &amp;lt;code&amp;gt;python36-pip&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Once you have pip installed, you can use it to install Python packages. Use the &amp;lt;code&amp;gt;pip-python&amp;lt;/code&amp;gt; command:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ pip-python install package_name # RHEL&lt;br /&gt;
$ pip install package_name # Debian&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Running Python =&lt;br /&gt;
&lt;br /&gt;
There are two common ways to run Python code: via the console, and via a Python script file.&lt;br /&gt;
&lt;br /&gt;
=== The Python Console ===&lt;br /&gt;
&lt;br /&gt;
The Python console enables you to experiment with code without opening a text editor. To enter the Python console, simply type the ''python'' command at the terminal:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ python&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
To leave the interactive console, either type &amp;lt;code&amp;gt;quit()&amp;lt;/code&amp;gt; or press &amp;lt;code&amp;gt;Ctrl-D&amp;lt;/code&amp;gt; (on both Mac and Windows).&lt;br /&gt;
&lt;br /&gt;
=== Python Script Files ===&lt;br /&gt;
&lt;br /&gt;
You can also save Python script files for later use. The extension for Python scripts is &amp;lt;code&amp;gt;*.py&amp;lt;/code&amp;gt;. To run a script file, simply feed its path as an argument to the &amp;lt;code&amp;gt;python&amp;lt;/code&amp;gt; command in Terminal:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ python my_script.py&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Python Syntax and Language Components =&lt;br /&gt;
&lt;br /&gt;
This section contains a very brief overview of Python syntax. For a more comprehensive introduction, see [http://docs.python.org/tutorial/ the Python docs].&lt;br /&gt;
&lt;br /&gt;
=== Python's Type System ===&lt;br /&gt;
&lt;br /&gt;
Python is a dynamically-typed, strongly-typed, and duck-typed language. What does that mean? Well, let's take those categories one by one:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;ol&amp;gt;&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
'''Dynamic typing''', in contrast to ''static typing'' means that the types of objects can be changed. In Java, for instance, if you tried to write the following code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
int c = 2;&lt;br /&gt;
c = &amp;quot;fish&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Your code would fail to compile, because the Java compiler wouldn't allow you to change the type of the variable &amp;lt;code&amp;gt;c&amp;lt;/code&amp;gt; from &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt; to &amp;lt;code&amp;gt;String&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Python, however, is just fine with that. You can write:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
c = 2&lt;br /&gt;
c = &amp;quot;fish&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
And Python will happily do what you ask.&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
'''Strong typing''', in contrast to ''weak typing'', means, roughly, that a language won't implicitly convert types for you. So far, you've used a lot of PHP, which is very weakly typed. For example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;php&amp;quot;&amp;gt;&lt;br /&gt;
echo &amp;quot;10&amp;quot; . 2;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In PHP, this works just fine. The PHP interpreter sees that &amp;lt;code&amp;gt;2&amp;lt;/code&amp;gt; is an int, and silently converts it to a string for you, so that &amp;lt;code&amp;gt;&amp;quot;10&amp;quot;. 2&amp;lt;/code&amp;gt; equals &amp;lt;code&amp;gt;&amp;quot;102&amp;quot;&amp;lt;/code&amp;gt;. The problem with weak typing is that it can make it unclear to the programmer why things are happening the way they are. For instance, in PHP, the expression &amp;lt;code&amp;gt;&amp;quot;10&amp;quot; == 10&amp;lt;/code&amp;gt; is true, which can be less than obvious. Python, however, tries to disallow that sort of thing:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
&amp;quot;10&amp;quot; + &amp;quot;10&amp;quot; # Allowed – concatenates the two strings.&lt;br /&gt;
10   +  10  # Allowed – adds the two ints.&lt;br /&gt;
&amp;quot;10&amp;quot; +  10  # Not allowed – raises a TypeError&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Perhaps the one exception to this rule is the relationship between numeric types; it's perfectly fine to add a float to an int, for example.&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
'''Duck-typing''' is a little bit different than the other categories, because it doesn't really have a direct opposite. Essentially, duck-typing is the philosophy that &amp;quot;If it walks like a duck, and quacks like a duck, it's a duck.&amp;quot; In programming terms, that means that we often don't care what type an object is, as long as it can do the things we ask.&lt;br /&gt;
&lt;br /&gt;
Let's look at an example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
# This function doubles the value it's passed.&lt;br /&gt;
def double(thing):&lt;br /&gt;
    return thing + thing&lt;br /&gt;
double(10) # Returns 20&lt;br /&gt;
double(&amp;quot;fish&amp;quot;) # Returns &amp;quot;fishfish&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If this were Java, we'd have to write two different methods here: one for things of type &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt;, and one for things of type &amp;lt;code&amp;gt;String&amp;lt;/code&amp;gt;. Since this is Python, though, we don't have to do that. Instead, Python lets us say, essentially: &amp;quot;This function uses the &amp;lt;code&amp;gt;+&amp;lt;/code&amp;gt; operator, so you can pass whatever object you want to the function, as long as the function supports the &amp;lt;code&amp;gt;+&amp;lt;/code&amp;gt; operator&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
To quote [https://groups.google.com/forum/?hl=en#!msg/comp.lang.python/CCs2oJdyuzc/NYjla5HKMOIJ Alex Martelli], one of the key people in the Python project,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;blockquote&amp;gt;&lt;br /&gt;
&amp;quot;[Don't] check whether it IS-a duck: check whether it QUACKS-like-a duck, WALKS-like-a duck, etc, etc, depending on exactly what subset of duck-like behaviour you need.&amp;quot;&lt;br /&gt;
&amp;lt;/blockquote&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&amp;lt;/ol&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Basic Types ===&lt;br /&gt;
&lt;br /&gt;
In Python, the basic scalar types are:&lt;br /&gt;
&lt;br /&gt;
# &amp;lt;code&amp;gt;str&amp;lt;/code&amp;gt; – a string.&lt;br /&gt;
# &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt; – an integer object with unlimited digits.&lt;br /&gt;
# &amp;lt;code&amp;gt;bool&amp;lt;/code&amp;gt; – a Boolean value.&lt;br /&gt;
# &amp;lt;code&amp;gt;float&amp;lt;/code&amp;gt; – a floating point number; generally equivalent to &amp;lt;code&amp;gt;double&amp;lt;/code&amp;gt; in Java.&lt;br /&gt;
# &amp;lt;code&amp;gt;bytes&amp;lt;/code&amp;gt; – represents a collection of bytes; you're unlikely to use this often.&lt;br /&gt;
&lt;br /&gt;
Casting is done in the C style - to parse an &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt; from a string, for instance, you'd write &amp;lt;code&amp;gt;int(&amp;quot;123&amp;quot;)&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== Basic Control Flow ===&lt;br /&gt;
In Python, blocks of code are delineated using colons and indentation instead of curly braces. '''''That means that proper indentation is mandatory.''''' Every time you use a colon, you must indent one step further, and every time a block ends, you must unindent a step.&lt;br /&gt;
&lt;br /&gt;
Conditional statements are done using the &amp;lt;code&amp;gt;if&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;elif&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;else&amp;lt;/code&amp;gt; operators, like in the example below - pay attention to the indentation:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
cookies_left = 10&lt;br /&gt;
cake_slices_left = 3&lt;br /&gt;
if cookies_left &amp;gt; 10:&lt;br /&gt;
    print(&amp;quot;Lots of cookies!&amp;quot;)&lt;br /&gt;
elif cookies_left &amp;gt; 8:&lt;br /&gt;
    print(&amp;quot;Plenty left!&amp;quot;)&lt;br /&gt;
elif cookies_left == 5:&lt;br /&gt;
    print(&amp;quot;Halfway done!&amp;quot;)&lt;br /&gt;
else:&lt;br /&gt;
    if cake_slices_left == 3:&lt;br /&gt;
        print(&amp;quot;Lots of cake!&amp;quot;)&lt;br /&gt;
    elif cake_slices_left == 2:&lt;br /&gt;
        print(&amp;quot;One slice gone!&amp;quot;)&lt;br /&gt;
    else:&lt;br /&gt;
        print(&amp;quot;Little to no cake left!&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== An Example Python Script ===&lt;br /&gt;
&lt;br /&gt;
In my mind, there's no better way to learn Python than to be immersed in a simple example script.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
print(&amp;quot;Hello World&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
fruits = [&amp;quot;apple&amp;quot;, &amp;quot;banana&amp;quot;, &amp;quot;cherry&amp;quot;, &amp;quot;date&amp;quot;]&lt;br /&gt;
for fruit in fruits:&lt;br /&gt;
    print(f&amp;quot;I always love to eat a fresh {fruit}&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Map the fruits list over to a new list containing the length of the fruit strings:&lt;br /&gt;
fruit_size = [len(fruit) for fruit in fruits]&lt;br /&gt;
&lt;br /&gt;
avg_fruit_size = sum(fruit_size) / len(fruit_size)&lt;br /&gt;
print(f&amp;quot;The average fruit string length is {avg_fruit_size:.2f}.&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Some things to notice:&lt;br /&gt;
&lt;br /&gt;
* Printing is achieved using the &amp;lt;code&amp;gt;print()&amp;lt;/code&amp;gt; function.&lt;br /&gt;
* Comments start with a pound symbol &amp;lt;code&amp;gt;#&amp;lt;/code&amp;gt;.&lt;br /&gt;
* We can transform/map a list to a new list in just one line!&lt;br /&gt;
&lt;br /&gt;
For some more examples, see [https://wiki.python.org/moin/SimplePrograms the Python wiki].&lt;br /&gt;
&lt;br /&gt;
=== A Few Gotchas ===&lt;br /&gt;
&lt;br /&gt;
Here are a few things you may not expect when starting out with Python:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;ol&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
Strings can be delimited using either single quotes (&amp;lt;code&amp;gt;'&amp;lt;/code&amp;gt;) or double quotes (&amp;lt;code&amp;gt;&amp;quot;&amp;lt;/code&amp;gt;), so &amp;lt;code&amp;gt;'Python'&amp;lt;/code&amp;gt; is the same as &amp;lt;code&amp;gt;&amp;quot;Python&amp;quot;&amp;lt;/code. You can also use three sets of quotes (&amp;lt;code&amp;gt;'''&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;&amp;quot;&amp;quot;&amp;quot;&amp;lt;/code&amp;gt;) to delineate a multiple-line string, like so:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
long_string = &amp;quot;&amp;quot;&amp;quot;This&lt;br /&gt;
is my&lt;br /&gt;
very long&lt;br /&gt;
multiple-line&lt;br /&gt;
string&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
To compare the equality of two objects, use the &amp;lt;code&amp;gt;==&amp;lt;/code&amp;gt; operator. To compare the identity of two objects (i.e. whether or not they are literally the same object, at the same place in memory), use the &amp;lt;code&amp;gt;is&amp;lt;/code&amp;gt; operator. These correspond, respectively to &amp;lt;code&amp;gt;.equals()&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;==&amp;lt;/code&amp;gt; in Java.&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
The &amp;lt;code&amp;gt;/&amp;lt;/code&amp;gt; operator performs floating-point division, not integer division, even when both its arguments are integers. If you want to do integer division, use the &amp;lt;code&amp;gt;//&amp;lt;/code&amp;gt; operator. Let's look at an example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
9   / 10    == 0.9 # Floating-point division&lt;br /&gt;
9.0 / 10.0  == 0.9 # Floating-point division&lt;br /&gt;
9   // 10   == 0   # Integer division&lt;br /&gt;
9.0 // 10.0 == 0.0 # Integer division, even though the resulting value is a float&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
As discussed in the section [[#Python's_Type_System|Python's Type System]], you can't combine strings and numbers using the &amp;lt;code&amp;gt;+&amp;lt;/code&amp;gt; operator. Instead, you'll have to use one of the following methods of string formatting:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
  &lt;br /&gt;
# Technique 1 – printf-style Formatting&lt;br /&gt;
# This is a classic style of string formatting, used in many programming languages, including in Java's String.format.&lt;br /&gt;
&amp;quot;You scored %d out of %d!&amp;quot; % (score, questions)&lt;br /&gt;
&lt;br /&gt;
# Technique 2 – str.format&lt;br /&gt;
&amp;quot;You scored {} out of {}!&amp;quot;.format(score, questions)&lt;br /&gt;
&lt;br /&gt;
# Technique 3 – f-strings&lt;br /&gt;
# These were only introduced in Python 3.6 but they're very convenient.&lt;br /&gt;
f&amp;quot;You scored {score} out of {questions}!&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# Technique 4 - String Concatenation&lt;br /&gt;
# This is fine for small things, but for more complicated stuff, use one of the other techniques.&lt;br /&gt;
&amp;quot;You scored &amp;quot; + str(score) + &amp;quot; out of &amp;quot; + str(questions) + &amp;quot;!&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&amp;lt;/ol&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Functions ===&lt;br /&gt;
&lt;br /&gt;
Define functions using the &amp;lt;code&amp;gt;def&amp;lt;/code&amp;gt; keyword:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def hello(name):&lt;br /&gt;
    print(f&amp;quot;Hello, {name}!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Invoke functions using parentheses:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
hello(&amp;quot;Batman&amp;quot;)&lt;br /&gt;
hello(&amp;quot;Superman&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Functions can have optional arguments; however, these must come after any required arguments:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def hello(name=&amp;quot;User&amp;quot;):&lt;br /&gt;
    print(f&amp;quot;Hello, {name}!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
hello() # Prints &amp;quot;Hello, User!&amp;quot;&lt;br /&gt;
hello(&amp;quot;Sarah&amp;quot;) # Prints &amp;quot;Hello, Sarah!&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Functions are just regular objects in Python, meaning you can do stuff like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def hello(name=&amp;quot;User&amp;quot;):&lt;br /&gt;
    print(f&amp;quot;Hello, {name}!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
greeting = hello&lt;br /&gt;
&lt;br /&gt;
greeting(&amp;quot;Siwei&amp;quot;) # Prints &amp;quot;Hello, Siwei!&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Collection Types ===&lt;br /&gt;
Python has a few basic, built-in collection types. They each have their own special use cases, but they share a lot of similarities. All built-in data structures in Python are zero-indexed, for instance.&lt;br /&gt;
&lt;br /&gt;
To obtain the number of elements in a collection, use the &amp;lt;code&amp;gt;len()&amp;lt;/code&amp;gt; function, like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish'] # This is a list; you'll learn about them below.&lt;br /&gt;
&lt;br /&gt;
len(pets) # Returns 3&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To check if a collection contains an item, use the &amp;lt;code&amp;gt;in&amp;lt;/code&amp;gt; operator:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish'] # This is a list; you'll learn about them below.&lt;br /&gt;
&lt;br /&gt;
'Dog' in pets # Returns True&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Helpfully, the Python Software Foundation maintains a page containing the asymptotic complexities of important operations on major Python data structures. It's available [https://wiki.python.org/moin/TimeComplexity here].&lt;br /&gt;
&lt;br /&gt;
==== Lists ====&lt;br /&gt;
&lt;br /&gt;
Unlike languages like Java and C, Python's array-like type doesn't have fixed length. Instead, a &amp;lt;code&amp;gt;list&amp;lt;/code&amp;gt; is a dynamic array (like Java's &amp;lt;code&amp;gt;ArrayList&amp;lt;/code&amp;gt;) of objects of any type. Here's an example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = [&amp;quot;Apple&amp;quot;, &amp;quot;Pear&amp;quot;, &amp;quot;Orange&amp;quot;] # Lists can be creating by placing their items between square brackets&lt;br /&gt;
&lt;br /&gt;
random_items = ['Apple', 12312, 2.0, [1, 2, 3]] # Lists can contain objects of different types - even other lists!&lt;br /&gt;
&lt;br /&gt;
pets.append('Turtle') # Adds 'Turtle' to the end of pets&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For the next few examples, we'll be using the following list:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish', 'Turtle', 'Lizard', 'Snake']&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access or assign elements of a list, use the &amp;lt;code&amp;gt;[]&amp;lt;/code&amp;gt; operator.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[0] # Returns 'Dog'&lt;br /&gt;
pets[1] = 'Cow' # Sets pets[1] to 'Cow'&lt;br /&gt;
pets[1] = 'Cat' # Sets pets[1] back to 'Cat' &lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You can also access or assign lists using negative indices, which will return elements starting from the end of the list:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[-1] # Returns 'Snake'&lt;br /&gt;
pets[-2] # Returns 'Lizard'&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You can also use 'slice notation' to obtain or assign subsets of lists:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[start:end] # Returns items from index start to index end - 1.&lt;br /&gt;
pets[start:]    # Returns items from index start to the end of the list, inclusive.&lt;br /&gt;
pets[:end]      # Returns items from the beginning of the list to index end - 1.&lt;br /&gt;
pets[:]         # Returns every item in the list&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
There's also a third, optional argument: &amp;lt;code&amp;gt;step&amp;lt;/code&amp;gt;, which lets you jump over values:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[start:end:step] # Returns items from index start to index end - 1, jumping step values at a time&lt;br /&gt;
&lt;br /&gt;
# Examples:&lt;br /&gt;
pets[1:5:2] # Returns items from index 1 to index 4, jumping 2 at a time, so ['Cat', 'Turtle']&lt;br /&gt;
pets[::3] # Returns all items in the list, jumping 3 at a time, so ['Dog', 'Turtle']&lt;br /&gt;
pets[::-1] # Returns all items in the list, jumping -1 at a time. This reverses the list, so ['Snake', 'Lizard', 'Turtle', 'Fish', 'Cat', 'Dog']&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Lists have all the performance characteristics you'd expect of a dynamic array - constant-time indexing, amortized constant-time appends, and so on.&lt;br /&gt;
&lt;br /&gt;
==== Tuples ====&lt;br /&gt;
&lt;br /&gt;
Python has a special data type called &amp;lt;code&amp;gt;tuple&amp;lt;/code&amp;gt;, which is exactly the same as a list except for the fact that it cannot be modified, so you can't append or replace items.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
cities = ('St. Louis', 'Los Angeles', 'Seattle') # Tuples are defined using parentheses.&lt;br /&gt;
numbers = 1, 2, 3 # You can also omit the parentheses if it's unambiguous&lt;br /&gt;
single_item_tuple = (1,) # To make a tuple with only one item, put a comma after it&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Tuples also enable you to have multiple return values from a function:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def compute_length(string):&lt;br /&gt;
    str_len = len(string)&lt;br /&gt;
    if str_len &amp;lt; 5:&lt;br /&gt;
        return str_len, &amp;quot;short&amp;quot;&lt;br /&gt;
    elif str_len &amp;lt; 40:&lt;br /&gt;
        return str_len, &amp;quot;medium&amp;quot;&lt;br /&gt;
    return str_len, &amp;quot;long&amp;quot;&lt;br /&gt;
&lt;br /&gt;
length, description = compute_length(&amp;quot;Four score and seven years ago&amp;quot;)&lt;br /&gt;
print(f&amp;quot;The {description} string is {length} characters long.&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
The above example also demonstrates Python's if...elif...else conditional structure.&lt;br /&gt;
&lt;br /&gt;
==== Dictionaries ====&lt;br /&gt;
&lt;br /&gt;
Python has another datatype called a '''dictionary''' (or &amp;lt;code&amp;gt;dict&amp;lt;/code&amp;gt;, for short), which are like ''Maps'' in Java, ''associative arrays'' in PHP, and ''object literals'' in JavaScript (coming up soon in Module 6). Essentially, they enable you to use any immutable object as the key in your data structure. &amp;lt;code&amp;gt;dict&amp;lt;/code&amp;gt; objects can be created using either the &amp;lt;code&amp;gt;dict&amp;lt;/code&amp;gt; function, or by placing items between curly braces, separating keys and values using colons:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits_in_bowl = {&lt;br /&gt;
    'apple': 4,&lt;br /&gt;
    'banana': 2,&lt;br /&gt;
    'cherry': 0,&lt;br /&gt;
    'date': 12&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
apple_count = fruits_in_bowl['apple'] # Equals 4&lt;br /&gt;
&lt;br /&gt;
fruits_in_bowl['pear'] = 9 # Sets 'pear' in the dictionary to 9.&lt;br /&gt;
&lt;br /&gt;
for fruit, num in fruits_in_bowl.items():&lt;br /&gt;
    print(f&amp;quot;There are {num} {fruit}(s) in the bowl.&amp;quot; % (num, fruit))&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If you only want the keys from a dictionary, you can just iterate over it directly, like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
for fruit in fruits_in_bowl:&lt;br /&gt;
    print(fruit)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If you want only the values but not the keys from a dictionary, use &amp;lt;code&amp;gt;my_dictionary.values()&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
==== Sets ==== &lt;br /&gt;
A &amp;lt;code&amp;gt;set&amp;lt;/code&amp;gt; is an unordered collection of unique items, with constant-time membership checking. &lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = {'Apple', 'Apple', 'Apple', 'Pear'} # The set removes duplicates, so it will only contain {'Apple', 'Pear'}&lt;br /&gt;
fruits = set(['Apple', 'Apple', 'Apple', 'Pear']) # This line transforms a list into a set&lt;br /&gt;
print('Apple' in fruits) # Constant-time!&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Loops ===&lt;br /&gt;
&lt;br /&gt;
In Python, while loops are written like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
i = 0&lt;br /&gt;
while i &amp;lt; 10:&lt;br /&gt;
    i += 1&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
For loops are written like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish']&lt;br /&gt;
&lt;br /&gt;
for pet in pets:&lt;br /&gt;
    print(pet)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
To iterate over a range of numbers, you can use the convenient &amp;lt;code&amp;gt;range&amp;lt;/code&amp;gt; function, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
for i in range(20, 30): # If you omit the first argument to range, it's assumed to be zero.&lt;br /&gt;
    print(i)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Note that &amp;lt;code&amp;gt;range&amp;lt;/code&amp;gt; provides a closed-open range. That is to say, it is inclusive of its lower bound and exclusive of its upper bound. To be very explicit about it:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
list(range(3, 6)) == [3, 4, 5]&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Unlike in other languages you may know, the following is not good practice in Python:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish']&lt;br /&gt;
&lt;br /&gt;
# BAD PRACTICE. DO NOT USE.&lt;br /&gt;
for i in range(len(pets)):&lt;br /&gt;
    pet = pets[i]&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Instead, if you need to access both a variable and its index, use the &amp;lt;code&amp;gt;enumerate&amp;lt;/code&amp;gt; function, which allows you to iterate through a group of items, along with their indexes, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish']&lt;br /&gt;
&lt;br /&gt;
for index, pet in enumerate(pets):&lt;br /&gt;
    print(f&amp;quot;{pet} at index {index}&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Generator Expressions and Comprehensions ===&lt;br /&gt;
&lt;br /&gt;
A generator is a special kind of object that, basically, represents a collection of items using a value and a function for generating the next value in the collection. In other words, it's a way of creating something that behaves like a list, but which only generates one value at a time, and discards a value when it's done with it. Say, for example, you wanted to do an operation on 10,000,000,000,000 numbers. You could put them all in a list, then iterate over the list, but that would take a lot of memory, plus you'd have to create and fill the entire list before beginning to actually work on your problem. Instead, you'd probably be better off using a generator; telling the computer, essentially: “The starting value is 0. When I ask for the next number in the collection, add 1 to current value and give me that.”&lt;br /&gt;
&lt;br /&gt;
A generator expression is an expression that is evaluated to create a generator. They're super useful. Generator expressions can take two forms – they can be used with and without a condition:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
(EXPRESSION for VARIABLE in ITERABLE) # Unconditional&lt;br /&gt;
(EXPRESSION for VARIABLE in ITERABLE if CONDITION) # Conditional&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
For our purposes, you can think of an iterable as anything you can do a for loop over. Let's take a look at a generator expression in use:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
double_even_digits = (number * 2 for number in range(10) if number % 2 == 0)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
That line says that &amp;lt;code&amp;gt;double_even_digits&amp;lt;/code&amp;gt; is every even number between 0 and 10 multiplied by two. Simple enough, right? If we wanted to use all of the numbers, not just the even ones, we could simply remove the if statement at the end of the expression.&lt;br /&gt;
&lt;br /&gt;
Here's the thing, though: if you were to print &amp;lt;code&amp;gt;double_even_digits&amp;lt;/code&amp;gt;, instead of a nice bunch of numbers, you'd get something that looks like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&amp;lt;generator object &amp;lt;genexpr&amp;gt;&amp;lt;code&amp;gt;at 0x107fc92b0&amp;gt;&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
That's because generators are lazy! They don't generate their values until those values are needed, and they discard values once they're no longer needed. As a result, '''you can only iterate over a generator once'''. In this case, you can't print out the whole generator, because it hasn't generated all the values yet. You can, however, iterate over the generator, and print its values one at a time, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
for number in double_even_digits:&lt;br /&gt;
    print(number)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
You can also make a list out of the generator, which will go through all the items in the generator and put them in a list, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
even_number_list = list(double_even_digits)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
That's actually a great segue to the second topic of this section: comprehensions. A comprehension is just a prettier way to make lists, sets, and dicts out of a generator expressions.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
# If you want a list:&lt;br /&gt;
list(i for i in range(10) if i % 2 == 0) # Don't do this&lt;br /&gt;
[i for i in range(10) if i % 2 == 0] # Use a list comprehension instead!&lt;br /&gt;
&lt;br /&gt;
# If you want a set:&lt;br /&gt;
set(i for i in range(10) if i % 2 == 0) # Don't do this&lt;br /&gt;
{i for i in range(10) if i % 2 == 0} # Use a set comprehension instead!&lt;br /&gt;
&lt;br /&gt;
# If you want a dict:&lt;br /&gt;
dict((i, i + 1) for i in range(10) if i % 2 == 0) # Don't do this&lt;br /&gt;
{i : i + 1 for i in range(10) if i % 2 == 0} # Use a dict comprehension instead!&lt;br /&gt;
&lt;br /&gt;
# If you want a tuple:&lt;br /&gt;
tuple(i for i in range(10) if i % 2 == 0) # Unfortunately, there's no better way to do this&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
In general, generators and comprehensions should be used whenever possible - they're the fastest and easiest way to build collections. If you ever see yourself writing code like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
# BAD PRACTICE! DO NOT USE!&lt;br /&gt;
digits = []&lt;br /&gt;
for digit in range(10):&lt;br /&gt;
    digits.append(digit)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Don't do it! Instead, use a generator expression or comprehension, as appropriate. A good way to decide whether a generator expression or comprehension is better for this situation is that, if you're just going to be iterating over your collection once, you should use an generator expression. If not, use a comprehension.&lt;br /&gt;
&lt;br /&gt;
=== Sorting ===&lt;br /&gt;
&lt;br /&gt;
Sorting in Python is frequently performed using the &amp;lt;code&amp;gt;sorted&amp;lt;/code&amp;gt; function, which takes two arguments: an iterable (anything you can do a for-loop over, including lists and tuples) and a function used to evaluate each item. If the function is omitted, Python will try to sort the lists by value.&lt;br /&gt;
&lt;br /&gt;
The following example demonstrates using an inline function, which Python calls a ''lambda''.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = ['apple', 'banana', 'cherry', 'date']&lt;br /&gt;
&lt;br /&gt;
# sort the fruits by string length&lt;br /&gt;
new_fruits = sorted(fruits, key=lambda v: len(v) // 2)&lt;br /&gt;
&lt;br /&gt;
print(new_fruits) # ['date', 'apple', 'banana', 'cherry']&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Alternatively, you can sort a &amp;lt;code&amp;gt;list&amp;lt;/code&amp;gt; using the &amp;lt;code&amp;gt;.sort&amp;lt;/code&amp;gt; method. This is faster than calling &amp;lt;code&amp;gt;sorted&amp;lt;/code&amp;gt;, but it modifies the list in-place and returns &amp;lt;code&amp;gt;None&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = ['apple', 'banana', 'cherry', 'date']&lt;br /&gt;
fruits.sort()&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
=== Import ===&lt;br /&gt;
&lt;br /&gt;
If you want to use functions from other libraries (including ones that you install using pip), use &amp;lt;code&amp;gt;import&amp;lt;/code&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
import time&lt;br /&gt;
&lt;br /&gt;
current_time = time.localtime()&lt;br /&gt;
print(time.strftime('%a, %d %b %Y %H:%M:%S', current_time))&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If you want to pull the functions out of their namespace, you can use &amp;lt;code&amp;gt;from ___ import ___&amp;lt;/code&amp;gt; syntax:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
from time import localtime, strftime&lt;br /&gt;
&lt;br /&gt;
current_time = localtime()&lt;br /&gt;
print(strftime('%a, %d %b %Y %H:%M:%S', current_time))&lt;br /&gt;
&lt;br /&gt;
# Be aware that this technique, although convenient, may cause unexpected behavior if the function names that you're pulling out of the namespace are already used for other purposes in Python.&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
=== File I/O ===&lt;br /&gt;
&lt;br /&gt;
You can read an entire file into a variable like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
f = open(&amp;quot;example.txt&amp;quot;)&lt;br /&gt;
file_contents = f.read()&lt;br /&gt;
&lt;br /&gt;
f.close() # free up memory when we're finished with the file&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
A better option is to use a with-block, which handles opening and closing the file for you automatically:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
with open(&amp;quot;example.txt&amp;quot;) as f:&lt;br /&gt;
    file_contents = f.read()&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
You can read a file line-by-line like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
with open(&amp;quot;example.txt&amp;quot;) as f:&lt;br /&gt;
    for line in f:&lt;br /&gt;
        print(&amp;quot;Read line: %s&amp;quot; % line.rstrip())&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
You can write to a file like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
with open(&amp;quot;example.txt&amp;quot;, &amp;quot;w&amp;quot;) as f:&lt;br /&gt;
    f.write(&amp;quot;Hello\nWorld\n&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
=== Command-Line Arguments ===&lt;br /&gt;
&lt;br /&gt;
Command line arguments are accessible in the variable &amp;lt;code&amp;gt;sys.argv&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
The following example shows a program that expects a filename as its argument, and it prints a usage message if the argument is not present ([https://stackoverflow.com/questions/983201/python-and-sys-argv source]).&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
import sys, os&lt;br /&gt;
&lt;br /&gt;
if len(sys.argv) &amp;lt; 2:&lt;br /&gt;
    sys.exit(f&amp;quot;Usage: {sys.argv[0]} filename&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
filename = sys.argv[1]&lt;br /&gt;
&lt;br /&gt;
if not os.path.exists(filename):&lt;br /&gt;
    sys.exit(f&amp;quot;Error: File '{sys.argv[1]}' not found&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Object-Oriented Programming ===&lt;br /&gt;
&lt;br /&gt;
You can define and use a class like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
class Food:&lt;br /&gt;
    # constructor:&lt;br /&gt;
    def __init__(self, name):&lt;br /&gt;
        self.name = name&lt;br /&gt;
    &lt;br /&gt;
    def format_name(self):&lt;br /&gt;
        return f&amp;quot;Gotta love to eat {self.name}&amp;quot;&lt;br /&gt;
&lt;br /&gt;
class Fruit(Food):&lt;br /&gt;
    def format_name(self):&lt;br /&gt;
        return f&amp;quot;{Food.format_name(self)} (fruit)&amp;quot;&lt;br /&gt;
&lt;br /&gt;
fruit = Fruit(&amp;quot;Cherry&amp;quot;)&lt;br /&gt;
print(fruit.format_name())&lt;br /&gt;
print(Food.get_definition())&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
This is the same example as in [[PHP#Object-Oriented_Programming|the PHP guide]].&lt;br /&gt;
&lt;br /&gt;
Some things to notice:&lt;br /&gt;
&lt;br /&gt;
* Instance methods ''always'' take &amp;lt;code&amp;gt;self&amp;lt;/code&amp;gt; as their first argument, followed by any number of additional parameters. This can be misleading for programmers familiar with other languages, because the number of arguments you feed to the method is actually ''one less than'' the number of declared parameters. Whenever you call a method on a class instance, that instance is implicitly fed into the explicitly-declared &amp;lt;code&amp;gt;self&amp;lt;/code&amp;gt; parameter of the method.&lt;br /&gt;
*: Note that the &amp;lt;code&amp;gt;self&amp;lt;/code&amp;gt; variable has the same purpose as the &amp;lt;code&amp;gt;this&amp;lt;/code&amp;gt; variable in languages like PHP, Java, JavaScript, and C++.&lt;br /&gt;
*There is no need for a &amp;lt;code&amp;gt;new&amp;lt;/code&amp;gt; keyword in Python.&lt;br /&gt;
&lt;br /&gt;
= Footnotes =&lt;br /&gt;
# {{note|interpreted}}This is an oversimplification. If you're interested, here's a quick explanation of how: In CPython (the reference implementation of Python) programs are compiled to bytecode, an intermediate representation, which is then interpreted.&lt;br /&gt;
[[Category:Module 4]]&lt;/div&gt;</summary>
		<author><name>Alex</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Python&amp;diff=2521</id>
		<title>Python</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Python&amp;diff=2521"/>
		<updated>2018-02-19T18:11:41Z</updated>

		<summary type="html">&lt;p&gt;Alex: /* Installation */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Languages like Java and C++ have lots of rules regarding variable types, syntax, return values, and so on. These can be cumbersome when you are trying to write short, quick scripts to perform tasks. This is where a ''scripting language'' comes into play.&lt;br /&gt;
&lt;br /&gt;
'''Python''' is a language well-suited to rapid prototype development. It is generally an ''interpreted language'', which means that, generally speaking, a Python program is converted line by line into instructions for the computer to execute as the program runs, instead of having a separate compilation step beforehand {{ref|interpreted}}. The syntax is clean, and it is usually clear at first glance what is going on when you write in Python.&lt;br /&gt;
&lt;br /&gt;
= Installation =&lt;br /&gt;
&lt;br /&gt;
Python may already be installed on your system. To see whether or not it is, enter the command&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ python3 --version&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If it tells you a version of Python '''greater than or equal to 3.6''' then you're good to go. If not, you need to do a quick package install to get it up and running. Using yum, it's just &amp;lt;code&amp;gt;sudo yum install python36&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
If you'd like to be able to just type &amp;lt;code&amp;gt;python&amp;lt;/code&amp;gt; instead of &amp;lt;code&amp;gt;python3&amp;lt;/code&amp;gt;, you can add the following line to the &amp;lt;code&amp;gt;~/.bash_profile&amp;lt;/code&amp;gt; file on your instance:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
alias python=&amp;quot;/usr/bin/python3&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Python 2 vs Python 3 ====&lt;br /&gt;
&lt;br /&gt;
In 2008, a new version of Python – Python 3 – was released, with a number changes that made it incompatible with the previous version, Python 2. For several years, the Python community was slow to make the change to Python 3, but today, Python 3 is ''the'' standard for new code. The ''only'' reason to write Python 2 code today is because you have to work in an environment or with libraries that do not support Python 3, and that situation is becoming increasingly rare.&lt;br /&gt;
&lt;br /&gt;
'''For CSE 330 (and this guide), you ''must'' use Python 3.6 or greater.'''&lt;br /&gt;
&lt;br /&gt;
=== Pip ===&lt;br /&gt;
&lt;br /&gt;
Linux distributions have package managers like ''Apt'', ''Yum'', and ''YaST''. PHP has a package manager named ''PEAR''. It's now time to introduce Python's leading package manager: '''pip'''.&lt;br /&gt;
&lt;br /&gt;
You need to install Pip from Yum before you can use it. The package is called &amp;lt;code&amp;gt;python-pip&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Once you have pip installed, you can use it to install Python packages. Use the &amp;lt;code&amp;gt;pip-python&amp;lt;/code&amp;gt; command:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ pip-python install package_name # RHEL&lt;br /&gt;
$ pip install package_name # Debian&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Running Python =&lt;br /&gt;
&lt;br /&gt;
There are two common ways to run Python code: via the console, and via a Python script file.&lt;br /&gt;
&lt;br /&gt;
=== The Python Console ===&lt;br /&gt;
&lt;br /&gt;
The Python console enables you to experiment with code without opening a text editor. To enter the Python console, simply type the ''python'' command at the terminal:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ python&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
To leave the interactive console, either type &amp;lt;code&amp;gt;quit()&amp;lt;/code&amp;gt; or press &amp;lt;code&amp;gt;Ctrl-D&amp;lt;/code&amp;gt; (on both Mac and Windows).&lt;br /&gt;
&lt;br /&gt;
=== Python Script Files ===&lt;br /&gt;
&lt;br /&gt;
You can also save Python script files for later use. The extension for Python scripts is &amp;lt;code&amp;gt;*.py&amp;lt;/code&amp;gt;. To run a script file, simply feed its path as an argument to the &amp;lt;code&amp;gt;python&amp;lt;/code&amp;gt; command in Terminal:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ python my_script.py&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Python Syntax and Language Components =&lt;br /&gt;
&lt;br /&gt;
This section contains a very brief overview of Python syntax. For a more comprehensive introduction, see [http://docs.python.org/tutorial/ the Python docs].&lt;br /&gt;
&lt;br /&gt;
=== Python's Type System ===&lt;br /&gt;
&lt;br /&gt;
Python is a dynamically-typed, strongly-typed, and duck-typed language. What does that mean? Well, let's take those categories one by one:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;ol&amp;gt;&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
'''Dynamic typing''', in contrast to ''static typing'' means that the types of objects can be changed. In Java, for instance, if you tried to write the following code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
int c = 2;&lt;br /&gt;
c = &amp;quot;fish&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Your code would fail to compile, because the Java compiler wouldn't allow you to change the type of the variable &amp;lt;code&amp;gt;c&amp;lt;/code&amp;gt; from &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt; to &amp;lt;code&amp;gt;String&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Python, however, is just fine with that. You can write:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
c = 2&lt;br /&gt;
c = &amp;quot;fish&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
And Python will happily do what you ask.&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
'''Strong typing''', in contrast to ''weak typing'', means, roughly, that a language won't implicitly convert types for you. So far, you've used a lot of PHP, which is very weakly typed. For example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;php&amp;quot;&amp;gt;&lt;br /&gt;
echo &amp;quot;10&amp;quot; . 2;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In PHP, this works just fine. The PHP interpreter sees that &amp;lt;code&amp;gt;2&amp;lt;/code&amp;gt; is an int, and silently converts it to a string for you, so that &amp;lt;code&amp;gt;&amp;quot;10&amp;quot;. 2&amp;lt;/code&amp;gt; equals &amp;lt;code&amp;gt;&amp;quot;102&amp;quot;&amp;lt;/code&amp;gt;. The problem with weak typing is that it can make it unclear to the programmer why things are happening the way they are. For instance, in PHP, the expression &amp;lt;code&amp;gt;&amp;quot;10&amp;quot; == 10&amp;lt;/code&amp;gt; is true, which can be less than obvious. Python, however, tries to disallow that sort of thing:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
&amp;quot;10&amp;quot; + &amp;quot;10&amp;quot; # Allowed – concatenates the two strings.&lt;br /&gt;
10   +  10  # Allowed – adds the two ints.&lt;br /&gt;
&amp;quot;10&amp;quot; +  10  # Not allowed – raises a TypeError&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Perhaps the one exception to this rule is the relationship between numeric types; it's perfectly fine to add a float to an int, for example.&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
'''Duck-typing''' is a little bit different than the other categories, because it doesn't really have a direct opposite. Essentially, duck-typing is the philosophy that &amp;quot;If it walks like a duck, and quacks like a duck, it's a duck.&amp;quot; In programming terms, that means that we often don't care what type an object is, as long as it can do the things we ask.&lt;br /&gt;
&lt;br /&gt;
Let's look at an example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
# This function doubles the value it's passed.&lt;br /&gt;
def double(thing):&lt;br /&gt;
    return thing + thing&lt;br /&gt;
double(10) # Returns 20&lt;br /&gt;
double(&amp;quot;fish&amp;quot;) # Returns &amp;quot;fishfish&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If this were Java, we'd have to write two different methods here: one for things of type &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt;, and one for things of type &amp;lt;code&amp;gt;String&amp;lt;/code&amp;gt;. Since this is Python, though, we don't have to do that. Instead, Python lets us say, essentially: &amp;quot;This function uses the &amp;lt;code&amp;gt;+&amp;lt;/code&amp;gt; operator, so you can pass whatever object you want to the function, as long as the function supports the &amp;lt;code&amp;gt;+&amp;lt;/code&amp;gt; operator&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
To quote [https://groups.google.com/forum/?hl=en#!msg/comp.lang.python/CCs2oJdyuzc/NYjla5HKMOIJ Alex Martelli], one of the key people in the Python project,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;blockquote&amp;gt;&lt;br /&gt;
&amp;quot;[Don't] check whether it IS-a duck: check whether it QUACKS-like-a duck, WALKS-like-a duck, etc, etc, depending on exactly what subset of duck-like behaviour you need.&amp;quot;&lt;br /&gt;
&amp;lt;/blockquote&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&amp;lt;/ol&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Basic Types ===&lt;br /&gt;
&lt;br /&gt;
In Python, the basic scalar types are:&lt;br /&gt;
&lt;br /&gt;
# &amp;lt;code&amp;gt;str&amp;lt;/code&amp;gt; – a string.&lt;br /&gt;
# &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt; – an integer object with unlimited digits.&lt;br /&gt;
# &amp;lt;code&amp;gt;bool&amp;lt;/code&amp;gt; – a Boolean value.&lt;br /&gt;
# &amp;lt;code&amp;gt;float&amp;lt;/code&amp;gt; – a floating point number; generally equivalent to &amp;lt;code&amp;gt;double&amp;lt;/code&amp;gt; in Java.&lt;br /&gt;
# &amp;lt;code&amp;gt;bytes&amp;lt;/code&amp;gt; – represents a collection of bytes; you're unlikely to use this often.&lt;br /&gt;
&lt;br /&gt;
Casting is done in the C style - to parse an &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt; from a string, for instance, you'd write &amp;lt;code&amp;gt;int(&amp;quot;123&amp;quot;)&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== Basic Control Flow ===&lt;br /&gt;
In Python, blocks of code are delineated using colons and indentation instead of curly braces. '''''That means that proper indentation is mandatory.''''' Every time you use a colon, you must indent one step further, and every time a block ends, you must unindent a step.&lt;br /&gt;
&lt;br /&gt;
Conditional statements are done using the &amp;lt;code&amp;gt;if&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;elif&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;else&amp;lt;/code&amp;gt; operators, like in the example below - pay attention to the indentation:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
cookies_left = 10&lt;br /&gt;
cake_slices_left = 3&lt;br /&gt;
if cookies_left &amp;gt; 10:&lt;br /&gt;
    print(&amp;quot;Lots of cookies!&amp;quot;)&lt;br /&gt;
elif cookies_left &amp;gt; 8:&lt;br /&gt;
    print(&amp;quot;Plenty left!&amp;quot;)&lt;br /&gt;
elif cookies_left == 5:&lt;br /&gt;
    print(&amp;quot;Halfway done!&amp;quot;)&lt;br /&gt;
else:&lt;br /&gt;
    if cake_slices_left == 3:&lt;br /&gt;
        print(&amp;quot;Lots of cake!&amp;quot;)&lt;br /&gt;
    elif cake_slices_left == 2:&lt;br /&gt;
        print(&amp;quot;One slice gone!&amp;quot;)&lt;br /&gt;
    else:&lt;br /&gt;
        print(&amp;quot;Little to no cake left!&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== An Example Python Script ===&lt;br /&gt;
&lt;br /&gt;
In my mind, there's no better way to learn Python than to be immersed in a simple example script.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
print(&amp;quot;Hello World&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
fruits = [&amp;quot;apple&amp;quot;, &amp;quot;banana&amp;quot;, &amp;quot;cherry&amp;quot;, &amp;quot;date&amp;quot;]&lt;br /&gt;
for fruit in fruits:&lt;br /&gt;
    print(f&amp;quot;I always love to eat a fresh {fruit}&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Map the fruits list over to a new list containing the length of the fruit strings:&lt;br /&gt;
fruit_size = [len(fruit) for fruit in fruits]&lt;br /&gt;
&lt;br /&gt;
avg_fruit_size = sum(fruit_size) / len(fruit_size)&lt;br /&gt;
print(f&amp;quot;The average fruit string length is {avg_fruit_size:.2f}.&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Some things to notice:&lt;br /&gt;
&lt;br /&gt;
* Printing is achieved using the &amp;lt;code&amp;gt;print()&amp;lt;/code&amp;gt; function.&lt;br /&gt;
* Comments start with a pound symbol &amp;lt;code&amp;gt;#&amp;lt;/code&amp;gt;.&lt;br /&gt;
* We can transform/map a list to a new list in just one line!&lt;br /&gt;
&lt;br /&gt;
For some more examples, see [https://wiki.python.org/moin/SimplePrograms the Python wiki].&lt;br /&gt;
&lt;br /&gt;
=== A Few Gotchas ===&lt;br /&gt;
&lt;br /&gt;
Here are a few things you may not expect when starting out with Python:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;ol&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
Strings can be delimited using either single quotes (&amp;lt;code&amp;gt;'&amp;lt;/code&amp;gt;) or double quotes (&amp;lt;code&amp;gt;&amp;quot;&amp;lt;/code&amp;gt;), so &amp;lt;code&amp;gt;'Python'&amp;lt;/code&amp;gt; is the same as &amp;lt;code&amp;gt;&amp;quot;Python&amp;quot;&amp;lt;/code. You can also use three sets of quotes (&amp;lt;code&amp;gt;'''&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;&amp;quot;&amp;quot;&amp;quot;&amp;lt;/code&amp;gt;) to delineate a multiple-line string, like so:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
long_string = &amp;quot;&amp;quot;&amp;quot;This&lt;br /&gt;
is my&lt;br /&gt;
very long&lt;br /&gt;
multiple-line&lt;br /&gt;
string&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
To compare the equality of two objects, use the &amp;lt;code&amp;gt;==&amp;lt;/code&amp;gt; operator. To compare the identity of two objects (i.e. whether or not they are literally the same object, at the same place in memory), use the &amp;lt;code&amp;gt;is&amp;lt;/code&amp;gt; operator. These correspond, respectively to &amp;lt;code&amp;gt;.equals()&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;==&amp;lt;/code&amp;gt; in Java.&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
The &amp;lt;code&amp;gt;/&amp;lt;/code&amp;gt; operator performs floating-point division, not integer division, even when both its arguments are integers. If you want to do integer division, use the &amp;lt;code&amp;gt;//&amp;lt;/code&amp;gt; operator. Let's look at an example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
9   / 10    == 0.9 # Floating-point division&lt;br /&gt;
9.0 / 10.0  == 0.9 # Floating-point division&lt;br /&gt;
9   // 10   == 0   # Integer division&lt;br /&gt;
9.0 // 10.0 == 0.0 # Integer division, even though the resulting value is a float&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
As discussed in the section [[#Python's_Type_System|Python's Type System]], you can't combine strings and numbers using the &amp;lt;code&amp;gt;+&amp;lt;/code&amp;gt; operator. Instead, you'll have to use one of the following methods of string formatting:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
  &lt;br /&gt;
# Technique 1 – printf-style Formatting&lt;br /&gt;
# This is a classic style of string formatting, used in many programming languages, including in Java's String.format.&lt;br /&gt;
&amp;quot;You scored %d out of %d!&amp;quot; % (score, questions)&lt;br /&gt;
&lt;br /&gt;
# Technique 2 – str.format&lt;br /&gt;
&amp;quot;You scored {} out of {}!&amp;quot;.format(score, questions)&lt;br /&gt;
&lt;br /&gt;
# Technique 3 – f-strings&lt;br /&gt;
# These were only introduced in Python 3.6 but they're very convenient.&lt;br /&gt;
f&amp;quot;You scored {score} out of {questions}!&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# Technique 4 - String Concatenation&lt;br /&gt;
# This is fine for small things, but for more complicated stuff, use one of the other techniques.&lt;br /&gt;
&amp;quot;You scored &amp;quot; + str(score) + &amp;quot; out of &amp;quot; + str(questions) + &amp;quot;!&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&amp;lt;/ol&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Functions ===&lt;br /&gt;
&lt;br /&gt;
Define functions using the &amp;lt;code&amp;gt;def&amp;lt;/code&amp;gt; keyword:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def hello(name):&lt;br /&gt;
    print(f&amp;quot;Hello, {name}!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Invoke functions using parentheses:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
hello(&amp;quot;Batman&amp;quot;)&lt;br /&gt;
hello(&amp;quot;Superman&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Functions can have optional arguments; however, these must come after any required arguments:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def hello(name=&amp;quot;User&amp;quot;):&lt;br /&gt;
    print(f&amp;quot;Hello, {name}!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
hello() # Prints &amp;quot;Hello, User!&amp;quot;&lt;br /&gt;
hello(&amp;quot;Sarah&amp;quot;) # Prints &amp;quot;Hello, Sarah!&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Functions are just regular objects in Python, meaning you can do stuff like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def hello(name=&amp;quot;User&amp;quot;):&lt;br /&gt;
    print(f&amp;quot;Hello, {name}!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
greeting = hello&lt;br /&gt;
&lt;br /&gt;
greeting(&amp;quot;Siwei&amp;quot;) # Prints &amp;quot;Hello, Siwei!&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Collection Types ===&lt;br /&gt;
Python has a few basic, built-in collection types. They each have their own special use cases, but they share a lot of similarities. All built-in data structures in Python are zero-indexed, for instance.&lt;br /&gt;
&lt;br /&gt;
To obtain the number of elements in a collection, use the &amp;lt;code&amp;gt;len()&amp;lt;/code&amp;gt; function, like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish'] # This is a list; you'll learn about them below.&lt;br /&gt;
&lt;br /&gt;
len(pets) # Returns 3&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To check if a collection contains an item, use the &amp;lt;code&amp;gt;in&amp;lt;/code&amp;gt; operator:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish'] # This is a list; you'll learn about them below.&lt;br /&gt;
&lt;br /&gt;
'Dog' in pets # Returns True&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Helpfully, the Python Software Foundation maintains a page containing the asymptotic complexities of important operations on major Python data structures. It's available [https://wiki.python.org/moin/TimeComplexity here].&lt;br /&gt;
&lt;br /&gt;
==== Lists ====&lt;br /&gt;
&lt;br /&gt;
Unlike languages like Java and C, Python's array-like type doesn't have fixed length. Instead, a &amp;lt;code&amp;gt;list&amp;lt;/code&amp;gt; is a dynamic array (like Java's &amp;lt;code&amp;gt;ArrayList&amp;lt;/code&amp;gt;) of objects of any type. Here's an example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = [&amp;quot;Apple&amp;quot;, &amp;quot;Pear&amp;quot;, &amp;quot;Orange&amp;quot;] # Lists can be creating by placing their items between square brackets&lt;br /&gt;
&lt;br /&gt;
random_items = ['Apple', 12312, 2.0, [1, 2, 3]] # Lists can contain objects of different types - even other lists!&lt;br /&gt;
&lt;br /&gt;
pets.append('Turtle') # Adds 'Turtle' to the end of pets&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For the next few examples, we'll be using the following list:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish', 'Turtle', 'Lizard', 'Snake']&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access or assign elements of a list, use the &amp;lt;code&amp;gt;[]&amp;lt;/code&amp;gt; operator.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[0] # Returns 'Dog'&lt;br /&gt;
pets[1] = 'Cow' # Sets pets[1] to 'Cow'&lt;br /&gt;
pets[1] = 'Cat' # Sets pets[1] back to 'Cat' &lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You can also access or assign lists using negative indices, which will return elements starting from the end of the list:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[-1] # Returns 'Snake'&lt;br /&gt;
pets[-2] # Returns 'Lizard'&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You can also use 'slice notation' to obtain or assign subsets of lists:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[start:end] # Returns items from index start to index end - 1.&lt;br /&gt;
pets[start:]    # Returns items from index start to the end of the list, inclusive.&lt;br /&gt;
pets[:end]      # Returns items from the beginning of the list to index end - 1.&lt;br /&gt;
pets[:]         # Returns every item in the list&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
There's also a third, optional argument: &amp;lt;code&amp;gt;step&amp;lt;/code&amp;gt;, which lets you jump over values:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[start:end:step] # Returns items from index start to index end - 1, jumping step values at a time&lt;br /&gt;
&lt;br /&gt;
# Examples:&lt;br /&gt;
pets[1:5:2] # Returns items from index 1 to index 4, jumping 2 at a time, so ['Cat', 'Turtle']&lt;br /&gt;
pets[::3] # Returns all items in the list, jumping 3 at a time, so ['Dog', 'Turtle']&lt;br /&gt;
pets[::-1] # Returns all items in the list, jumping -1 at a time. This reverses the list, so ['Snake', 'Lizard', 'Turtle', 'Fish', 'Cat', 'Dog']&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Lists have all the performance characteristics you'd expect of a dynamic array - constant-time indexing, amortized constant-time appends, and so on.&lt;br /&gt;
&lt;br /&gt;
==== Tuples ====&lt;br /&gt;
&lt;br /&gt;
Python has a special data type called &amp;lt;code&amp;gt;tuple&amp;lt;/code&amp;gt;, which is exactly the same as a list except for the fact that it cannot be modified, so you can't append or replace items.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
cities = ('St. Louis', 'Los Angeles', 'Seattle') # Tuples are defined using parentheses.&lt;br /&gt;
numbers = 1, 2, 3 # You can also omit the parentheses if it's unambiguous&lt;br /&gt;
single_item_tuple = (1,) # To make a tuple with only one item, put a comma after it&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Tuples also enable you to have multiple return values from a function:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def compute_length(string):&lt;br /&gt;
    str_len = len(string)&lt;br /&gt;
    if str_len &amp;lt; 5:&lt;br /&gt;
        return str_len, &amp;quot;short&amp;quot;&lt;br /&gt;
    elif str_len &amp;lt; 40:&lt;br /&gt;
        return str_len, &amp;quot;medium&amp;quot;&lt;br /&gt;
    return str_len, &amp;quot;long&amp;quot;&lt;br /&gt;
&lt;br /&gt;
length, description = compute_length(&amp;quot;Four score and seven years ago&amp;quot;)&lt;br /&gt;
print(f&amp;quot;The {description} string is {length} characters long.&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
The above example also demonstrates Python's if...elif...else conditional structure.&lt;br /&gt;
&lt;br /&gt;
==== Dictionaries ====&lt;br /&gt;
&lt;br /&gt;
Python has another datatype called a '''dictionary''' (or &amp;lt;code&amp;gt;dict&amp;lt;/code&amp;gt;, for short), which are like ''Maps'' in Java, ''associative arrays'' in PHP, and ''object literals'' in JavaScript (coming up soon in Module 6). Essentially, they enable you to use any immutable object as the key in your data structure. &amp;lt;code&amp;gt;dict&amp;lt;/code&amp;gt; objects can be created using either the &amp;lt;code&amp;gt;dict&amp;lt;/code&amp;gt; function, or by placing items between curly braces, separating keys and values using colons:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits_in_bowl = {&lt;br /&gt;
    'apple': 4,&lt;br /&gt;
    'banana': 2,&lt;br /&gt;
    'cherry': 0,&lt;br /&gt;
    'date': 12&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
apple_count = fruits_in_bowl['apple'] # Equals 4&lt;br /&gt;
&lt;br /&gt;
fruits_in_bowl['pear'] = 9 # Sets 'pear' in the dictionary to 9.&lt;br /&gt;
&lt;br /&gt;
for fruit, num in fruits_in_bowl.items():&lt;br /&gt;
    print(f&amp;quot;There are {num} {fruit}(s) in the bowl.&amp;quot; % (num, fruit))&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If you only want the keys from a dictionary, you can just iterate over it directly, like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
for fruit in fruits_in_bowl:&lt;br /&gt;
    print(fruit)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If you want only the values but not the keys from a dictionary, use &amp;lt;code&amp;gt;my_dictionary.values()&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
==== Sets ==== &lt;br /&gt;
A &amp;lt;code&amp;gt;set&amp;lt;/code&amp;gt; is an unordered collection of unique items, with constant-time membership checking. &lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = {'Apple', 'Apple', 'Apple', 'Pear'} # The set removes duplicates, so it will only contain {'Apple', 'Pear'}&lt;br /&gt;
fruits = set(['Apple', 'Apple', 'Apple', 'Pear']) # This line transforms a list into a set&lt;br /&gt;
print('Apple' in fruits) # Constant-time!&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Loops ===&lt;br /&gt;
&lt;br /&gt;
In Python, while loops are written like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
i = 0&lt;br /&gt;
while i &amp;lt; 10:&lt;br /&gt;
    i += 1&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
For loops are written like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish']&lt;br /&gt;
&lt;br /&gt;
for pet in pets:&lt;br /&gt;
    print(pet)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
To iterate over a range of numbers, you can use the convenient &amp;lt;code&amp;gt;range&amp;lt;/code&amp;gt; function, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
for i in range(20, 30): # If you omit the first argument to range, it's assumed to be zero.&lt;br /&gt;
    print(i)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Note that &amp;lt;code&amp;gt;range&amp;lt;/code&amp;gt; provides a closed-open range. That is to say, it is inclusive of its lower bound and exclusive of its upper bound. To be very explicit about it:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
list(range(3, 6)) == [3, 4, 5]&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Unlike in other languages you may know, the following is not good practice in Python:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish']&lt;br /&gt;
&lt;br /&gt;
# BAD PRACTICE. DO NOT USE.&lt;br /&gt;
for i in range(len(pets)):&lt;br /&gt;
    pet = pets[i]&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Instead, if you need to access both a variable and its index, use the &amp;lt;code&amp;gt;enumerate&amp;lt;/code&amp;gt; function, which allows you to iterate through a group of items, along with their indexes, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish']&lt;br /&gt;
&lt;br /&gt;
for index, pet in enumerate(pets):&lt;br /&gt;
    print(f&amp;quot;{pet} at index {index}&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Generator Expressions and Comprehensions ===&lt;br /&gt;
&lt;br /&gt;
A generator is a special kind of object that, basically, represents a collection of items using a value and a function for generating the next value in the collection. In other words, it's a way of creating something that behaves like a list, but which only generates one value at a time, and discards a value when it's done with it. Say, for example, you wanted to do an operation on 10,000,000,000,000 numbers. You could put them all in a list, then iterate over the list, but that would take a lot of memory, plus you'd have to create and fill the entire list before beginning to actually work on your problem. Instead, you'd probably be better off using a generator; telling the computer, essentially: “The starting value is 0. When I ask for the next number in the collection, add 1 to current value and give me that.”&lt;br /&gt;
&lt;br /&gt;
A generator expression is an expression that is evaluated to create a generator. They're super useful. Generator expressions can take two forms – they can be used with and without a condition:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
(EXPRESSION for VARIABLE in ITERABLE) # Unconditional&lt;br /&gt;
(EXPRESSION for VARIABLE in ITERABLE if CONDITION) # Conditional&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
For our purposes, you can think of an iterable as anything you can do a for loop over. Let's take a look at a generator expression in use:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
double_even_digits = (number * 2 for number in range(10) if number % 2 == 0)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
That line says that &amp;lt;code&amp;gt;double_even_digits&amp;lt;/code&amp;gt; is every even number between 0 and 10 multiplied by two. Simple enough, right? If we wanted to use all of the numbers, not just the even ones, we could simply remove the if statement at the end of the expression.&lt;br /&gt;
&lt;br /&gt;
Here's the thing, though: if you were to print &amp;lt;code&amp;gt;double_even_digits&amp;lt;/code&amp;gt;, instead of a nice bunch of numbers, you'd get something that looks like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&amp;lt;generator object &amp;lt;genexpr&amp;gt;&amp;lt;code&amp;gt;at 0x107fc92b0&amp;gt;&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
That's because generators are lazy! They don't generate their values until those values are needed, and they discard values once they're no longer needed. As a result, '''you can only iterate over a generator once'''. In this case, you can't print out the whole generator, because it hasn't generated all the values yet. You can, however, iterate over the generator, and print its values one at a time, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
for number in double_even_digits:&lt;br /&gt;
    print(number)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
You can also make a list out of the generator, which will go through all the items in the generator and put them in a list, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
even_number_list = list(double_even_digits)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
That's actually a great segue to the second topic of this section: comprehensions. A comprehension is just a prettier way to make lists, sets, and dicts out of a generator expressions.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
# If you want a list:&lt;br /&gt;
list(i for i in range(10) if i % 2 == 0) # Don't do this&lt;br /&gt;
[i for i in range(10) if i % 2 == 0] # Use a list comprehension instead!&lt;br /&gt;
&lt;br /&gt;
# If you want a set:&lt;br /&gt;
set(i for i in range(10) if i % 2 == 0) # Don't do this&lt;br /&gt;
{i for i in range(10) if i % 2 == 0} # Use a set comprehension instead!&lt;br /&gt;
&lt;br /&gt;
# If you want a dict:&lt;br /&gt;
dict((i, i + 1) for i in range(10) if i % 2 == 0) # Don't do this&lt;br /&gt;
{i : i + 1 for i in range(10) if i % 2 == 0} # Use a dict comprehension instead!&lt;br /&gt;
&lt;br /&gt;
# If you want a tuple:&lt;br /&gt;
tuple(i for i in range(10) if i % 2 == 0) # Unfortunately, there's no better way to do this&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
In general, generators and comprehensions should be used whenever possible - they're the fastest and easiest way to build collections. If you ever see yourself writing code like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
# BAD PRACTICE! DO NOT USE!&lt;br /&gt;
digits = []&lt;br /&gt;
for digit in range(10):&lt;br /&gt;
    digits.append(digit)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Don't do it! Instead, use a generator expression or comprehension, as appropriate. A good way to decide whether a generator expression or comprehension is better for this situation is that, if you're just going to be iterating over your collection once, you should use an generator expression. If not, use a comprehension.&lt;br /&gt;
&lt;br /&gt;
=== Sorting ===&lt;br /&gt;
&lt;br /&gt;
Sorting in Python is frequently performed using the &amp;lt;code&amp;gt;sorted&amp;lt;/code&amp;gt; function, which takes two arguments: an iterable (anything you can do a for-loop over, including lists and tuples) and a function used to evaluate each item. If the function is omitted, Python will try to sort the lists by value.&lt;br /&gt;
&lt;br /&gt;
The following example demonstrates using an inline function, which Python calls a ''lambda''.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = ['apple', 'banana', 'cherry', 'date']&lt;br /&gt;
&lt;br /&gt;
# sort the fruits by string length&lt;br /&gt;
new_fruits = sorted(fruits, key=lambda v: len(v) // 2)&lt;br /&gt;
&lt;br /&gt;
print(new_fruits) # ['date', 'apple', 'banana', 'cherry']&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Alternatively, you can sort a &amp;lt;code&amp;gt;list&amp;lt;/code&amp;gt; using the &amp;lt;code&amp;gt;.sort&amp;lt;/code&amp;gt; method. This is faster than calling &amp;lt;code&amp;gt;sorted&amp;lt;/code&amp;gt;, but it modifies the list in-place and returns &amp;lt;code&amp;gt;None&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = ['apple', 'banana', 'cherry', 'date']&lt;br /&gt;
fruits.sort()&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
=== Import ===&lt;br /&gt;
&lt;br /&gt;
If you want to use functions from other libraries (including ones that you install using pip), use &amp;lt;code&amp;gt;import&amp;lt;/code&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
import time&lt;br /&gt;
&lt;br /&gt;
current_time = time.localtime()&lt;br /&gt;
print(time.strftime('%a, %d %b %Y %H:%M:%S', current_time))&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If you want to pull the functions out of their namespace, you can use &amp;lt;code&amp;gt;from ___ import ___&amp;lt;/code&amp;gt; syntax:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
from time import localtime, strftime&lt;br /&gt;
&lt;br /&gt;
current_time = localtime()&lt;br /&gt;
print(strftime('%a, %d %b %Y %H:%M:%S', current_time))&lt;br /&gt;
&lt;br /&gt;
# Be aware that this technique, although convenient, may cause unexpected behavior if the function names that you're pulling out of the namespace are already used for other purposes in Python.&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
=== File I/O ===&lt;br /&gt;
&lt;br /&gt;
You can read an entire file into a variable like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
f = open(&amp;quot;example.txt&amp;quot;)&lt;br /&gt;
file_contents = f.read()&lt;br /&gt;
&lt;br /&gt;
f.close() # free up memory when we're finished with the file&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
A better option is to use a with-block, which handles opening and closing the file for you automatically:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
with open(&amp;quot;example.txt&amp;quot;) as f:&lt;br /&gt;
    file_contents = f.read()&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
You can read a file line-by-line like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
with open(&amp;quot;example.txt&amp;quot;) as f:&lt;br /&gt;
    for line in f:&lt;br /&gt;
        print(&amp;quot;Read line: %s&amp;quot; % line.rstrip())&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
You can write to a file like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
with open(&amp;quot;example.txt&amp;quot;, &amp;quot;w&amp;quot;) as f:&lt;br /&gt;
    f.write(&amp;quot;Hello\nWorld\n&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
=== Command-Line Arguments ===&lt;br /&gt;
&lt;br /&gt;
Command line arguments are accessible in the variable &amp;lt;code&amp;gt;sys.argv&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
The following example shows a program that expects a filename as its argument, and it prints a usage message if the argument is not present ([https://stackoverflow.com/questions/983201/python-and-sys-argv source]).&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
import sys, os&lt;br /&gt;
&lt;br /&gt;
if len(sys.argv) &amp;lt; 2:&lt;br /&gt;
    sys.exit(f&amp;quot;Usage: {sys.argv[0]} filename&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
filename = sys.argv[1]&lt;br /&gt;
&lt;br /&gt;
if not os.path.exists(filename):&lt;br /&gt;
    sys.exit(f&amp;quot;Error: File '{sys.argv[1]}' not found&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Object-Oriented Programming ===&lt;br /&gt;
&lt;br /&gt;
You can define and use a class like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
class Food:&lt;br /&gt;
    # constructor:&lt;br /&gt;
    def __init__(self, name):&lt;br /&gt;
        self.name = name&lt;br /&gt;
    &lt;br /&gt;
    def format_name(self):&lt;br /&gt;
        return f&amp;quot;Gotta love to eat {self.name}&amp;quot;&lt;br /&gt;
&lt;br /&gt;
class Fruit(Food):&lt;br /&gt;
    def format_name(self):&lt;br /&gt;
        return f&amp;quot;{Food.format_name(self)} (fruit)&amp;quot;&lt;br /&gt;
&lt;br /&gt;
fruit = Fruit(&amp;quot;Cherry&amp;quot;)&lt;br /&gt;
print(fruit.format_name())&lt;br /&gt;
print(Food.get_definition())&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
This is the same example as in [[PHP#Object-Oriented_Programming|the PHP guide]].&lt;br /&gt;
&lt;br /&gt;
Some things to notice:&lt;br /&gt;
&lt;br /&gt;
* Instance methods ''always'' take &amp;lt;code&amp;gt;self&amp;lt;/code&amp;gt; as their first argument, followed by any number of additional parameters. This can be misleading for programmers familiar with other languages, because the number of arguments you feed to the method is actually ''one less than'' the number of declared parameters. Whenever you call a method on a class instance, that instance is implicitly fed into the explicitly-declared &amp;lt;code&amp;gt;self&amp;lt;/code&amp;gt; parameter of the method.&lt;br /&gt;
*: Note that the &amp;lt;code&amp;gt;self&amp;lt;/code&amp;gt; variable has the same purpose as the &amp;lt;code&amp;gt;this&amp;lt;/code&amp;gt; variable in languages like PHP, Java, JavaScript, and C++.&lt;br /&gt;
*There is no need for a &amp;lt;code&amp;gt;new&amp;lt;/code&amp;gt; keyword in Python.&lt;br /&gt;
&lt;br /&gt;
= Footnotes =&lt;br /&gt;
# {{note|interpreted}}This is an oversimplification. If you're interested, here's a quick explanation of how: In CPython (the reference implementation of Python) programs are compiled to bytecode, an intermediate representation, which is then interpreted.&lt;br /&gt;
[[Category:Module 4]]&lt;/div&gt;</summary>
		<author><name>Alex</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Python&amp;diff=2520</id>
		<title>Python</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Python&amp;diff=2520"/>
		<updated>2018-02-19T17:33:39Z</updated>

		<summary type="html">&lt;p&gt;Alex: /* Installation */  Bumped Python version&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Languages like Java and C++ have lots of rules regarding variable types, syntax, return values, and so on. These can be cumbersome when you are trying to write short, quick scripts to perform tasks. This is where a ''scripting language'' comes into play.&lt;br /&gt;
&lt;br /&gt;
'''Python''' is a language well-suited to rapid prototype development. It is generally an ''interpreted language'', which means that, generally speaking, a Python program is converted line by line into instructions for the computer to execute as the program runs, instead of having a separate compilation step beforehand {{ref|interpreted}}. The syntax is clean, and it is usually clear at first glance what is going on when you write in Python.&lt;br /&gt;
&lt;br /&gt;
= Installation =&lt;br /&gt;
&lt;br /&gt;
Python may already be installed on your system. To see whether or not it is, enter the command&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ python --version&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If it tells you a version of Python '''greater than or equal to 3.6''' then you're good to go. If not, you need to do a quick package install to get it up and running. Using yum, it's just &amp;lt;code&amp;gt;sudo yum install python36; sudo alternatives --set python /usr/bin/python3&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
==== Python 2 vs Python 3 ====&lt;br /&gt;
&lt;br /&gt;
In 2008, a new version of Python – Python 3 – was released, with a number changes that made it incompatible with the previous version, Python 2. For several years, the Python community was slow to make the change to Python 3, but today, Python 3 is ''the'' standard for new code. The ''only'' reason to write Python 2 code today is because you have to work in an environment or with libraries that do not support Python 3, and that situation is becoming increasingly rare.&lt;br /&gt;
&lt;br /&gt;
'''For CSE 330 (and this guide), you ''must'' use Python 3.6 or greater.'''&lt;br /&gt;
&lt;br /&gt;
=== Pip ===&lt;br /&gt;
&lt;br /&gt;
Linux distributions have package managers like ''Apt'', ''Yum'', and ''YaST''. PHP has a package manager named ''PEAR''. It's now time to introduce Python's leading package manager: '''pip'''.&lt;br /&gt;
&lt;br /&gt;
You need to install Pip from Yum before you can use it. The package is called &amp;lt;code&amp;gt;python-pip&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Once you have pip installed, you can use it to install Python packages. Use the &amp;lt;code&amp;gt;pip-python&amp;lt;/code&amp;gt; command:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ pip-python install package_name # RHEL&lt;br /&gt;
$ pip install package_name # Debian&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Running Python =&lt;br /&gt;
&lt;br /&gt;
There are two common ways to run Python code: via the console, and via a Python script file.&lt;br /&gt;
&lt;br /&gt;
=== The Python Console ===&lt;br /&gt;
&lt;br /&gt;
The Python console enables you to experiment with code without opening a text editor. To enter the Python console, simply type the ''python'' command at the terminal:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ python&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
To leave the interactive console, either type &amp;lt;code&amp;gt;quit()&amp;lt;/code&amp;gt; or press &amp;lt;code&amp;gt;Ctrl-D&amp;lt;/code&amp;gt; (on both Mac and Windows).&lt;br /&gt;
&lt;br /&gt;
=== Python Script Files ===&lt;br /&gt;
&lt;br /&gt;
You can also save Python script files for later use. The extension for Python scripts is &amp;lt;code&amp;gt;*.py&amp;lt;/code&amp;gt;. To run a script file, simply feed its path as an argument to the &amp;lt;code&amp;gt;python&amp;lt;/code&amp;gt; command in Terminal:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ python my_script.py&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Python Syntax and Language Components =&lt;br /&gt;
&lt;br /&gt;
This section contains a very brief overview of Python syntax. For a more comprehensive introduction, see [http://docs.python.org/tutorial/ the Python docs].&lt;br /&gt;
&lt;br /&gt;
=== Python's Type System ===&lt;br /&gt;
&lt;br /&gt;
Python is a dynamically-typed, strongly-typed, and duck-typed language. What does that mean? Well, let's take those categories one by one:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;ol&amp;gt;&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
'''Dynamic typing''', in contrast to ''static typing'' means that the types of objects can be changed. In Java, for instance, if you tried to write the following code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
int c = 2;&lt;br /&gt;
c = &amp;quot;fish&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Your code would fail to compile, because the Java compiler wouldn't allow you to change the type of the variable &amp;lt;code&amp;gt;c&amp;lt;/code&amp;gt; from &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt; to &amp;lt;code&amp;gt;String&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Python, however, is just fine with that. You can write:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
c = 2&lt;br /&gt;
c = &amp;quot;fish&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
And Python will happily do what you ask.&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
'''Strong typing''', in contrast to ''weak typing'', means, roughly, that a language won't implicitly convert types for you. So far, you've used a lot of PHP, which is very weakly typed. For example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;php&amp;quot;&amp;gt;&lt;br /&gt;
echo &amp;quot;10&amp;quot; . 2;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In PHP, this works just fine. The PHP interpreter sees that &amp;lt;code&amp;gt;2&amp;lt;/code&amp;gt; is an int, and silently converts it to a string for you, so that &amp;lt;code&amp;gt;&amp;quot;10&amp;quot;. 2&amp;lt;/code&amp;gt; equals &amp;lt;code&amp;gt;&amp;quot;102&amp;quot;&amp;lt;/code&amp;gt;. The problem with weak typing is that it can make it unclear to the programmer why things are happening the way they are. For instance, in PHP, the expression &amp;lt;code&amp;gt;&amp;quot;10&amp;quot; == 10&amp;lt;/code&amp;gt; is true, which can be less than obvious. Python, however, tries to disallow that sort of thing:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
&amp;quot;10&amp;quot; + &amp;quot;10&amp;quot; # Allowed – concatenates the two strings.&lt;br /&gt;
10   +  10  # Allowed – adds the two ints.&lt;br /&gt;
&amp;quot;10&amp;quot; +  10  # Not allowed – raises a TypeError&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Perhaps the one exception to this rule is the relationship between numeric types; it's perfectly fine to add a float to an int, for example.&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
'''Duck-typing''' is a little bit different than the other categories, because it doesn't really have a direct opposite. Essentially, duck-typing is the philosophy that &amp;quot;If it walks like a duck, and quacks like a duck, it's a duck.&amp;quot; In programming terms, that means that we often don't care what type an object is, as long as it can do the things we ask.&lt;br /&gt;
&lt;br /&gt;
Let's look at an example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
# This function doubles the value it's passed.&lt;br /&gt;
def double(thing):&lt;br /&gt;
    return thing + thing&lt;br /&gt;
double(10) # Returns 20&lt;br /&gt;
double(&amp;quot;fish&amp;quot;) # Returns &amp;quot;fishfish&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If this were Java, we'd have to write two different methods here: one for things of type &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt;, and one for things of type &amp;lt;code&amp;gt;String&amp;lt;/code&amp;gt;. Since this is Python, though, we don't have to do that. Instead, Python lets us say, essentially: &amp;quot;This function uses the &amp;lt;code&amp;gt;+&amp;lt;/code&amp;gt; operator, so you can pass whatever object you want to the function, as long as the function supports the &amp;lt;code&amp;gt;+&amp;lt;/code&amp;gt; operator&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
To quote [https://groups.google.com/forum/?hl=en#!msg/comp.lang.python/CCs2oJdyuzc/NYjla5HKMOIJ Alex Martelli], one of the key people in the Python project,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;blockquote&amp;gt;&lt;br /&gt;
&amp;quot;[Don't] check whether it IS-a duck: check whether it QUACKS-like-a duck, WALKS-like-a duck, etc, etc, depending on exactly what subset of duck-like behaviour you need.&amp;quot;&lt;br /&gt;
&amp;lt;/blockquote&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&amp;lt;/ol&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Basic Types ===&lt;br /&gt;
&lt;br /&gt;
In Python, the basic scalar types are:&lt;br /&gt;
&lt;br /&gt;
# &amp;lt;code&amp;gt;str&amp;lt;/code&amp;gt; – a string.&lt;br /&gt;
# &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt; – an integer object with unlimited digits.&lt;br /&gt;
# &amp;lt;code&amp;gt;bool&amp;lt;/code&amp;gt; – a Boolean value.&lt;br /&gt;
# &amp;lt;code&amp;gt;float&amp;lt;/code&amp;gt; – a floating point number; generally equivalent to &amp;lt;code&amp;gt;double&amp;lt;/code&amp;gt; in Java.&lt;br /&gt;
# &amp;lt;code&amp;gt;bytes&amp;lt;/code&amp;gt; – represents a collection of bytes; you're unlikely to use this often.&lt;br /&gt;
&lt;br /&gt;
Casting is done in the C style - to parse an &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt; from a string, for instance, you'd write &amp;lt;code&amp;gt;int(&amp;quot;123&amp;quot;)&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== Basic Control Flow ===&lt;br /&gt;
In Python, blocks of code are delineated using colons and indentation instead of curly braces. '''''That means that proper indentation is mandatory.''''' Every time you use a colon, you must indent one step further, and every time a block ends, you must unindent a step.&lt;br /&gt;
&lt;br /&gt;
Conditional statements are done using the &amp;lt;code&amp;gt;if&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;elif&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;else&amp;lt;/code&amp;gt; operators, like in the example below - pay attention to the indentation:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
cookies_left = 10&lt;br /&gt;
cake_slices_left = 3&lt;br /&gt;
if cookies_left &amp;gt; 10:&lt;br /&gt;
    print(&amp;quot;Lots of cookies!&amp;quot;)&lt;br /&gt;
elif cookies_left &amp;gt; 8:&lt;br /&gt;
    print(&amp;quot;Plenty left!&amp;quot;)&lt;br /&gt;
elif cookies_left == 5:&lt;br /&gt;
    print(&amp;quot;Halfway done!&amp;quot;)&lt;br /&gt;
else:&lt;br /&gt;
    if cake_slices_left == 3:&lt;br /&gt;
        print(&amp;quot;Lots of cake!&amp;quot;)&lt;br /&gt;
    elif cake_slices_left == 2:&lt;br /&gt;
        print(&amp;quot;One slice gone!&amp;quot;)&lt;br /&gt;
    else:&lt;br /&gt;
        print(&amp;quot;Little to no cake left!&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== An Example Python Script ===&lt;br /&gt;
&lt;br /&gt;
In my mind, there's no better way to learn Python than to be immersed in a simple example script.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
print(&amp;quot;Hello World&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
fruits = [&amp;quot;apple&amp;quot;, &amp;quot;banana&amp;quot;, &amp;quot;cherry&amp;quot;, &amp;quot;date&amp;quot;]&lt;br /&gt;
for fruit in fruits:&lt;br /&gt;
    print(f&amp;quot;I always love to eat a fresh {fruit}&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Map the fruits list over to a new list containing the length of the fruit strings:&lt;br /&gt;
fruit_size = [len(fruit) for fruit in fruits]&lt;br /&gt;
&lt;br /&gt;
avg_fruit_size = sum(fruit_size) / len(fruit_size)&lt;br /&gt;
print(f&amp;quot;The average fruit string length is {avg_fruit_size:.2f}.&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Some things to notice:&lt;br /&gt;
&lt;br /&gt;
* Printing is achieved using the &amp;lt;code&amp;gt;print()&amp;lt;/code&amp;gt; function.&lt;br /&gt;
* Comments start with a pound symbol &amp;lt;code&amp;gt;#&amp;lt;/code&amp;gt;.&lt;br /&gt;
* We can transform/map a list to a new list in just one line!&lt;br /&gt;
&lt;br /&gt;
For some more examples, see [https://wiki.python.org/moin/SimplePrograms the Python wiki].&lt;br /&gt;
&lt;br /&gt;
=== A Few Gotchas ===&lt;br /&gt;
&lt;br /&gt;
Here are a few things you may not expect when starting out with Python:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;ol&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
Strings can be delimited using either single quotes (&amp;lt;code&amp;gt;'&amp;lt;/code&amp;gt;) or double quotes (&amp;lt;code&amp;gt;&amp;quot;&amp;lt;/code&amp;gt;), so &amp;lt;code&amp;gt;'Python'&amp;lt;/code&amp;gt; is the same as &amp;lt;code&amp;gt;&amp;quot;Python&amp;quot;&amp;lt;/code. You can also use three sets of quotes (&amp;lt;code&amp;gt;'''&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;&amp;quot;&amp;quot;&amp;quot;&amp;lt;/code&amp;gt;) to delineate a multiple-line string, like so:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
long_string = &amp;quot;&amp;quot;&amp;quot;This&lt;br /&gt;
is my&lt;br /&gt;
very long&lt;br /&gt;
multiple-line&lt;br /&gt;
string&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
To compare the equality of two objects, use the &amp;lt;code&amp;gt;==&amp;lt;/code&amp;gt; operator. To compare the identity of two objects (i.e. whether or not they are literally the same object, at the same place in memory), use the &amp;lt;code&amp;gt;is&amp;lt;/code&amp;gt; operator. These correspond, respectively to &amp;lt;code&amp;gt;.equals()&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;==&amp;lt;/code&amp;gt; in Java.&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
The &amp;lt;code&amp;gt;/&amp;lt;/code&amp;gt; operator performs floating-point division, not integer division, even when both its arguments are integers. If you want to do integer division, use the &amp;lt;code&amp;gt;//&amp;lt;/code&amp;gt; operator. Let's look at an example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
9   / 10    == 0.9 # Floating-point division&lt;br /&gt;
9.0 / 10.0  == 0.9 # Floating-point division&lt;br /&gt;
9   // 10   == 0   # Integer division&lt;br /&gt;
9.0 // 10.0 == 0.0 # Integer division, even though the resulting value is a float&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
As discussed in the section [[#Python's_Type_System|Python's Type System]], you can't combine strings and numbers using the &amp;lt;code&amp;gt;+&amp;lt;/code&amp;gt; operator. Instead, you'll have to use one of the following methods of string formatting:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
  &lt;br /&gt;
# Technique 1 – printf-style Formatting&lt;br /&gt;
# This is a classic style of string formatting, used in many programming languages, including in Java's String.format.&lt;br /&gt;
&amp;quot;You scored %d out of %d!&amp;quot; % (score, questions)&lt;br /&gt;
&lt;br /&gt;
# Technique 2 – str.format&lt;br /&gt;
&amp;quot;You scored {} out of {}!&amp;quot;.format(score, questions)&lt;br /&gt;
&lt;br /&gt;
# Technique 3 – f-strings&lt;br /&gt;
# These were only introduced in Python 3.6 but they're very convenient.&lt;br /&gt;
f&amp;quot;You scored {score} out of {questions}!&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# Technique 4 - String Concatenation&lt;br /&gt;
# This is fine for small things, but for more complicated stuff, use one of the other techniques.&lt;br /&gt;
&amp;quot;You scored &amp;quot; + str(score) + &amp;quot; out of &amp;quot; + str(questions) + &amp;quot;!&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&amp;lt;/ol&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Functions ===&lt;br /&gt;
&lt;br /&gt;
Define functions using the &amp;lt;code&amp;gt;def&amp;lt;/code&amp;gt; keyword:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def hello(name):&lt;br /&gt;
    print(f&amp;quot;Hello, {name}!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Invoke functions using parentheses:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
hello(&amp;quot;Batman&amp;quot;)&lt;br /&gt;
hello(&amp;quot;Superman&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Functions can have optional arguments; however, these must come after any required arguments:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def hello(name=&amp;quot;User&amp;quot;):&lt;br /&gt;
    print(f&amp;quot;Hello, {name}!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
hello() # Prints &amp;quot;Hello, User!&amp;quot;&lt;br /&gt;
hello(&amp;quot;Sarah&amp;quot;) # Prints &amp;quot;Hello, Sarah!&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Functions are just regular objects in Python, meaning you can do stuff like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def hello(name=&amp;quot;User&amp;quot;):&lt;br /&gt;
    print(f&amp;quot;Hello, {name}!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
greeting = hello&lt;br /&gt;
&lt;br /&gt;
greeting(&amp;quot;Siwei&amp;quot;) # Prints &amp;quot;Hello, Siwei!&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Collection Types ===&lt;br /&gt;
Python has a few basic, built-in collection types. They each have their own special use cases, but they share a lot of similarities. All built-in data structures in Python are zero-indexed, for instance.&lt;br /&gt;
&lt;br /&gt;
To obtain the number of elements in a collection, use the &amp;lt;code&amp;gt;len()&amp;lt;/code&amp;gt; function, like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish'] # This is a list; you'll learn about them below.&lt;br /&gt;
&lt;br /&gt;
len(pets) # Returns 3&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To check if a collection contains an item, use the &amp;lt;code&amp;gt;in&amp;lt;/code&amp;gt; operator:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish'] # This is a list; you'll learn about them below.&lt;br /&gt;
&lt;br /&gt;
'Dog' in pets # Returns True&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Helpfully, the Python Software Foundation maintains a page containing the asymptotic complexities of important operations on major Python data structures. It's available [https://wiki.python.org/moin/TimeComplexity here].&lt;br /&gt;
&lt;br /&gt;
==== Lists ====&lt;br /&gt;
&lt;br /&gt;
Unlike languages like Java and C, Python's array-like type doesn't have fixed length. Instead, a &amp;lt;code&amp;gt;list&amp;lt;/code&amp;gt; is a dynamic array (like Java's &amp;lt;code&amp;gt;ArrayList&amp;lt;/code&amp;gt;) of objects of any type. Here's an example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = [&amp;quot;Apple&amp;quot;, &amp;quot;Pear&amp;quot;, &amp;quot;Orange&amp;quot;] # Lists can be creating by placing their items between square brackets&lt;br /&gt;
&lt;br /&gt;
random_items = ['Apple', 12312, 2.0, [1, 2, 3]] # Lists can contain objects of different types - even other lists!&lt;br /&gt;
&lt;br /&gt;
pets.append('Turtle') # Adds 'Turtle' to the end of pets&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For the next few examples, we'll be using the following list:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish', 'Turtle', 'Lizard', 'Snake']&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access or assign elements of a list, use the &amp;lt;code&amp;gt;[]&amp;lt;/code&amp;gt; operator.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[0] # Returns 'Dog'&lt;br /&gt;
pets[1] = 'Cow' # Sets pets[1] to 'Cow'&lt;br /&gt;
pets[1] = 'Cat' # Sets pets[1] back to 'Cat' &lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You can also access or assign lists using negative indices, which will return elements starting from the end of the list:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[-1] # Returns 'Snake'&lt;br /&gt;
pets[-2] # Returns 'Lizard'&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You can also use 'slice notation' to obtain or assign subsets of lists:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[start:end] # Returns items from index start to index end - 1.&lt;br /&gt;
pets[start:]    # Returns items from index start to the end of the list, inclusive.&lt;br /&gt;
pets[:end]      # Returns items from the beginning of the list to index end - 1.&lt;br /&gt;
pets[:]         # Returns every item in the list&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
There's also a third, optional argument: &amp;lt;code&amp;gt;step&amp;lt;/code&amp;gt;, which lets you jump over values:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[start:end:step] # Returns items from index start to index end - 1, jumping step values at a time&lt;br /&gt;
&lt;br /&gt;
# Examples:&lt;br /&gt;
pets[1:5:2] # Returns items from index 1 to index 4, jumping 2 at a time, so ['Cat', 'Turtle']&lt;br /&gt;
pets[::3] # Returns all items in the list, jumping 3 at a time, so ['Dog', 'Turtle']&lt;br /&gt;
pets[::-1] # Returns all items in the list, jumping -1 at a time. This reverses the list, so ['Snake', 'Lizard', 'Turtle', 'Fish', 'Cat', 'Dog']&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Lists have all the performance characteristics you'd expect of a dynamic array - constant-time indexing, amortized constant-time appends, and so on.&lt;br /&gt;
&lt;br /&gt;
==== Tuples ====&lt;br /&gt;
&lt;br /&gt;
Python has a special data type called &amp;lt;code&amp;gt;tuple&amp;lt;/code&amp;gt;, which is exactly the same as a list except for the fact that it cannot be modified, so you can't append or replace items.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
cities = ('St. Louis', 'Los Angeles', 'Seattle') # Tuples are defined using parentheses.&lt;br /&gt;
numbers = 1, 2, 3 # You can also omit the parentheses if it's unambiguous&lt;br /&gt;
single_item_tuple = (1,) # To make a tuple with only one item, put a comma after it&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Tuples also enable you to have multiple return values from a function:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def compute_length(string):&lt;br /&gt;
    str_len = len(string)&lt;br /&gt;
    if str_len &amp;lt; 5:&lt;br /&gt;
        return str_len, &amp;quot;short&amp;quot;&lt;br /&gt;
    elif str_len &amp;lt; 40:&lt;br /&gt;
        return str_len, &amp;quot;medium&amp;quot;&lt;br /&gt;
    return str_len, &amp;quot;long&amp;quot;&lt;br /&gt;
&lt;br /&gt;
length, description = compute_length(&amp;quot;Four score and seven years ago&amp;quot;)&lt;br /&gt;
print(f&amp;quot;The {description} string is {length} characters long.&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
The above example also demonstrates Python's if...elif...else conditional structure.&lt;br /&gt;
&lt;br /&gt;
==== Dictionaries ====&lt;br /&gt;
&lt;br /&gt;
Python has another datatype called a '''dictionary''' (or &amp;lt;code&amp;gt;dict&amp;lt;/code&amp;gt;, for short), which are like ''Maps'' in Java, ''associative arrays'' in PHP, and ''object literals'' in JavaScript (coming up soon in Module 6). Essentially, they enable you to use any immutable object as the key in your data structure. &amp;lt;code&amp;gt;dict&amp;lt;/code&amp;gt; objects can be created using either the &amp;lt;code&amp;gt;dict&amp;lt;/code&amp;gt; function, or by placing items between curly braces, separating keys and values using colons:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits_in_bowl = {&lt;br /&gt;
    'apple': 4,&lt;br /&gt;
    'banana': 2,&lt;br /&gt;
    'cherry': 0,&lt;br /&gt;
    'date': 12&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
apple_count = fruits_in_bowl['apple'] # Equals 4&lt;br /&gt;
&lt;br /&gt;
fruits_in_bowl['pear'] = 9 # Sets 'pear' in the dictionary to 9.&lt;br /&gt;
&lt;br /&gt;
for fruit, num in fruits_in_bowl.items():&lt;br /&gt;
    print(f&amp;quot;There are {num} {fruit}(s) in the bowl.&amp;quot; % (num, fruit))&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If you only want the keys from a dictionary, you can just iterate over it directly, like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
for fruit in fruits_in_bowl:&lt;br /&gt;
    print(fruit)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If you want only the values but not the keys from a dictionary, use &amp;lt;code&amp;gt;my_dictionary.values()&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
==== Sets ==== &lt;br /&gt;
A &amp;lt;code&amp;gt;set&amp;lt;/code&amp;gt; is an unordered collection of unique items, with constant-time membership checking. &lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = {'Apple', 'Apple', 'Apple', 'Pear'} # The set removes duplicates, so it will only contain {'Apple', 'Pear'}&lt;br /&gt;
fruits = set(['Apple', 'Apple', 'Apple', 'Pear']) # This line transforms a list into a set&lt;br /&gt;
print('Apple' in fruits) # Constant-time!&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Loops ===&lt;br /&gt;
&lt;br /&gt;
In Python, while loops are written like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
i = 0&lt;br /&gt;
while i &amp;lt; 10:&lt;br /&gt;
    i += 1&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
For loops are written like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish']&lt;br /&gt;
&lt;br /&gt;
for pet in pets:&lt;br /&gt;
    print(pet)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
To iterate over a range of numbers, you can use the convenient &amp;lt;code&amp;gt;range&amp;lt;/code&amp;gt; function, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
for i in range(20, 30): # If you omit the first argument to range, it's assumed to be zero.&lt;br /&gt;
    print(i)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Note that &amp;lt;code&amp;gt;range&amp;lt;/code&amp;gt; provides a closed-open range. That is to say, it is inclusive of its lower bound and exclusive of its upper bound. To be very explicit about it:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
list(range(3, 6)) == [3, 4, 5]&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Unlike in other languages you may know, the following is not good practice in Python:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish']&lt;br /&gt;
&lt;br /&gt;
# BAD PRACTICE. DO NOT USE.&lt;br /&gt;
for i in range(len(pets)):&lt;br /&gt;
    pet = pets[i]&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Instead, if you need to access both a variable and its index, use the &amp;lt;code&amp;gt;enumerate&amp;lt;/code&amp;gt; function, which allows you to iterate through a group of items, along with their indexes, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish']&lt;br /&gt;
&lt;br /&gt;
for index, pet in enumerate(pets):&lt;br /&gt;
    print(f&amp;quot;{pet} at index {index}&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Generator Expressions and Comprehensions ===&lt;br /&gt;
&lt;br /&gt;
A generator is a special kind of object that, basically, represents a collection of items using a value and a function for generating the next value in the collection. In other words, it's a way of creating something that behaves like a list, but which only generates one value at a time, and discards a value when it's done with it. Say, for example, you wanted to do an operation on 10,000,000,000,000 numbers. You could put them all in a list, then iterate over the list, but that would take a lot of memory, plus you'd have to create and fill the entire list before beginning to actually work on your problem. Instead, you'd probably be better off using a generator; telling the computer, essentially: “The starting value is 0. When I ask for the next number in the collection, add 1 to current value and give me that.”&lt;br /&gt;
&lt;br /&gt;
A generator expression is an expression that is evaluated to create a generator. They're super useful. Generator expressions can take two forms – they can be used with and without a condition:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
(EXPRESSION for VARIABLE in ITERABLE) # Unconditional&lt;br /&gt;
(EXPRESSION for VARIABLE in ITERABLE if CONDITION) # Conditional&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
For our purposes, you can think of an iterable as anything you can do a for loop over. Let's take a look at a generator expression in use:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
double_even_digits = (number * 2 for number in range(10) if number % 2 == 0)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
That line says that &amp;lt;code&amp;gt;double_even_digits&amp;lt;/code&amp;gt; is every even number between 0 and 10 multiplied by two. Simple enough, right? If we wanted to use all of the numbers, not just the even ones, we could simply remove the if statement at the end of the expression.&lt;br /&gt;
&lt;br /&gt;
Here's the thing, though: if you were to print &amp;lt;code&amp;gt;double_even_digits&amp;lt;/code&amp;gt;, instead of a nice bunch of numbers, you'd get something that looks like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&amp;lt;generator object &amp;lt;genexpr&amp;gt;&amp;lt;code&amp;gt;at 0x107fc92b0&amp;gt;&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
That's because generators are lazy! They don't generate their values until those values are needed, and they discard values once they're no longer needed. As a result, '''you can only iterate over a generator once'''. In this case, you can't print out the whole generator, because it hasn't generated all the values yet. You can, however, iterate over the generator, and print its values one at a time, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
for number in double_even_digits:&lt;br /&gt;
    print(number)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
You can also make a list out of the generator, which will go through all the items in the generator and put them in a list, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
even_number_list = list(double_even_digits)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
That's actually a great segue to the second topic of this section: comprehensions. A comprehension is just a prettier way to make lists, sets, and dicts out of a generator expressions.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
# If you want a list:&lt;br /&gt;
list(i for i in range(10) if i % 2 == 0) # Don't do this&lt;br /&gt;
[i for i in range(10) if i % 2 == 0] # Use a list comprehension instead!&lt;br /&gt;
&lt;br /&gt;
# If you want a set:&lt;br /&gt;
set(i for i in range(10) if i % 2 == 0) # Don't do this&lt;br /&gt;
{i for i in range(10) if i % 2 == 0} # Use a set comprehension instead!&lt;br /&gt;
&lt;br /&gt;
# If you want a dict:&lt;br /&gt;
dict((i, i + 1) for i in range(10) if i % 2 == 0) # Don't do this&lt;br /&gt;
{i : i + 1 for i in range(10) if i % 2 == 0} # Use a dict comprehension instead!&lt;br /&gt;
&lt;br /&gt;
# If you want a tuple:&lt;br /&gt;
tuple(i for i in range(10) if i % 2 == 0) # Unfortunately, there's no better way to do this&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
In general, generators and comprehensions should be used whenever possible - they're the fastest and easiest way to build collections. If you ever see yourself writing code like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
# BAD PRACTICE! DO NOT USE!&lt;br /&gt;
digits = []&lt;br /&gt;
for digit in range(10):&lt;br /&gt;
    digits.append(digit)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Don't do it! Instead, use a generator expression or comprehension, as appropriate. A good way to decide whether a generator expression or comprehension is better for this situation is that, if you're just going to be iterating over your collection once, you should use an generator expression. If not, use a comprehension.&lt;br /&gt;
&lt;br /&gt;
=== Sorting ===&lt;br /&gt;
&lt;br /&gt;
Sorting in Python is frequently performed using the &amp;lt;code&amp;gt;sorted&amp;lt;/code&amp;gt; function, which takes two arguments: an iterable (anything you can do a for-loop over, including lists and tuples) and a function used to evaluate each item. If the function is omitted, Python will try to sort the lists by value.&lt;br /&gt;
&lt;br /&gt;
The following example demonstrates using an inline function, which Python calls a ''lambda''.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = ['apple', 'banana', 'cherry', 'date']&lt;br /&gt;
&lt;br /&gt;
# sort the fruits by string length&lt;br /&gt;
new_fruits = sorted(fruits, key=lambda v: len(v) // 2)&lt;br /&gt;
&lt;br /&gt;
print(new_fruits) # ['date', 'apple', 'banana', 'cherry']&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Alternatively, you can sort a &amp;lt;code&amp;gt;list&amp;lt;/code&amp;gt; using the &amp;lt;code&amp;gt;.sort&amp;lt;/code&amp;gt; method. This is faster than calling &amp;lt;code&amp;gt;sorted&amp;lt;/code&amp;gt;, but it modifies the list in-place and returns &amp;lt;code&amp;gt;None&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = ['apple', 'banana', 'cherry', 'date']&lt;br /&gt;
fruits.sort()&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
=== Import ===&lt;br /&gt;
&lt;br /&gt;
If you want to use functions from other libraries (including ones that you install using pip), use &amp;lt;code&amp;gt;import&amp;lt;/code&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
import time&lt;br /&gt;
&lt;br /&gt;
current_time = time.localtime()&lt;br /&gt;
print(time.strftime('%a, %d %b %Y %H:%M:%S', current_time))&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If you want to pull the functions out of their namespace, you can use &amp;lt;code&amp;gt;from ___ import ___&amp;lt;/code&amp;gt; syntax:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
from time import localtime, strftime&lt;br /&gt;
&lt;br /&gt;
current_time = localtime()&lt;br /&gt;
print(strftime('%a, %d %b %Y %H:%M:%S', current_time))&lt;br /&gt;
&lt;br /&gt;
# Be aware that this technique, although convenient, may cause unexpected behavior if the function names that you're pulling out of the namespace are already used for other purposes in Python.&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
=== File I/O ===&lt;br /&gt;
&lt;br /&gt;
You can read an entire file into a variable like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
f = open(&amp;quot;example.txt&amp;quot;)&lt;br /&gt;
file_contents = f.read()&lt;br /&gt;
&lt;br /&gt;
f.close() # free up memory when we're finished with the file&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
A better option is to use a with-block, which handles opening and closing the file for you automatically:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
with open(&amp;quot;example.txt&amp;quot;) as f:&lt;br /&gt;
    file_contents = f.read()&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
You can read a file line-by-line like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
with open(&amp;quot;example.txt&amp;quot;) as f:&lt;br /&gt;
    for line in f:&lt;br /&gt;
        print(&amp;quot;Read line: %s&amp;quot; % line.rstrip())&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
You can write to a file like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
with open(&amp;quot;example.txt&amp;quot;, &amp;quot;w&amp;quot;) as f:&lt;br /&gt;
    f.write(&amp;quot;Hello\nWorld\n&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
=== Command-Line Arguments ===&lt;br /&gt;
&lt;br /&gt;
Command line arguments are accessible in the variable &amp;lt;code&amp;gt;sys.argv&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
The following example shows a program that expects a filename as its argument, and it prints a usage message if the argument is not present ([https://stackoverflow.com/questions/983201/python-and-sys-argv source]).&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
import sys, os&lt;br /&gt;
&lt;br /&gt;
if len(sys.argv) &amp;lt; 2:&lt;br /&gt;
    sys.exit(f&amp;quot;Usage: {sys.argv[0]} filename&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
filename = sys.argv[1]&lt;br /&gt;
&lt;br /&gt;
if not os.path.exists(filename):&lt;br /&gt;
    sys.exit(f&amp;quot;Error: File '{sys.argv[1]}' not found&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Object-Oriented Programming ===&lt;br /&gt;
&lt;br /&gt;
You can define and use a class like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
class Food:&lt;br /&gt;
    # constructor:&lt;br /&gt;
    def __init__(self, name):&lt;br /&gt;
        self.name = name&lt;br /&gt;
    &lt;br /&gt;
    def format_name(self):&lt;br /&gt;
        return f&amp;quot;Gotta love to eat {self.name}&amp;quot;&lt;br /&gt;
&lt;br /&gt;
class Fruit(Food):&lt;br /&gt;
    def format_name(self):&lt;br /&gt;
        return f&amp;quot;{Food.format_name(self)} (fruit)&amp;quot;&lt;br /&gt;
&lt;br /&gt;
fruit = Fruit(&amp;quot;Cherry&amp;quot;)&lt;br /&gt;
print(fruit.format_name())&lt;br /&gt;
print(Food.get_definition())&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
This is the same example as in [[PHP#Object-Oriented_Programming|the PHP guide]].&lt;br /&gt;
&lt;br /&gt;
Some things to notice:&lt;br /&gt;
&lt;br /&gt;
* Instance methods ''always'' take &amp;lt;code&amp;gt;self&amp;lt;/code&amp;gt; as their first argument, followed by any number of additional parameters. This can be misleading for programmers familiar with other languages, because the number of arguments you feed to the method is actually ''one less than'' the number of declared parameters. Whenever you call a method on a class instance, that instance is implicitly fed into the explicitly-declared &amp;lt;code&amp;gt;self&amp;lt;/code&amp;gt; parameter of the method.&lt;br /&gt;
*: Note that the &amp;lt;code&amp;gt;self&amp;lt;/code&amp;gt; variable has the same purpose as the &amp;lt;code&amp;gt;this&amp;lt;/code&amp;gt; variable in languages like PHP, Java, JavaScript, and C++.&lt;br /&gt;
*There is no need for a &amp;lt;code&amp;gt;new&amp;lt;/code&amp;gt; keyword in Python.&lt;br /&gt;
&lt;br /&gt;
= Footnotes =&lt;br /&gt;
# {{note|interpreted}}This is an oversimplification. If you're interested, here's a quick explanation of how: In CPython (the reference implementation of Python) programs are compiled to bytecode, an intermediate representation, which is then interpreted.&lt;br /&gt;
[[Category:Module 4]]&lt;/div&gt;</summary>
		<author><name>Alex</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Python&amp;diff=2519</id>
		<title>Python</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Python&amp;diff=2519"/>
		<updated>2018-02-19T17:33:18Z</updated>

		<summary type="html">&lt;p&gt;Alex: /* Python 2 vs Python 3 */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Languages like Java and C++ have lots of rules regarding variable types, syntax, return values, and so on. These can be cumbersome when you are trying to write short, quick scripts to perform tasks. This is where a ''scripting language'' comes into play.&lt;br /&gt;
&lt;br /&gt;
'''Python''' is a language well-suited to rapid prototype development. It is generally an ''interpreted language'', which means that, generally speaking, a Python program is converted line by line into instructions for the computer to execute as the program runs, instead of having a separate compilation step beforehand {{ref|interpreted}}. The syntax is clean, and it is usually clear at first glance what is going on when you write in Python.&lt;br /&gt;
&lt;br /&gt;
= Installation =&lt;br /&gt;
&lt;br /&gt;
Python may already be installed on your system. To see whether or not it is, enter the command&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ python --version&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If it tells you a version of Python '''greater than or equal to 3.5''' then you're good to go. If not, you need to do a quick package install to get it up and running. Using yum, it's just &amp;lt;code&amp;gt;sudo yum install python35; sudo alternatives --set python /usr/bin/python3&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
==== Python 2 vs Python 3 ====&lt;br /&gt;
&lt;br /&gt;
In 2008, a new version of Python – Python 3 – was released, with a number changes that made it incompatible with the previous version, Python 2. For several years, the Python community was slow to make the change to Python 3, but today, Python 3 is ''the'' standard for new code. The ''only'' reason to write Python 2 code today is because you have to work in an environment or with libraries that do not support Python 3, and that situation is becoming increasingly rare.&lt;br /&gt;
&lt;br /&gt;
'''For CSE 330 (and this guide), you ''must'' use Python 3.6 or greater.'''&lt;br /&gt;
&lt;br /&gt;
=== Pip ===&lt;br /&gt;
&lt;br /&gt;
Linux distributions have package managers like ''Apt'', ''Yum'', and ''YaST''. PHP has a package manager named ''PEAR''. It's now time to introduce Python's leading package manager: '''pip'''.&lt;br /&gt;
&lt;br /&gt;
You need to install Pip from Yum before you can use it. The package is called &amp;lt;code&amp;gt;python-pip&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Once you have pip installed, you can use it to install Python packages. Use the &amp;lt;code&amp;gt;pip-python&amp;lt;/code&amp;gt; command:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ pip-python install package_name # RHEL&lt;br /&gt;
$ pip install package_name # Debian&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
= Running Python =&lt;br /&gt;
&lt;br /&gt;
There are two common ways to run Python code: via the console, and via a Python script file.&lt;br /&gt;
&lt;br /&gt;
=== The Python Console ===&lt;br /&gt;
&lt;br /&gt;
The Python console enables you to experiment with code without opening a text editor. To enter the Python console, simply type the ''python'' command at the terminal:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ python&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
To leave the interactive console, either type &amp;lt;code&amp;gt;quit()&amp;lt;/code&amp;gt; or press &amp;lt;code&amp;gt;Ctrl-D&amp;lt;/code&amp;gt; (on both Mac and Windows).&lt;br /&gt;
&lt;br /&gt;
=== Python Script Files ===&lt;br /&gt;
&lt;br /&gt;
You can also save Python script files for later use. The extension for Python scripts is &amp;lt;code&amp;gt;*.py&amp;lt;/code&amp;gt;. To run a script file, simply feed its path as an argument to the &amp;lt;code&amp;gt;python&amp;lt;/code&amp;gt; command in Terminal:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ python my_script.py&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Python Syntax and Language Components =&lt;br /&gt;
&lt;br /&gt;
This section contains a very brief overview of Python syntax. For a more comprehensive introduction, see [http://docs.python.org/tutorial/ the Python docs].&lt;br /&gt;
&lt;br /&gt;
=== Python's Type System ===&lt;br /&gt;
&lt;br /&gt;
Python is a dynamically-typed, strongly-typed, and duck-typed language. What does that mean? Well, let's take those categories one by one:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;ol&amp;gt;&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
'''Dynamic typing''', in contrast to ''static typing'' means that the types of objects can be changed. In Java, for instance, if you tried to write the following code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
int c = 2;&lt;br /&gt;
c = &amp;quot;fish&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Your code would fail to compile, because the Java compiler wouldn't allow you to change the type of the variable &amp;lt;code&amp;gt;c&amp;lt;/code&amp;gt; from &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt; to &amp;lt;code&amp;gt;String&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Python, however, is just fine with that. You can write:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
c = 2&lt;br /&gt;
c = &amp;quot;fish&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
And Python will happily do what you ask.&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
'''Strong typing''', in contrast to ''weak typing'', means, roughly, that a language won't implicitly convert types for you. So far, you've used a lot of PHP, which is very weakly typed. For example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;php&amp;quot;&amp;gt;&lt;br /&gt;
echo &amp;quot;10&amp;quot; . 2;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In PHP, this works just fine. The PHP interpreter sees that &amp;lt;code&amp;gt;2&amp;lt;/code&amp;gt; is an int, and silently converts it to a string for you, so that &amp;lt;code&amp;gt;&amp;quot;10&amp;quot;. 2&amp;lt;/code&amp;gt; equals &amp;lt;code&amp;gt;&amp;quot;102&amp;quot;&amp;lt;/code&amp;gt;. The problem with weak typing is that it can make it unclear to the programmer why things are happening the way they are. For instance, in PHP, the expression &amp;lt;code&amp;gt;&amp;quot;10&amp;quot; == 10&amp;lt;/code&amp;gt; is true, which can be less than obvious. Python, however, tries to disallow that sort of thing:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
&amp;quot;10&amp;quot; + &amp;quot;10&amp;quot; # Allowed – concatenates the two strings.&lt;br /&gt;
10   +  10  # Allowed – adds the two ints.&lt;br /&gt;
&amp;quot;10&amp;quot; +  10  # Not allowed – raises a TypeError&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Perhaps the one exception to this rule is the relationship between numeric types; it's perfectly fine to add a float to an int, for example.&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
'''Duck-typing''' is a little bit different than the other categories, because it doesn't really have a direct opposite. Essentially, duck-typing is the philosophy that &amp;quot;If it walks like a duck, and quacks like a duck, it's a duck.&amp;quot; In programming terms, that means that we often don't care what type an object is, as long as it can do the things we ask.&lt;br /&gt;
&lt;br /&gt;
Let's look at an example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
# This function doubles the value it's passed.&lt;br /&gt;
def double(thing):&lt;br /&gt;
    return thing + thing&lt;br /&gt;
double(10) # Returns 20&lt;br /&gt;
double(&amp;quot;fish&amp;quot;) # Returns &amp;quot;fishfish&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If this were Java, we'd have to write two different methods here: one for things of type &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt;, and one for things of type &amp;lt;code&amp;gt;String&amp;lt;/code&amp;gt;. Since this is Python, though, we don't have to do that. Instead, Python lets us say, essentially: &amp;quot;This function uses the &amp;lt;code&amp;gt;+&amp;lt;/code&amp;gt; operator, so you can pass whatever object you want to the function, as long as the function supports the &amp;lt;code&amp;gt;+&amp;lt;/code&amp;gt; operator&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
To quote [https://groups.google.com/forum/?hl=en#!msg/comp.lang.python/CCs2oJdyuzc/NYjla5HKMOIJ Alex Martelli], one of the key people in the Python project,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;blockquote&amp;gt;&lt;br /&gt;
&amp;quot;[Don't] check whether it IS-a duck: check whether it QUACKS-like-a duck, WALKS-like-a duck, etc, etc, depending on exactly what subset of duck-like behaviour you need.&amp;quot;&lt;br /&gt;
&amp;lt;/blockquote&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&amp;lt;/ol&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Basic Types ===&lt;br /&gt;
&lt;br /&gt;
In Python, the basic scalar types are:&lt;br /&gt;
&lt;br /&gt;
# &amp;lt;code&amp;gt;str&amp;lt;/code&amp;gt; – a string.&lt;br /&gt;
# &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt; – an integer object with unlimited digits.&lt;br /&gt;
# &amp;lt;code&amp;gt;bool&amp;lt;/code&amp;gt; – a Boolean value.&lt;br /&gt;
# &amp;lt;code&amp;gt;float&amp;lt;/code&amp;gt; – a floating point number; generally equivalent to &amp;lt;code&amp;gt;double&amp;lt;/code&amp;gt; in Java.&lt;br /&gt;
# &amp;lt;code&amp;gt;bytes&amp;lt;/code&amp;gt; – represents a collection of bytes; you're unlikely to use this often.&lt;br /&gt;
&lt;br /&gt;
Casting is done in the C style - to parse an &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt; from a string, for instance, you'd write &amp;lt;code&amp;gt;int(&amp;quot;123&amp;quot;)&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== Basic Control Flow ===&lt;br /&gt;
In Python, blocks of code are delineated using colons and indentation instead of curly braces. '''''That means that proper indentation is mandatory.''''' Every time you use a colon, you must indent one step further, and every time a block ends, you must unindent a step.&lt;br /&gt;
&lt;br /&gt;
Conditional statements are done using the &amp;lt;code&amp;gt;if&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;elif&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;else&amp;lt;/code&amp;gt; operators, like in the example below - pay attention to the indentation:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
cookies_left = 10&lt;br /&gt;
cake_slices_left = 3&lt;br /&gt;
if cookies_left &amp;gt; 10:&lt;br /&gt;
    print(&amp;quot;Lots of cookies!&amp;quot;)&lt;br /&gt;
elif cookies_left &amp;gt; 8:&lt;br /&gt;
    print(&amp;quot;Plenty left!&amp;quot;)&lt;br /&gt;
elif cookies_left == 5:&lt;br /&gt;
    print(&amp;quot;Halfway done!&amp;quot;)&lt;br /&gt;
else:&lt;br /&gt;
    if cake_slices_left == 3:&lt;br /&gt;
        print(&amp;quot;Lots of cake!&amp;quot;)&lt;br /&gt;
    elif cake_slices_left == 2:&lt;br /&gt;
        print(&amp;quot;One slice gone!&amp;quot;)&lt;br /&gt;
    else:&lt;br /&gt;
        print(&amp;quot;Little to no cake left!&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== An Example Python Script ===&lt;br /&gt;
&lt;br /&gt;
In my mind, there's no better way to learn Python than to be immersed in a simple example script.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
print(&amp;quot;Hello World&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
fruits = [&amp;quot;apple&amp;quot;, &amp;quot;banana&amp;quot;, &amp;quot;cherry&amp;quot;, &amp;quot;date&amp;quot;]&lt;br /&gt;
for fruit in fruits:&lt;br /&gt;
    print(f&amp;quot;I always love to eat a fresh {fruit}&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Map the fruits list over to a new list containing the length of the fruit strings:&lt;br /&gt;
fruit_size = [len(fruit) for fruit in fruits]&lt;br /&gt;
&lt;br /&gt;
avg_fruit_size = sum(fruit_size) / len(fruit_size)&lt;br /&gt;
print(f&amp;quot;The average fruit string length is {avg_fruit_size:.2f}.&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Some things to notice:&lt;br /&gt;
&lt;br /&gt;
* Printing is achieved using the &amp;lt;code&amp;gt;print()&amp;lt;/code&amp;gt; function.&lt;br /&gt;
* Comments start with a pound symbol &amp;lt;code&amp;gt;#&amp;lt;/code&amp;gt;.&lt;br /&gt;
* We can transform/map a list to a new list in just one line!&lt;br /&gt;
&lt;br /&gt;
For some more examples, see [https://wiki.python.org/moin/SimplePrograms the Python wiki].&lt;br /&gt;
&lt;br /&gt;
=== A Few Gotchas ===&lt;br /&gt;
&lt;br /&gt;
Here are a few things you may not expect when starting out with Python:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;ol&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
Strings can be delimited using either single quotes (&amp;lt;code&amp;gt;'&amp;lt;/code&amp;gt;) or double quotes (&amp;lt;code&amp;gt;&amp;quot;&amp;lt;/code&amp;gt;), so &amp;lt;code&amp;gt;'Python'&amp;lt;/code&amp;gt; is the same as &amp;lt;code&amp;gt;&amp;quot;Python&amp;quot;&amp;lt;/code. You can also use three sets of quotes (&amp;lt;code&amp;gt;'''&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;&amp;quot;&amp;quot;&amp;quot;&amp;lt;/code&amp;gt;) to delineate a multiple-line string, like so:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
long_string = &amp;quot;&amp;quot;&amp;quot;This&lt;br /&gt;
is my&lt;br /&gt;
very long&lt;br /&gt;
multiple-line&lt;br /&gt;
string&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
To compare the equality of two objects, use the &amp;lt;code&amp;gt;==&amp;lt;/code&amp;gt; operator. To compare the identity of two objects (i.e. whether or not they are literally the same object, at the same place in memory), use the &amp;lt;code&amp;gt;is&amp;lt;/code&amp;gt; operator. These correspond, respectively to &amp;lt;code&amp;gt;.equals()&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;==&amp;lt;/code&amp;gt; in Java.&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
The &amp;lt;code&amp;gt;/&amp;lt;/code&amp;gt; operator performs floating-point division, not integer division, even when both its arguments are integers. If you want to do integer division, use the &amp;lt;code&amp;gt;//&amp;lt;/code&amp;gt; operator. Let's look at an example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
9   / 10    == 0.9 # Floating-point division&lt;br /&gt;
9.0 / 10.0  == 0.9 # Floating-point division&lt;br /&gt;
9   // 10   == 0   # Integer division&lt;br /&gt;
9.0 // 10.0 == 0.0 # Integer division, even though the resulting value is a float&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
As discussed in the section [[#Python's_Type_System|Python's Type System]], you can't combine strings and numbers using the &amp;lt;code&amp;gt;+&amp;lt;/code&amp;gt; operator. Instead, you'll have to use one of the following methods of string formatting:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
  &lt;br /&gt;
# Technique 1 – printf-style Formatting&lt;br /&gt;
# This is a classic style of string formatting, used in many programming languages, including in Java's String.format.&lt;br /&gt;
&amp;quot;You scored %d out of %d!&amp;quot; % (score, questions)&lt;br /&gt;
&lt;br /&gt;
# Technique 2 – str.format&lt;br /&gt;
&amp;quot;You scored {} out of {}!&amp;quot;.format(score, questions)&lt;br /&gt;
&lt;br /&gt;
# Technique 3 – f-strings&lt;br /&gt;
# These were only introduced in Python 3.6 but they're very convenient.&lt;br /&gt;
f&amp;quot;You scored {score} out of {questions}!&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# Technique 4 - String Concatenation&lt;br /&gt;
# This is fine for small things, but for more complicated stuff, use one of the other techniques.&lt;br /&gt;
&amp;quot;You scored &amp;quot; + str(score) + &amp;quot; out of &amp;quot; + str(questions) + &amp;quot;!&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&amp;lt;/ol&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Functions ===&lt;br /&gt;
&lt;br /&gt;
Define functions using the &amp;lt;code&amp;gt;def&amp;lt;/code&amp;gt; keyword:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def hello(name):&lt;br /&gt;
    print(f&amp;quot;Hello, {name}!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Invoke functions using parentheses:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
hello(&amp;quot;Batman&amp;quot;)&lt;br /&gt;
hello(&amp;quot;Superman&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Functions can have optional arguments; however, these must come after any required arguments:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def hello(name=&amp;quot;User&amp;quot;):&lt;br /&gt;
    print(f&amp;quot;Hello, {name}!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
hello() # Prints &amp;quot;Hello, User!&amp;quot;&lt;br /&gt;
hello(&amp;quot;Sarah&amp;quot;) # Prints &amp;quot;Hello, Sarah!&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Functions are just regular objects in Python, meaning you can do stuff like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def hello(name=&amp;quot;User&amp;quot;):&lt;br /&gt;
    print(f&amp;quot;Hello, {name}!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
greeting = hello&lt;br /&gt;
&lt;br /&gt;
greeting(&amp;quot;Siwei&amp;quot;) # Prints &amp;quot;Hello, Siwei!&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Collection Types ===&lt;br /&gt;
Python has a few basic, built-in collection types. They each have their own special use cases, but they share a lot of similarities. All built-in data structures in Python are zero-indexed, for instance.&lt;br /&gt;
&lt;br /&gt;
To obtain the number of elements in a collection, use the &amp;lt;code&amp;gt;len()&amp;lt;/code&amp;gt; function, like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish'] # This is a list; you'll learn about them below.&lt;br /&gt;
&lt;br /&gt;
len(pets) # Returns 3&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To check if a collection contains an item, use the &amp;lt;code&amp;gt;in&amp;lt;/code&amp;gt; operator:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish'] # This is a list; you'll learn about them below.&lt;br /&gt;
&lt;br /&gt;
'Dog' in pets # Returns True&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Helpfully, the Python Software Foundation maintains a page containing the asymptotic complexities of important operations on major Python data structures. It's available [https://wiki.python.org/moin/TimeComplexity here].&lt;br /&gt;
&lt;br /&gt;
==== Lists ====&lt;br /&gt;
&lt;br /&gt;
Unlike languages like Java and C, Python's array-like type doesn't have fixed length. Instead, a &amp;lt;code&amp;gt;list&amp;lt;/code&amp;gt; is a dynamic array (like Java's &amp;lt;code&amp;gt;ArrayList&amp;lt;/code&amp;gt;) of objects of any type. Here's an example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = [&amp;quot;Apple&amp;quot;, &amp;quot;Pear&amp;quot;, &amp;quot;Orange&amp;quot;] # Lists can be creating by placing their items between square brackets&lt;br /&gt;
&lt;br /&gt;
random_items = ['Apple', 12312, 2.0, [1, 2, 3]] # Lists can contain objects of different types - even other lists!&lt;br /&gt;
&lt;br /&gt;
pets.append('Turtle') # Adds 'Turtle' to the end of pets&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For the next few examples, we'll be using the following list:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish', 'Turtle', 'Lizard', 'Snake']&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access or assign elements of a list, use the &amp;lt;code&amp;gt;[]&amp;lt;/code&amp;gt; operator.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[0] # Returns 'Dog'&lt;br /&gt;
pets[1] = 'Cow' # Sets pets[1] to 'Cow'&lt;br /&gt;
pets[1] = 'Cat' # Sets pets[1] back to 'Cat' &lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You can also access or assign lists using negative indices, which will return elements starting from the end of the list:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[-1] # Returns 'Snake'&lt;br /&gt;
pets[-2] # Returns 'Lizard'&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You can also use 'slice notation' to obtain or assign subsets of lists:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[start:end] # Returns items from index start to index end - 1.&lt;br /&gt;
pets[start:]    # Returns items from index start to the end of the list, inclusive.&lt;br /&gt;
pets[:end]      # Returns items from the beginning of the list to index end - 1.&lt;br /&gt;
pets[:]         # Returns every item in the list&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
There's also a third, optional argument: &amp;lt;code&amp;gt;step&amp;lt;/code&amp;gt;, which lets you jump over values:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[start:end:step] # Returns items from index start to index end - 1, jumping step values at a time&lt;br /&gt;
&lt;br /&gt;
# Examples:&lt;br /&gt;
pets[1:5:2] # Returns items from index 1 to index 4, jumping 2 at a time, so ['Cat', 'Turtle']&lt;br /&gt;
pets[::3] # Returns all items in the list, jumping 3 at a time, so ['Dog', 'Turtle']&lt;br /&gt;
pets[::-1] # Returns all items in the list, jumping -1 at a time. This reverses the list, so ['Snake', 'Lizard', 'Turtle', 'Fish', 'Cat', 'Dog']&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Lists have all the performance characteristics you'd expect of a dynamic array - constant-time indexing, amortized constant-time appends, and so on.&lt;br /&gt;
&lt;br /&gt;
==== Tuples ====&lt;br /&gt;
&lt;br /&gt;
Python has a special data type called &amp;lt;code&amp;gt;tuple&amp;lt;/code&amp;gt;, which is exactly the same as a list except for the fact that it cannot be modified, so you can't append or replace items.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
cities = ('St. Louis', 'Los Angeles', 'Seattle') # Tuples are defined using parentheses.&lt;br /&gt;
numbers = 1, 2, 3 # You can also omit the parentheses if it's unambiguous&lt;br /&gt;
single_item_tuple = (1,) # To make a tuple with only one item, put a comma after it&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Tuples also enable you to have multiple return values from a function:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def compute_length(string):&lt;br /&gt;
    str_len = len(string)&lt;br /&gt;
    if str_len &amp;lt; 5:&lt;br /&gt;
        return str_len, &amp;quot;short&amp;quot;&lt;br /&gt;
    elif str_len &amp;lt; 40:&lt;br /&gt;
        return str_len, &amp;quot;medium&amp;quot;&lt;br /&gt;
    return str_len, &amp;quot;long&amp;quot;&lt;br /&gt;
&lt;br /&gt;
length, description = compute_length(&amp;quot;Four score and seven years ago&amp;quot;)&lt;br /&gt;
print(f&amp;quot;The {description} string is {length} characters long.&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
The above example also demonstrates Python's if...elif...else conditional structure.&lt;br /&gt;
&lt;br /&gt;
==== Dictionaries ====&lt;br /&gt;
&lt;br /&gt;
Python has another datatype called a '''dictionary''' (or &amp;lt;code&amp;gt;dict&amp;lt;/code&amp;gt;, for short), which are like ''Maps'' in Java, ''associative arrays'' in PHP, and ''object literals'' in JavaScript (coming up soon in Module 6). Essentially, they enable you to use any immutable object as the key in your data structure. &amp;lt;code&amp;gt;dict&amp;lt;/code&amp;gt; objects can be created using either the &amp;lt;code&amp;gt;dict&amp;lt;/code&amp;gt; function, or by placing items between curly braces, separating keys and values using colons:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits_in_bowl = {&lt;br /&gt;
    'apple': 4,&lt;br /&gt;
    'banana': 2,&lt;br /&gt;
    'cherry': 0,&lt;br /&gt;
    'date': 12&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
apple_count = fruits_in_bowl['apple'] # Equals 4&lt;br /&gt;
&lt;br /&gt;
fruits_in_bowl['pear'] = 9 # Sets 'pear' in the dictionary to 9.&lt;br /&gt;
&lt;br /&gt;
for fruit, num in fruits_in_bowl.items():&lt;br /&gt;
    print(f&amp;quot;There are {num} {fruit}(s) in the bowl.&amp;quot; % (num, fruit))&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If you only want the keys from a dictionary, you can just iterate over it directly, like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
for fruit in fruits_in_bowl:&lt;br /&gt;
    print(fruit)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If you want only the values but not the keys from a dictionary, use &amp;lt;code&amp;gt;my_dictionary.values()&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
==== Sets ==== &lt;br /&gt;
A &amp;lt;code&amp;gt;set&amp;lt;/code&amp;gt; is an unordered collection of unique items, with constant-time membership checking. &lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = {'Apple', 'Apple', 'Apple', 'Pear'} # The set removes duplicates, so it will only contain {'Apple', 'Pear'}&lt;br /&gt;
fruits = set(['Apple', 'Apple', 'Apple', 'Pear']) # This line transforms a list into a set&lt;br /&gt;
print('Apple' in fruits) # Constant-time!&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Loops ===&lt;br /&gt;
&lt;br /&gt;
In Python, while loops are written like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
i = 0&lt;br /&gt;
while i &amp;lt; 10:&lt;br /&gt;
    i += 1&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
For loops are written like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish']&lt;br /&gt;
&lt;br /&gt;
for pet in pets:&lt;br /&gt;
    print(pet)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
To iterate over a range of numbers, you can use the convenient &amp;lt;code&amp;gt;range&amp;lt;/code&amp;gt; function, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
for i in range(20, 30): # If you omit the first argument to range, it's assumed to be zero.&lt;br /&gt;
    print(i)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Note that &amp;lt;code&amp;gt;range&amp;lt;/code&amp;gt; provides a closed-open range. That is to say, it is inclusive of its lower bound and exclusive of its upper bound. To be very explicit about it:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
list(range(3, 6)) == [3, 4, 5]&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Unlike in other languages you may know, the following is not good practice in Python:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish']&lt;br /&gt;
&lt;br /&gt;
# BAD PRACTICE. DO NOT USE.&lt;br /&gt;
for i in range(len(pets)):&lt;br /&gt;
    pet = pets[i]&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Instead, if you need to access both a variable and its index, use the &amp;lt;code&amp;gt;enumerate&amp;lt;/code&amp;gt; function, which allows you to iterate through a group of items, along with their indexes, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish']&lt;br /&gt;
&lt;br /&gt;
for index, pet in enumerate(pets):&lt;br /&gt;
    print(f&amp;quot;{pet} at index {index}&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Generator Expressions and Comprehensions ===&lt;br /&gt;
&lt;br /&gt;
A generator is a special kind of object that, basically, represents a collection of items using a value and a function for generating the next value in the collection. In other words, it's a way of creating something that behaves like a list, but which only generates one value at a time, and discards a value when it's done with it. Say, for example, you wanted to do an operation on 10,000,000,000,000 numbers. You could put them all in a list, then iterate over the list, but that would take a lot of memory, plus you'd have to create and fill the entire list before beginning to actually work on your problem. Instead, you'd probably be better off using a generator; telling the computer, essentially: “The starting value is 0. When I ask for the next number in the collection, add 1 to current value and give me that.”&lt;br /&gt;
&lt;br /&gt;
A generator expression is an expression that is evaluated to create a generator. They're super useful. Generator expressions can take two forms – they can be used with and without a condition:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
(EXPRESSION for VARIABLE in ITERABLE) # Unconditional&lt;br /&gt;
(EXPRESSION for VARIABLE in ITERABLE if CONDITION) # Conditional&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
For our purposes, you can think of an iterable as anything you can do a for loop over. Let's take a look at a generator expression in use:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
double_even_digits = (number * 2 for number in range(10) if number % 2 == 0)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
That line says that &amp;lt;code&amp;gt;double_even_digits&amp;lt;/code&amp;gt; is every even number between 0 and 10 multiplied by two. Simple enough, right? If we wanted to use all of the numbers, not just the even ones, we could simply remove the if statement at the end of the expression.&lt;br /&gt;
&lt;br /&gt;
Here's the thing, though: if you were to print &amp;lt;code&amp;gt;double_even_digits&amp;lt;/code&amp;gt;, instead of a nice bunch of numbers, you'd get something that looks like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&amp;lt;generator object &amp;lt;genexpr&amp;gt;&amp;lt;code&amp;gt;at 0x107fc92b0&amp;gt;&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
That's because generators are lazy! They don't generate their values until those values are needed, and they discard values once they're no longer needed. As a result, '''you can only iterate over a generator once'''. In this case, you can't print out the whole generator, because it hasn't generated all the values yet. You can, however, iterate over the generator, and print its values one at a time, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
for number in double_even_digits:&lt;br /&gt;
    print(number)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
You can also make a list out of the generator, which will go through all the items in the generator and put them in a list, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
even_number_list = list(double_even_digits)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
That's actually a great segue to the second topic of this section: comprehensions. A comprehension is just a prettier way to make lists, sets, and dicts out of a generator expressions.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
# If you want a list:&lt;br /&gt;
list(i for i in range(10) if i % 2 == 0) # Don't do this&lt;br /&gt;
[i for i in range(10) if i % 2 == 0] # Use a list comprehension instead!&lt;br /&gt;
&lt;br /&gt;
# If you want a set:&lt;br /&gt;
set(i for i in range(10) if i % 2 == 0) # Don't do this&lt;br /&gt;
{i for i in range(10) if i % 2 == 0} # Use a set comprehension instead!&lt;br /&gt;
&lt;br /&gt;
# If you want a dict:&lt;br /&gt;
dict((i, i + 1) for i in range(10) if i % 2 == 0) # Don't do this&lt;br /&gt;
{i : i + 1 for i in range(10) if i % 2 == 0} # Use a dict comprehension instead!&lt;br /&gt;
&lt;br /&gt;
# If you want a tuple:&lt;br /&gt;
tuple(i for i in range(10) if i % 2 == 0) # Unfortunately, there's no better way to do this&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
In general, generators and comprehensions should be used whenever possible - they're the fastest and easiest way to build collections. If you ever see yourself writing code like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
# BAD PRACTICE! DO NOT USE!&lt;br /&gt;
digits = []&lt;br /&gt;
for digit in range(10):&lt;br /&gt;
    digits.append(digit)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Don't do it! Instead, use a generator expression or comprehension, as appropriate. A good way to decide whether a generator expression or comprehension is better for this situation is that, if you're just going to be iterating over your collection once, you should use an generator expression. If not, use a comprehension.&lt;br /&gt;
&lt;br /&gt;
=== Sorting ===&lt;br /&gt;
&lt;br /&gt;
Sorting in Python is frequently performed using the &amp;lt;code&amp;gt;sorted&amp;lt;/code&amp;gt; function, which takes two arguments: an iterable (anything you can do a for-loop over, including lists and tuples) and a function used to evaluate each item. If the function is omitted, Python will try to sort the lists by value.&lt;br /&gt;
&lt;br /&gt;
The following example demonstrates using an inline function, which Python calls a ''lambda''.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = ['apple', 'banana', 'cherry', 'date']&lt;br /&gt;
&lt;br /&gt;
# sort the fruits by string length&lt;br /&gt;
new_fruits = sorted(fruits, key=lambda v: len(v) // 2)&lt;br /&gt;
&lt;br /&gt;
print(new_fruits) # ['date', 'apple', 'banana', 'cherry']&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Alternatively, you can sort a &amp;lt;code&amp;gt;list&amp;lt;/code&amp;gt; using the &amp;lt;code&amp;gt;.sort&amp;lt;/code&amp;gt; method. This is faster than calling &amp;lt;code&amp;gt;sorted&amp;lt;/code&amp;gt;, but it modifies the list in-place and returns &amp;lt;code&amp;gt;None&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = ['apple', 'banana', 'cherry', 'date']&lt;br /&gt;
fruits.sort()&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
=== Import ===&lt;br /&gt;
&lt;br /&gt;
If you want to use functions from other libraries (including ones that you install using pip), use &amp;lt;code&amp;gt;import&amp;lt;/code&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
import time&lt;br /&gt;
&lt;br /&gt;
current_time = time.localtime()&lt;br /&gt;
print(time.strftime('%a, %d %b %Y %H:%M:%S', current_time))&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If you want to pull the functions out of their namespace, you can use &amp;lt;code&amp;gt;from ___ import ___&amp;lt;/code&amp;gt; syntax:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
from time import localtime, strftime&lt;br /&gt;
&lt;br /&gt;
current_time = localtime()&lt;br /&gt;
print(strftime('%a, %d %b %Y %H:%M:%S', current_time))&lt;br /&gt;
&lt;br /&gt;
# Be aware that this technique, although convenient, may cause unexpected behavior if the function names that you're pulling out of the namespace are already used for other purposes in Python.&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
=== File I/O ===&lt;br /&gt;
&lt;br /&gt;
You can read an entire file into a variable like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
f = open(&amp;quot;example.txt&amp;quot;)&lt;br /&gt;
file_contents = f.read()&lt;br /&gt;
&lt;br /&gt;
f.close() # free up memory when we're finished with the file&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
A better option is to use a with-block, which handles opening and closing the file for you automatically:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
with open(&amp;quot;example.txt&amp;quot;) as f:&lt;br /&gt;
    file_contents = f.read()&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
You can read a file line-by-line like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
with open(&amp;quot;example.txt&amp;quot;) as f:&lt;br /&gt;
    for line in f:&lt;br /&gt;
        print(&amp;quot;Read line: %s&amp;quot; % line.rstrip())&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
You can write to a file like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
with open(&amp;quot;example.txt&amp;quot;, &amp;quot;w&amp;quot;) as f:&lt;br /&gt;
    f.write(&amp;quot;Hello\nWorld\n&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
=== Command-Line Arguments ===&lt;br /&gt;
&lt;br /&gt;
Command line arguments are accessible in the variable &amp;lt;code&amp;gt;sys.argv&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
The following example shows a program that expects a filename as its argument, and it prints a usage message if the argument is not present ([https://stackoverflow.com/questions/983201/python-and-sys-argv source]).&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
import sys, os&lt;br /&gt;
&lt;br /&gt;
if len(sys.argv) &amp;lt; 2:&lt;br /&gt;
    sys.exit(f&amp;quot;Usage: {sys.argv[0]} filename&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
filename = sys.argv[1]&lt;br /&gt;
&lt;br /&gt;
if not os.path.exists(filename):&lt;br /&gt;
    sys.exit(f&amp;quot;Error: File '{sys.argv[1]}' not found&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Object-Oriented Programming ===&lt;br /&gt;
&lt;br /&gt;
You can define and use a class like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
class Food:&lt;br /&gt;
    # constructor:&lt;br /&gt;
    def __init__(self, name):&lt;br /&gt;
        self.name = name&lt;br /&gt;
    &lt;br /&gt;
    def format_name(self):&lt;br /&gt;
        return f&amp;quot;Gotta love to eat {self.name}&amp;quot;&lt;br /&gt;
&lt;br /&gt;
class Fruit(Food):&lt;br /&gt;
    def format_name(self):&lt;br /&gt;
        return f&amp;quot;{Food.format_name(self)} (fruit)&amp;quot;&lt;br /&gt;
&lt;br /&gt;
fruit = Fruit(&amp;quot;Cherry&amp;quot;)&lt;br /&gt;
print(fruit.format_name())&lt;br /&gt;
print(Food.get_definition())&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
This is the same example as in [[PHP#Object-Oriented_Programming|the PHP guide]].&lt;br /&gt;
&lt;br /&gt;
Some things to notice:&lt;br /&gt;
&lt;br /&gt;
* Instance methods ''always'' take &amp;lt;code&amp;gt;self&amp;lt;/code&amp;gt; as their first argument, followed by any number of additional parameters. This can be misleading for programmers familiar with other languages, because the number of arguments you feed to the method is actually ''one less than'' the number of declared parameters. Whenever you call a method on a class instance, that instance is implicitly fed into the explicitly-declared &amp;lt;code&amp;gt;self&amp;lt;/code&amp;gt; parameter of the method.&lt;br /&gt;
*: Note that the &amp;lt;code&amp;gt;self&amp;lt;/code&amp;gt; variable has the same purpose as the &amp;lt;code&amp;gt;this&amp;lt;/code&amp;gt; variable in languages like PHP, Java, JavaScript, and C++.&lt;br /&gt;
*There is no need for a &amp;lt;code&amp;gt;new&amp;lt;/code&amp;gt; keyword in Python.&lt;br /&gt;
&lt;br /&gt;
= Footnotes =&lt;br /&gt;
# {{note|interpreted}}This is an oversimplification. If you're interested, here's a quick explanation of how: In CPython (the reference implementation of Python) programs are compiled to bytecode, an intermediate representation, which is then interpreted.&lt;br /&gt;
[[Category:Module 4]]&lt;/div&gt;</summary>
		<author><name>Alex</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Python&amp;diff=2518</id>
		<title>Python</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Python&amp;diff=2518"/>
		<updated>2018-02-19T17:32:34Z</updated>

		<summary type="html">&lt;p&gt;Alex: /* Tuples */  Format strings&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Languages like Java and C++ have lots of rules regarding variable types, syntax, return values, and so on. These can be cumbersome when you are trying to write short, quick scripts to perform tasks. This is where a ''scripting language'' comes into play.&lt;br /&gt;
&lt;br /&gt;
'''Python''' is a language well-suited to rapid prototype development. It is generally an ''interpreted language'', which means that, generally speaking, a Python program is converted line by line into instructions for the computer to execute as the program runs, instead of having a separate compilation step beforehand {{ref|interpreted}}. The syntax is clean, and it is usually clear at first glance what is going on when you write in Python.&lt;br /&gt;
&lt;br /&gt;
= Installation =&lt;br /&gt;
&lt;br /&gt;
Python may already be installed on your system. To see whether or not it is, enter the command&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ python --version&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If it tells you a version of Python '''greater than or equal to 3.5''' then you're good to go. If not, you need to do a quick package install to get it up and running. Using yum, it's just &amp;lt;code&amp;gt;sudo yum install python35; sudo alternatives --set python /usr/bin/python3&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
==== Python 2 vs Python 3 ====&lt;br /&gt;
&lt;br /&gt;
In 2008, a new version of Python – Python 3 – was released, with a number changes that made it incompatible with the previous version, Python 2. For several years, the Python community was slow to make the change to Python 3, but today, Python 3 is ''the'' standard for new code. The ''only'' reason to write Python 2 code today is because you have to work in an environment or with libraries that do not support Python 3, and that situation is becoming increasingly rare.&lt;br /&gt;
&lt;br /&gt;
'''For CSE 330 (and this guide), you ''must'' use Python 3.5 or greater.'''&lt;br /&gt;
&lt;br /&gt;
=== Pip ===&lt;br /&gt;
&lt;br /&gt;
Linux distributions have package managers like ''Apt'', ''Yum'', and ''YaST''. PHP has a package manager named ''PEAR''. It's now time to introduce Python's leading package manager: '''pip'''.&lt;br /&gt;
&lt;br /&gt;
You need to install Pip from Yum before you can use it. The package is called &amp;lt;code&amp;gt;python-pip&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Once you have pip installed, you can use it to install Python packages. Use the &amp;lt;code&amp;gt;pip-python&amp;lt;/code&amp;gt; command:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ pip-python install package_name # RHEL&lt;br /&gt;
$ pip install package_name # Debian&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
= Running Python =&lt;br /&gt;
&lt;br /&gt;
There are two common ways to run Python code: via the console, and via a Python script file.&lt;br /&gt;
&lt;br /&gt;
=== The Python Console ===&lt;br /&gt;
&lt;br /&gt;
The Python console enables you to experiment with code without opening a text editor. To enter the Python console, simply type the ''python'' command at the terminal:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ python&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
To leave the interactive console, either type &amp;lt;code&amp;gt;quit()&amp;lt;/code&amp;gt; or press &amp;lt;code&amp;gt;Ctrl-D&amp;lt;/code&amp;gt; (on both Mac and Windows).&lt;br /&gt;
&lt;br /&gt;
=== Python Script Files ===&lt;br /&gt;
&lt;br /&gt;
You can also save Python script files for later use. The extension for Python scripts is &amp;lt;code&amp;gt;*.py&amp;lt;/code&amp;gt;. To run a script file, simply feed its path as an argument to the &amp;lt;code&amp;gt;python&amp;lt;/code&amp;gt; command in Terminal:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ python my_script.py&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Python Syntax and Language Components =&lt;br /&gt;
&lt;br /&gt;
This section contains a very brief overview of Python syntax. For a more comprehensive introduction, see [http://docs.python.org/tutorial/ the Python docs].&lt;br /&gt;
&lt;br /&gt;
=== Python's Type System ===&lt;br /&gt;
&lt;br /&gt;
Python is a dynamically-typed, strongly-typed, and duck-typed language. What does that mean? Well, let's take those categories one by one:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;ol&amp;gt;&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
'''Dynamic typing''', in contrast to ''static typing'' means that the types of objects can be changed. In Java, for instance, if you tried to write the following code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
int c = 2;&lt;br /&gt;
c = &amp;quot;fish&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Your code would fail to compile, because the Java compiler wouldn't allow you to change the type of the variable &amp;lt;code&amp;gt;c&amp;lt;/code&amp;gt; from &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt; to &amp;lt;code&amp;gt;String&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Python, however, is just fine with that. You can write:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
c = 2&lt;br /&gt;
c = &amp;quot;fish&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
And Python will happily do what you ask.&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
'''Strong typing''', in contrast to ''weak typing'', means, roughly, that a language won't implicitly convert types for you. So far, you've used a lot of PHP, which is very weakly typed. For example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;php&amp;quot;&amp;gt;&lt;br /&gt;
echo &amp;quot;10&amp;quot; . 2;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In PHP, this works just fine. The PHP interpreter sees that &amp;lt;code&amp;gt;2&amp;lt;/code&amp;gt; is an int, and silently converts it to a string for you, so that &amp;lt;code&amp;gt;&amp;quot;10&amp;quot;. 2&amp;lt;/code&amp;gt; equals &amp;lt;code&amp;gt;&amp;quot;102&amp;quot;&amp;lt;/code&amp;gt;. The problem with weak typing is that it can make it unclear to the programmer why things are happening the way they are. For instance, in PHP, the expression &amp;lt;code&amp;gt;&amp;quot;10&amp;quot; == 10&amp;lt;/code&amp;gt; is true, which can be less than obvious. Python, however, tries to disallow that sort of thing:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
&amp;quot;10&amp;quot; + &amp;quot;10&amp;quot; # Allowed – concatenates the two strings.&lt;br /&gt;
10   +  10  # Allowed – adds the two ints.&lt;br /&gt;
&amp;quot;10&amp;quot; +  10  # Not allowed – raises a TypeError&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Perhaps the one exception to this rule is the relationship between numeric types; it's perfectly fine to add a float to an int, for example.&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
'''Duck-typing''' is a little bit different than the other categories, because it doesn't really have a direct opposite. Essentially, duck-typing is the philosophy that &amp;quot;If it walks like a duck, and quacks like a duck, it's a duck.&amp;quot; In programming terms, that means that we often don't care what type an object is, as long as it can do the things we ask.&lt;br /&gt;
&lt;br /&gt;
Let's look at an example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
# This function doubles the value it's passed.&lt;br /&gt;
def double(thing):&lt;br /&gt;
    return thing + thing&lt;br /&gt;
double(10) # Returns 20&lt;br /&gt;
double(&amp;quot;fish&amp;quot;) # Returns &amp;quot;fishfish&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If this were Java, we'd have to write two different methods here: one for things of type &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt;, and one for things of type &amp;lt;code&amp;gt;String&amp;lt;/code&amp;gt;. Since this is Python, though, we don't have to do that. Instead, Python lets us say, essentially: &amp;quot;This function uses the &amp;lt;code&amp;gt;+&amp;lt;/code&amp;gt; operator, so you can pass whatever object you want to the function, as long as the function supports the &amp;lt;code&amp;gt;+&amp;lt;/code&amp;gt; operator&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
To quote [https://groups.google.com/forum/?hl=en#!msg/comp.lang.python/CCs2oJdyuzc/NYjla5HKMOIJ Alex Martelli], one of the key people in the Python project,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;blockquote&amp;gt;&lt;br /&gt;
&amp;quot;[Don't] check whether it IS-a duck: check whether it QUACKS-like-a duck, WALKS-like-a duck, etc, etc, depending on exactly what subset of duck-like behaviour you need.&amp;quot;&lt;br /&gt;
&amp;lt;/blockquote&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&amp;lt;/ol&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Basic Types ===&lt;br /&gt;
&lt;br /&gt;
In Python, the basic scalar types are:&lt;br /&gt;
&lt;br /&gt;
# &amp;lt;code&amp;gt;str&amp;lt;/code&amp;gt; – a string.&lt;br /&gt;
# &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt; – an integer object with unlimited digits.&lt;br /&gt;
# &amp;lt;code&amp;gt;bool&amp;lt;/code&amp;gt; – a Boolean value.&lt;br /&gt;
# &amp;lt;code&amp;gt;float&amp;lt;/code&amp;gt; – a floating point number; generally equivalent to &amp;lt;code&amp;gt;double&amp;lt;/code&amp;gt; in Java.&lt;br /&gt;
# &amp;lt;code&amp;gt;bytes&amp;lt;/code&amp;gt; – represents a collection of bytes; you're unlikely to use this often.&lt;br /&gt;
&lt;br /&gt;
Casting is done in the C style - to parse an &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt; from a string, for instance, you'd write &amp;lt;code&amp;gt;int(&amp;quot;123&amp;quot;)&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== Basic Control Flow ===&lt;br /&gt;
In Python, blocks of code are delineated using colons and indentation instead of curly braces. '''''That means that proper indentation is mandatory.''''' Every time you use a colon, you must indent one step further, and every time a block ends, you must unindent a step.&lt;br /&gt;
&lt;br /&gt;
Conditional statements are done using the &amp;lt;code&amp;gt;if&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;elif&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;else&amp;lt;/code&amp;gt; operators, like in the example below - pay attention to the indentation:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
cookies_left = 10&lt;br /&gt;
cake_slices_left = 3&lt;br /&gt;
if cookies_left &amp;gt; 10:&lt;br /&gt;
    print(&amp;quot;Lots of cookies!&amp;quot;)&lt;br /&gt;
elif cookies_left &amp;gt; 8:&lt;br /&gt;
    print(&amp;quot;Plenty left!&amp;quot;)&lt;br /&gt;
elif cookies_left == 5:&lt;br /&gt;
    print(&amp;quot;Halfway done!&amp;quot;)&lt;br /&gt;
else:&lt;br /&gt;
    if cake_slices_left == 3:&lt;br /&gt;
        print(&amp;quot;Lots of cake!&amp;quot;)&lt;br /&gt;
    elif cake_slices_left == 2:&lt;br /&gt;
        print(&amp;quot;One slice gone!&amp;quot;)&lt;br /&gt;
    else:&lt;br /&gt;
        print(&amp;quot;Little to no cake left!&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== An Example Python Script ===&lt;br /&gt;
&lt;br /&gt;
In my mind, there's no better way to learn Python than to be immersed in a simple example script.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
print(&amp;quot;Hello World&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
fruits = [&amp;quot;apple&amp;quot;, &amp;quot;banana&amp;quot;, &amp;quot;cherry&amp;quot;, &amp;quot;date&amp;quot;]&lt;br /&gt;
for fruit in fruits:&lt;br /&gt;
    print(f&amp;quot;I always love to eat a fresh {fruit}&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Map the fruits list over to a new list containing the length of the fruit strings:&lt;br /&gt;
fruit_size = [len(fruit) for fruit in fruits]&lt;br /&gt;
&lt;br /&gt;
avg_fruit_size = sum(fruit_size) / len(fruit_size)&lt;br /&gt;
print(f&amp;quot;The average fruit string length is {avg_fruit_size:.2f}.&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Some things to notice:&lt;br /&gt;
&lt;br /&gt;
* Printing is achieved using the &amp;lt;code&amp;gt;print()&amp;lt;/code&amp;gt; function.&lt;br /&gt;
* Comments start with a pound symbol &amp;lt;code&amp;gt;#&amp;lt;/code&amp;gt;.&lt;br /&gt;
* We can transform/map a list to a new list in just one line!&lt;br /&gt;
&lt;br /&gt;
For some more examples, see [https://wiki.python.org/moin/SimplePrograms the Python wiki].&lt;br /&gt;
&lt;br /&gt;
=== A Few Gotchas ===&lt;br /&gt;
&lt;br /&gt;
Here are a few things you may not expect when starting out with Python:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;ol&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
Strings can be delimited using either single quotes (&amp;lt;code&amp;gt;'&amp;lt;/code&amp;gt;) or double quotes (&amp;lt;code&amp;gt;&amp;quot;&amp;lt;/code&amp;gt;), so &amp;lt;code&amp;gt;'Python'&amp;lt;/code&amp;gt; is the same as &amp;lt;code&amp;gt;&amp;quot;Python&amp;quot;&amp;lt;/code. You can also use three sets of quotes (&amp;lt;code&amp;gt;'''&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;&amp;quot;&amp;quot;&amp;quot;&amp;lt;/code&amp;gt;) to delineate a multiple-line string, like so:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
long_string = &amp;quot;&amp;quot;&amp;quot;This&lt;br /&gt;
is my&lt;br /&gt;
very long&lt;br /&gt;
multiple-line&lt;br /&gt;
string&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
To compare the equality of two objects, use the &amp;lt;code&amp;gt;==&amp;lt;/code&amp;gt; operator. To compare the identity of two objects (i.e. whether or not they are literally the same object, at the same place in memory), use the &amp;lt;code&amp;gt;is&amp;lt;/code&amp;gt; operator. These correspond, respectively to &amp;lt;code&amp;gt;.equals()&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;==&amp;lt;/code&amp;gt; in Java.&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
The &amp;lt;code&amp;gt;/&amp;lt;/code&amp;gt; operator performs floating-point division, not integer division, even when both its arguments are integers. If you want to do integer division, use the &amp;lt;code&amp;gt;//&amp;lt;/code&amp;gt; operator. Let's look at an example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
9   / 10    == 0.9 # Floating-point division&lt;br /&gt;
9.0 / 10.0  == 0.9 # Floating-point division&lt;br /&gt;
9   // 10   == 0   # Integer division&lt;br /&gt;
9.0 // 10.0 == 0.0 # Integer division, even though the resulting value is a float&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
As discussed in the section [[#Python's_Type_System|Python's Type System]], you can't combine strings and numbers using the &amp;lt;code&amp;gt;+&amp;lt;/code&amp;gt; operator. Instead, you'll have to use one of the following methods of string formatting:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
  &lt;br /&gt;
# Technique 1 – printf-style Formatting&lt;br /&gt;
# This is a classic style of string formatting, used in many programming languages, including in Java's String.format.&lt;br /&gt;
&amp;quot;You scored %d out of %d!&amp;quot; % (score, questions)&lt;br /&gt;
&lt;br /&gt;
# Technique 2 – str.format&lt;br /&gt;
&amp;quot;You scored {} out of {}!&amp;quot;.format(score, questions)&lt;br /&gt;
&lt;br /&gt;
# Technique 3 – f-strings&lt;br /&gt;
# These were only introduced in Python 3.6 but they're very convenient.&lt;br /&gt;
f&amp;quot;You scored {score} out of {questions}!&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# Technique 4 - String Concatenation&lt;br /&gt;
# This is fine for small things, but for more complicated stuff, use one of the other techniques.&lt;br /&gt;
&amp;quot;You scored &amp;quot; + str(score) + &amp;quot; out of &amp;quot; + str(questions) + &amp;quot;!&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&amp;lt;/ol&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Functions ===&lt;br /&gt;
&lt;br /&gt;
Define functions using the &amp;lt;code&amp;gt;def&amp;lt;/code&amp;gt; keyword:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def hello(name):&lt;br /&gt;
    print(f&amp;quot;Hello, {name}!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Invoke functions using parentheses:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
hello(&amp;quot;Batman&amp;quot;)&lt;br /&gt;
hello(&amp;quot;Superman&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Functions can have optional arguments; however, these must come after any required arguments:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def hello(name=&amp;quot;User&amp;quot;):&lt;br /&gt;
    print(f&amp;quot;Hello, {name}!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
hello() # Prints &amp;quot;Hello, User!&amp;quot;&lt;br /&gt;
hello(&amp;quot;Sarah&amp;quot;) # Prints &amp;quot;Hello, Sarah!&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Functions are just regular objects in Python, meaning you can do stuff like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def hello(name=&amp;quot;User&amp;quot;):&lt;br /&gt;
    print(f&amp;quot;Hello, {name}!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
greeting = hello&lt;br /&gt;
&lt;br /&gt;
greeting(&amp;quot;Siwei&amp;quot;) # Prints &amp;quot;Hello, Siwei!&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Collection Types ===&lt;br /&gt;
Python has a few basic, built-in collection types. They each have their own special use cases, but they share a lot of similarities. All built-in data structures in Python are zero-indexed, for instance.&lt;br /&gt;
&lt;br /&gt;
To obtain the number of elements in a collection, use the &amp;lt;code&amp;gt;len()&amp;lt;/code&amp;gt; function, like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish'] # This is a list; you'll learn about them below.&lt;br /&gt;
&lt;br /&gt;
len(pets) # Returns 3&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To check if a collection contains an item, use the &amp;lt;code&amp;gt;in&amp;lt;/code&amp;gt; operator:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish'] # This is a list; you'll learn about them below.&lt;br /&gt;
&lt;br /&gt;
'Dog' in pets # Returns True&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Helpfully, the Python Software Foundation maintains a page containing the asymptotic complexities of important operations on major Python data structures. It's available [https://wiki.python.org/moin/TimeComplexity here].&lt;br /&gt;
&lt;br /&gt;
==== Lists ====&lt;br /&gt;
&lt;br /&gt;
Unlike languages like Java and C, Python's array-like type doesn't have fixed length. Instead, a &amp;lt;code&amp;gt;list&amp;lt;/code&amp;gt; is a dynamic array (like Java's &amp;lt;code&amp;gt;ArrayList&amp;lt;/code&amp;gt;) of objects of any type. Here's an example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = [&amp;quot;Apple&amp;quot;, &amp;quot;Pear&amp;quot;, &amp;quot;Orange&amp;quot;] # Lists can be creating by placing their items between square brackets&lt;br /&gt;
&lt;br /&gt;
random_items = ['Apple', 12312, 2.0, [1, 2, 3]] # Lists can contain objects of different types - even other lists!&lt;br /&gt;
&lt;br /&gt;
pets.append('Turtle') # Adds 'Turtle' to the end of pets&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For the next few examples, we'll be using the following list:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish', 'Turtle', 'Lizard', 'Snake']&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access or assign elements of a list, use the &amp;lt;code&amp;gt;[]&amp;lt;/code&amp;gt; operator.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[0] # Returns 'Dog'&lt;br /&gt;
pets[1] = 'Cow' # Sets pets[1] to 'Cow'&lt;br /&gt;
pets[1] = 'Cat' # Sets pets[1] back to 'Cat' &lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You can also access or assign lists using negative indices, which will return elements starting from the end of the list:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[-1] # Returns 'Snake'&lt;br /&gt;
pets[-2] # Returns 'Lizard'&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You can also use 'slice notation' to obtain or assign subsets of lists:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[start:end] # Returns items from index start to index end - 1.&lt;br /&gt;
pets[start:]    # Returns items from index start to the end of the list, inclusive.&lt;br /&gt;
pets[:end]      # Returns items from the beginning of the list to index end - 1.&lt;br /&gt;
pets[:]         # Returns every item in the list&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
There's also a third, optional argument: &amp;lt;code&amp;gt;step&amp;lt;/code&amp;gt;, which lets you jump over values:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[start:end:step] # Returns items from index start to index end - 1, jumping step values at a time&lt;br /&gt;
&lt;br /&gt;
# Examples:&lt;br /&gt;
pets[1:5:2] # Returns items from index 1 to index 4, jumping 2 at a time, so ['Cat', 'Turtle']&lt;br /&gt;
pets[::3] # Returns all items in the list, jumping 3 at a time, so ['Dog', 'Turtle']&lt;br /&gt;
pets[::-1] # Returns all items in the list, jumping -1 at a time. This reverses the list, so ['Snake', 'Lizard', 'Turtle', 'Fish', 'Cat', 'Dog']&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Lists have all the performance characteristics you'd expect of a dynamic array - constant-time indexing, amortized constant-time appends, and so on.&lt;br /&gt;
&lt;br /&gt;
==== Tuples ====&lt;br /&gt;
&lt;br /&gt;
Python has a special data type called &amp;lt;code&amp;gt;tuple&amp;lt;/code&amp;gt;, which is exactly the same as a list except for the fact that it cannot be modified, so you can't append or replace items.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
cities = ('St. Louis', 'Los Angeles', 'Seattle') # Tuples are defined using parentheses.&lt;br /&gt;
numbers = 1, 2, 3 # You can also omit the parentheses if it's unambiguous&lt;br /&gt;
single_item_tuple = (1,) # To make a tuple with only one item, put a comma after it&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Tuples also enable you to have multiple return values from a function:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def compute_length(string):&lt;br /&gt;
    str_len = len(string)&lt;br /&gt;
    if str_len &amp;lt; 5:&lt;br /&gt;
        return str_len, &amp;quot;short&amp;quot;&lt;br /&gt;
    elif str_len &amp;lt; 40:&lt;br /&gt;
        return str_len, &amp;quot;medium&amp;quot;&lt;br /&gt;
    return str_len, &amp;quot;long&amp;quot;&lt;br /&gt;
&lt;br /&gt;
length, description = compute_length(&amp;quot;Four score and seven years ago&amp;quot;)&lt;br /&gt;
print(f&amp;quot;The {description} string is {length} characters long.&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
The above example also demonstrates Python's if...elif...else conditional structure.&lt;br /&gt;
&lt;br /&gt;
==== Dictionaries ====&lt;br /&gt;
&lt;br /&gt;
Python has another datatype called a '''dictionary''' (or &amp;lt;code&amp;gt;dict&amp;lt;/code&amp;gt;, for short), which are like ''Maps'' in Java, ''associative arrays'' in PHP, and ''object literals'' in JavaScript (coming up soon in Module 6). Essentially, they enable you to use any immutable object as the key in your data structure. &amp;lt;code&amp;gt;dict&amp;lt;/code&amp;gt; objects can be created using either the &amp;lt;code&amp;gt;dict&amp;lt;/code&amp;gt; function, or by placing items between curly braces, separating keys and values using colons:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits_in_bowl = {&lt;br /&gt;
    'apple': 4,&lt;br /&gt;
    'banana': 2,&lt;br /&gt;
    'cherry': 0,&lt;br /&gt;
    'date': 12&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
apple_count = fruits_in_bowl['apple'] # Equals 4&lt;br /&gt;
&lt;br /&gt;
fruits_in_bowl['pear'] = 9 # Sets 'pear' in the dictionary to 9.&lt;br /&gt;
&lt;br /&gt;
for fruit, num in fruits_in_bowl.items():&lt;br /&gt;
    print(f&amp;quot;There are {num} {fruit}(s) in the bowl.&amp;quot; % (num, fruit))&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If you only want the keys from a dictionary, you can just iterate over it directly, like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
for fruit in fruits_in_bowl:&lt;br /&gt;
    print(fruit)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If you want only the values but not the keys from a dictionary, use &amp;lt;code&amp;gt;my_dictionary.values()&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
==== Sets ==== &lt;br /&gt;
A &amp;lt;code&amp;gt;set&amp;lt;/code&amp;gt; is an unordered collection of unique items, with constant-time membership checking. &lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = {'Apple', 'Apple', 'Apple', 'Pear'} # The set removes duplicates, so it will only contain {'Apple', 'Pear'}&lt;br /&gt;
fruits = set(['Apple', 'Apple', 'Apple', 'Pear']) # This line transforms a list into a set&lt;br /&gt;
print('Apple' in fruits) # Constant-time!&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Loops ===&lt;br /&gt;
&lt;br /&gt;
In Python, while loops are written like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
i = 0&lt;br /&gt;
while i &amp;lt; 10:&lt;br /&gt;
    i += 1&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
For loops are written like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish']&lt;br /&gt;
&lt;br /&gt;
for pet in pets:&lt;br /&gt;
    print(pet)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
To iterate over a range of numbers, you can use the convenient &amp;lt;code&amp;gt;range&amp;lt;/code&amp;gt; function, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
for i in range(20, 30): # If you omit the first argument to range, it's assumed to be zero.&lt;br /&gt;
    print(i)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Note that &amp;lt;code&amp;gt;range&amp;lt;/code&amp;gt; provides a closed-open range. That is to say, it is inclusive of its lower bound and exclusive of its upper bound. To be very explicit about it:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
list(range(3, 6)) == [3, 4, 5]&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Unlike in other languages you may know, the following is not good practice in Python:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish']&lt;br /&gt;
&lt;br /&gt;
# BAD PRACTICE. DO NOT USE.&lt;br /&gt;
for i in range(len(pets)):&lt;br /&gt;
    pet = pets[i]&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Instead, if you need to access both a variable and its index, use the &amp;lt;code&amp;gt;enumerate&amp;lt;/code&amp;gt; function, which allows you to iterate through a group of items, along with their indexes, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish']&lt;br /&gt;
&lt;br /&gt;
for index, pet in enumerate(pets):&lt;br /&gt;
    print(f&amp;quot;{pet} at index {index}&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Generator Expressions and Comprehensions ===&lt;br /&gt;
&lt;br /&gt;
A generator is a special kind of object that, basically, represents a collection of items using a value and a function for generating the next value in the collection. In other words, it's a way of creating something that behaves like a list, but which only generates one value at a time, and discards a value when it's done with it. Say, for example, you wanted to do an operation on 10,000,000,000,000 numbers. You could put them all in a list, then iterate over the list, but that would take a lot of memory, plus you'd have to create and fill the entire list before beginning to actually work on your problem. Instead, you'd probably be better off using a generator; telling the computer, essentially: “The starting value is 0. When I ask for the next number in the collection, add 1 to current value and give me that.”&lt;br /&gt;
&lt;br /&gt;
A generator expression is an expression that is evaluated to create a generator. They're super useful. Generator expressions can take two forms – they can be used with and without a condition:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
(EXPRESSION for VARIABLE in ITERABLE) # Unconditional&lt;br /&gt;
(EXPRESSION for VARIABLE in ITERABLE if CONDITION) # Conditional&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
For our purposes, you can think of an iterable as anything you can do a for loop over. Let's take a look at a generator expression in use:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
double_even_digits = (number * 2 for number in range(10) if number % 2 == 0)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
That line says that &amp;lt;code&amp;gt;double_even_digits&amp;lt;/code&amp;gt; is every even number between 0 and 10 multiplied by two. Simple enough, right? If we wanted to use all of the numbers, not just the even ones, we could simply remove the if statement at the end of the expression.&lt;br /&gt;
&lt;br /&gt;
Here's the thing, though: if you were to print &amp;lt;code&amp;gt;double_even_digits&amp;lt;/code&amp;gt;, instead of a nice bunch of numbers, you'd get something that looks like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&amp;lt;generator object &amp;lt;genexpr&amp;gt;&amp;lt;code&amp;gt;at 0x107fc92b0&amp;gt;&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
That's because generators are lazy! They don't generate their values until those values are needed, and they discard values once they're no longer needed. As a result, '''you can only iterate over a generator once'''. In this case, you can't print out the whole generator, because it hasn't generated all the values yet. You can, however, iterate over the generator, and print its values one at a time, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
for number in double_even_digits:&lt;br /&gt;
    print(number)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
You can also make a list out of the generator, which will go through all the items in the generator and put them in a list, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
even_number_list = list(double_even_digits)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
That's actually a great segue to the second topic of this section: comprehensions. A comprehension is just a prettier way to make lists, sets, and dicts out of a generator expressions.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
# If you want a list:&lt;br /&gt;
list(i for i in range(10) if i % 2 == 0) # Don't do this&lt;br /&gt;
[i for i in range(10) if i % 2 == 0] # Use a list comprehension instead!&lt;br /&gt;
&lt;br /&gt;
# If you want a set:&lt;br /&gt;
set(i for i in range(10) if i % 2 == 0) # Don't do this&lt;br /&gt;
{i for i in range(10) if i % 2 == 0} # Use a set comprehension instead!&lt;br /&gt;
&lt;br /&gt;
# If you want a dict:&lt;br /&gt;
dict((i, i + 1) for i in range(10) if i % 2 == 0) # Don't do this&lt;br /&gt;
{i : i + 1 for i in range(10) if i % 2 == 0} # Use a dict comprehension instead!&lt;br /&gt;
&lt;br /&gt;
# If you want a tuple:&lt;br /&gt;
tuple(i for i in range(10) if i % 2 == 0) # Unfortunately, there's no better way to do this&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
In general, generators and comprehensions should be used whenever possible - they're the fastest and easiest way to build collections. If you ever see yourself writing code like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
# BAD PRACTICE! DO NOT USE!&lt;br /&gt;
digits = []&lt;br /&gt;
for digit in range(10):&lt;br /&gt;
    digits.append(digit)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Don't do it! Instead, use a generator expression or comprehension, as appropriate. A good way to decide whether a generator expression or comprehension is better for this situation is that, if you're just going to be iterating over your collection once, you should use an generator expression. If not, use a comprehension.&lt;br /&gt;
&lt;br /&gt;
=== Sorting ===&lt;br /&gt;
&lt;br /&gt;
Sorting in Python is frequently performed using the &amp;lt;code&amp;gt;sorted&amp;lt;/code&amp;gt; function, which takes two arguments: an iterable (anything you can do a for-loop over, including lists and tuples) and a function used to evaluate each item. If the function is omitted, Python will try to sort the lists by value.&lt;br /&gt;
&lt;br /&gt;
The following example demonstrates using an inline function, which Python calls a ''lambda''.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = ['apple', 'banana', 'cherry', 'date']&lt;br /&gt;
&lt;br /&gt;
# sort the fruits by string length&lt;br /&gt;
new_fruits = sorted(fruits, key=lambda v: len(v) // 2)&lt;br /&gt;
&lt;br /&gt;
print(new_fruits) # ['date', 'apple', 'banana', 'cherry']&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Alternatively, you can sort a &amp;lt;code&amp;gt;list&amp;lt;/code&amp;gt; using the &amp;lt;code&amp;gt;.sort&amp;lt;/code&amp;gt; method. This is faster than calling &amp;lt;code&amp;gt;sorted&amp;lt;/code&amp;gt;, but it modifies the list in-place and returns &amp;lt;code&amp;gt;None&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = ['apple', 'banana', 'cherry', 'date']&lt;br /&gt;
fruits.sort()&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
=== Import ===&lt;br /&gt;
&lt;br /&gt;
If you want to use functions from other libraries (including ones that you install using pip), use &amp;lt;code&amp;gt;import&amp;lt;/code&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
import time&lt;br /&gt;
&lt;br /&gt;
current_time = time.localtime()&lt;br /&gt;
print(time.strftime('%a, %d %b %Y %H:%M:%S', current_time))&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If you want to pull the functions out of their namespace, you can use &amp;lt;code&amp;gt;from ___ import ___&amp;lt;/code&amp;gt; syntax:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
from time import localtime, strftime&lt;br /&gt;
&lt;br /&gt;
current_time = localtime()&lt;br /&gt;
print(strftime('%a, %d %b %Y %H:%M:%S', current_time))&lt;br /&gt;
&lt;br /&gt;
# Be aware that this technique, although convenient, may cause unexpected behavior if the function names that you're pulling out of the namespace are already used for other purposes in Python.&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
=== File I/O ===&lt;br /&gt;
&lt;br /&gt;
You can read an entire file into a variable like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
f = open(&amp;quot;example.txt&amp;quot;)&lt;br /&gt;
file_contents = f.read()&lt;br /&gt;
&lt;br /&gt;
f.close() # free up memory when we're finished with the file&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
A better option is to use a with-block, which handles opening and closing the file for you automatically:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
with open(&amp;quot;example.txt&amp;quot;) as f:&lt;br /&gt;
    file_contents = f.read()&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
You can read a file line-by-line like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
with open(&amp;quot;example.txt&amp;quot;) as f:&lt;br /&gt;
    for line in f:&lt;br /&gt;
        print(&amp;quot;Read line: %s&amp;quot; % line.rstrip())&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
You can write to a file like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
with open(&amp;quot;example.txt&amp;quot;, &amp;quot;w&amp;quot;) as f:&lt;br /&gt;
    f.write(&amp;quot;Hello\nWorld\n&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
=== Command-Line Arguments ===&lt;br /&gt;
&lt;br /&gt;
Command line arguments are accessible in the variable &amp;lt;code&amp;gt;sys.argv&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
The following example shows a program that expects a filename as its argument, and it prints a usage message if the argument is not present ([https://stackoverflow.com/questions/983201/python-and-sys-argv source]).&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
import sys, os&lt;br /&gt;
&lt;br /&gt;
if len(sys.argv) &amp;lt; 2:&lt;br /&gt;
    sys.exit(f&amp;quot;Usage: {sys.argv[0]} filename&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
filename = sys.argv[1]&lt;br /&gt;
&lt;br /&gt;
if not os.path.exists(filename):&lt;br /&gt;
    sys.exit(f&amp;quot;Error: File '{sys.argv[1]}' not found&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Object-Oriented Programming ===&lt;br /&gt;
&lt;br /&gt;
You can define and use a class like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
class Food:&lt;br /&gt;
    # constructor:&lt;br /&gt;
    def __init__(self, name):&lt;br /&gt;
        self.name = name&lt;br /&gt;
    &lt;br /&gt;
    def format_name(self):&lt;br /&gt;
        return f&amp;quot;Gotta love to eat {self.name}&amp;quot;&lt;br /&gt;
&lt;br /&gt;
class Fruit(Food):&lt;br /&gt;
    def format_name(self):&lt;br /&gt;
        return f&amp;quot;{Food.format_name(self)} (fruit)&amp;quot;&lt;br /&gt;
&lt;br /&gt;
fruit = Fruit(&amp;quot;Cherry&amp;quot;)&lt;br /&gt;
print(fruit.format_name())&lt;br /&gt;
print(Food.get_definition())&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
This is the same example as in [[PHP#Object-Oriented_Programming|the PHP guide]].&lt;br /&gt;
&lt;br /&gt;
Some things to notice:&lt;br /&gt;
&lt;br /&gt;
* Instance methods ''always'' take &amp;lt;code&amp;gt;self&amp;lt;/code&amp;gt; as their first argument, followed by any number of additional parameters. This can be misleading for programmers familiar with other languages, because the number of arguments you feed to the method is actually ''one less than'' the number of declared parameters. Whenever you call a method on a class instance, that instance is implicitly fed into the explicitly-declared &amp;lt;code&amp;gt;self&amp;lt;/code&amp;gt; parameter of the method.&lt;br /&gt;
*: Note that the &amp;lt;code&amp;gt;self&amp;lt;/code&amp;gt; variable has the same purpose as the &amp;lt;code&amp;gt;this&amp;lt;/code&amp;gt; variable in languages like PHP, Java, JavaScript, and C++.&lt;br /&gt;
*There is no need for a &amp;lt;code&amp;gt;new&amp;lt;/code&amp;gt; keyword in Python.&lt;br /&gt;
&lt;br /&gt;
= Footnotes =&lt;br /&gt;
# {{note|interpreted}}This is an oversimplification. If you're interested, here's a quick explanation of how: In CPython (the reference implementation of Python) programs are compiled to bytecode, an intermediate representation, which is then interpreted.&lt;br /&gt;
[[Category:Module 4]]&lt;/div&gt;</summary>
		<author><name>Alex</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Python&amp;diff=2517</id>
		<title>Python</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Python&amp;diff=2517"/>
		<updated>2018-02-19T17:31:41Z</updated>

		<summary type="html">&lt;p&gt;Alex: /* Object-Oriented Programming */  Format strings&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Languages like Java and C++ have lots of rules regarding variable types, syntax, return values, and so on. These can be cumbersome when you are trying to write short, quick scripts to perform tasks. This is where a ''scripting language'' comes into play.&lt;br /&gt;
&lt;br /&gt;
'''Python''' is a language well-suited to rapid prototype development. It is generally an ''interpreted language'', which means that, generally speaking, a Python program is converted line by line into instructions for the computer to execute as the program runs, instead of having a separate compilation step beforehand {{ref|interpreted}}. The syntax is clean, and it is usually clear at first glance what is going on when you write in Python.&lt;br /&gt;
&lt;br /&gt;
= Installation =&lt;br /&gt;
&lt;br /&gt;
Python may already be installed on your system. To see whether or not it is, enter the command&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ python --version&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If it tells you a version of Python '''greater than or equal to 3.5''' then you're good to go. If not, you need to do a quick package install to get it up and running. Using yum, it's just &amp;lt;code&amp;gt;sudo yum install python35; sudo alternatives --set python /usr/bin/python3&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
==== Python 2 vs Python 3 ====&lt;br /&gt;
&lt;br /&gt;
In 2008, a new version of Python – Python 3 – was released, with a number changes that made it incompatible with the previous version, Python 2. For several years, the Python community was slow to make the change to Python 3, but today, Python 3 is ''the'' standard for new code. The ''only'' reason to write Python 2 code today is because you have to work in an environment or with libraries that do not support Python 3, and that situation is becoming increasingly rare.&lt;br /&gt;
&lt;br /&gt;
'''For CSE 330 (and this guide), you ''must'' use Python 3.5 or greater.'''&lt;br /&gt;
&lt;br /&gt;
=== Pip ===&lt;br /&gt;
&lt;br /&gt;
Linux distributions have package managers like ''Apt'', ''Yum'', and ''YaST''. PHP has a package manager named ''PEAR''. It's now time to introduce Python's leading package manager: '''pip'''.&lt;br /&gt;
&lt;br /&gt;
You need to install Pip from Yum before you can use it. The package is called &amp;lt;code&amp;gt;python-pip&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Once you have pip installed, you can use it to install Python packages. Use the &amp;lt;code&amp;gt;pip-python&amp;lt;/code&amp;gt; command:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ pip-python install package_name # RHEL&lt;br /&gt;
$ pip install package_name # Debian&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
= Running Python =&lt;br /&gt;
&lt;br /&gt;
There are two common ways to run Python code: via the console, and via a Python script file.&lt;br /&gt;
&lt;br /&gt;
=== The Python Console ===&lt;br /&gt;
&lt;br /&gt;
The Python console enables you to experiment with code without opening a text editor. To enter the Python console, simply type the ''python'' command at the terminal:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ python&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
To leave the interactive console, either type &amp;lt;code&amp;gt;quit()&amp;lt;/code&amp;gt; or press &amp;lt;code&amp;gt;Ctrl-D&amp;lt;/code&amp;gt; (on both Mac and Windows).&lt;br /&gt;
&lt;br /&gt;
=== Python Script Files ===&lt;br /&gt;
&lt;br /&gt;
You can also save Python script files for later use. The extension for Python scripts is &amp;lt;code&amp;gt;*.py&amp;lt;/code&amp;gt;. To run a script file, simply feed its path as an argument to the &amp;lt;code&amp;gt;python&amp;lt;/code&amp;gt; command in Terminal:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ python my_script.py&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Python Syntax and Language Components =&lt;br /&gt;
&lt;br /&gt;
This section contains a very brief overview of Python syntax. For a more comprehensive introduction, see [http://docs.python.org/tutorial/ the Python docs].&lt;br /&gt;
&lt;br /&gt;
=== Python's Type System ===&lt;br /&gt;
&lt;br /&gt;
Python is a dynamically-typed, strongly-typed, and duck-typed language. What does that mean? Well, let's take those categories one by one:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;ol&amp;gt;&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
'''Dynamic typing''', in contrast to ''static typing'' means that the types of objects can be changed. In Java, for instance, if you tried to write the following code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
int c = 2;&lt;br /&gt;
c = &amp;quot;fish&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Your code would fail to compile, because the Java compiler wouldn't allow you to change the type of the variable &amp;lt;code&amp;gt;c&amp;lt;/code&amp;gt; from &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt; to &amp;lt;code&amp;gt;String&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Python, however, is just fine with that. You can write:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
c = 2&lt;br /&gt;
c = &amp;quot;fish&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
And Python will happily do what you ask.&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
'''Strong typing''', in contrast to ''weak typing'', means, roughly, that a language won't implicitly convert types for you. So far, you've used a lot of PHP, which is very weakly typed. For example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;php&amp;quot;&amp;gt;&lt;br /&gt;
echo &amp;quot;10&amp;quot; . 2;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In PHP, this works just fine. The PHP interpreter sees that &amp;lt;code&amp;gt;2&amp;lt;/code&amp;gt; is an int, and silently converts it to a string for you, so that &amp;lt;code&amp;gt;&amp;quot;10&amp;quot;. 2&amp;lt;/code&amp;gt; equals &amp;lt;code&amp;gt;&amp;quot;102&amp;quot;&amp;lt;/code&amp;gt;. The problem with weak typing is that it can make it unclear to the programmer why things are happening the way they are. For instance, in PHP, the expression &amp;lt;code&amp;gt;&amp;quot;10&amp;quot; == 10&amp;lt;/code&amp;gt; is true, which can be less than obvious. Python, however, tries to disallow that sort of thing:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
&amp;quot;10&amp;quot; + &amp;quot;10&amp;quot; # Allowed – concatenates the two strings.&lt;br /&gt;
10   +  10  # Allowed – adds the two ints.&lt;br /&gt;
&amp;quot;10&amp;quot; +  10  # Not allowed – raises a TypeError&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Perhaps the one exception to this rule is the relationship between numeric types; it's perfectly fine to add a float to an int, for example.&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
'''Duck-typing''' is a little bit different than the other categories, because it doesn't really have a direct opposite. Essentially, duck-typing is the philosophy that &amp;quot;If it walks like a duck, and quacks like a duck, it's a duck.&amp;quot; In programming terms, that means that we often don't care what type an object is, as long as it can do the things we ask.&lt;br /&gt;
&lt;br /&gt;
Let's look at an example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
# This function doubles the value it's passed.&lt;br /&gt;
def double(thing):&lt;br /&gt;
    return thing + thing&lt;br /&gt;
double(10) # Returns 20&lt;br /&gt;
double(&amp;quot;fish&amp;quot;) # Returns &amp;quot;fishfish&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If this were Java, we'd have to write two different methods here: one for things of type &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt;, and one for things of type &amp;lt;code&amp;gt;String&amp;lt;/code&amp;gt;. Since this is Python, though, we don't have to do that. Instead, Python lets us say, essentially: &amp;quot;This function uses the &amp;lt;code&amp;gt;+&amp;lt;/code&amp;gt; operator, so you can pass whatever object you want to the function, as long as the function supports the &amp;lt;code&amp;gt;+&amp;lt;/code&amp;gt; operator&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
To quote [https://groups.google.com/forum/?hl=en#!msg/comp.lang.python/CCs2oJdyuzc/NYjla5HKMOIJ Alex Martelli], one of the key people in the Python project,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;blockquote&amp;gt;&lt;br /&gt;
&amp;quot;[Don't] check whether it IS-a duck: check whether it QUACKS-like-a duck, WALKS-like-a duck, etc, etc, depending on exactly what subset of duck-like behaviour you need.&amp;quot;&lt;br /&gt;
&amp;lt;/blockquote&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&amp;lt;/ol&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Basic Types ===&lt;br /&gt;
&lt;br /&gt;
In Python, the basic scalar types are:&lt;br /&gt;
&lt;br /&gt;
# &amp;lt;code&amp;gt;str&amp;lt;/code&amp;gt; – a string.&lt;br /&gt;
# &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt; – an integer object with unlimited digits.&lt;br /&gt;
# &amp;lt;code&amp;gt;bool&amp;lt;/code&amp;gt; – a Boolean value.&lt;br /&gt;
# &amp;lt;code&amp;gt;float&amp;lt;/code&amp;gt; – a floating point number; generally equivalent to &amp;lt;code&amp;gt;double&amp;lt;/code&amp;gt; in Java.&lt;br /&gt;
# &amp;lt;code&amp;gt;bytes&amp;lt;/code&amp;gt; – represents a collection of bytes; you're unlikely to use this often.&lt;br /&gt;
&lt;br /&gt;
Casting is done in the C style - to parse an &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt; from a string, for instance, you'd write &amp;lt;code&amp;gt;int(&amp;quot;123&amp;quot;)&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== Basic Control Flow ===&lt;br /&gt;
In Python, blocks of code are delineated using colons and indentation instead of curly braces. '''''That means that proper indentation is mandatory.''''' Every time you use a colon, you must indent one step further, and every time a block ends, you must unindent a step.&lt;br /&gt;
&lt;br /&gt;
Conditional statements are done using the &amp;lt;code&amp;gt;if&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;elif&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;else&amp;lt;/code&amp;gt; operators, like in the example below - pay attention to the indentation:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
cookies_left = 10&lt;br /&gt;
cake_slices_left = 3&lt;br /&gt;
if cookies_left &amp;gt; 10:&lt;br /&gt;
    print(&amp;quot;Lots of cookies!&amp;quot;)&lt;br /&gt;
elif cookies_left &amp;gt; 8:&lt;br /&gt;
    print(&amp;quot;Plenty left!&amp;quot;)&lt;br /&gt;
elif cookies_left == 5:&lt;br /&gt;
    print(&amp;quot;Halfway done!&amp;quot;)&lt;br /&gt;
else:&lt;br /&gt;
    if cake_slices_left == 3:&lt;br /&gt;
        print(&amp;quot;Lots of cake!&amp;quot;)&lt;br /&gt;
    elif cake_slices_left == 2:&lt;br /&gt;
        print(&amp;quot;One slice gone!&amp;quot;)&lt;br /&gt;
    else:&lt;br /&gt;
        print(&amp;quot;Little to no cake left!&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== An Example Python Script ===&lt;br /&gt;
&lt;br /&gt;
In my mind, there's no better way to learn Python than to be immersed in a simple example script.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
print(&amp;quot;Hello World&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
fruits = [&amp;quot;apple&amp;quot;, &amp;quot;banana&amp;quot;, &amp;quot;cherry&amp;quot;, &amp;quot;date&amp;quot;]&lt;br /&gt;
for fruit in fruits:&lt;br /&gt;
    print(f&amp;quot;I always love to eat a fresh {fruit}&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Map the fruits list over to a new list containing the length of the fruit strings:&lt;br /&gt;
fruit_size = [len(fruit) for fruit in fruits]&lt;br /&gt;
&lt;br /&gt;
avg_fruit_size = sum(fruit_size) / len(fruit_size)&lt;br /&gt;
print(f&amp;quot;The average fruit string length is {avg_fruit_size:.2f}.&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Some things to notice:&lt;br /&gt;
&lt;br /&gt;
* Printing is achieved using the &amp;lt;code&amp;gt;print()&amp;lt;/code&amp;gt; function.&lt;br /&gt;
* Comments start with a pound symbol &amp;lt;code&amp;gt;#&amp;lt;/code&amp;gt;.&lt;br /&gt;
* We can transform/map a list to a new list in just one line!&lt;br /&gt;
&lt;br /&gt;
For some more examples, see [https://wiki.python.org/moin/SimplePrograms the Python wiki].&lt;br /&gt;
&lt;br /&gt;
=== A Few Gotchas ===&lt;br /&gt;
&lt;br /&gt;
Here are a few things you may not expect when starting out with Python:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;ol&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
Strings can be delimited using either single quotes (&amp;lt;code&amp;gt;'&amp;lt;/code&amp;gt;) or double quotes (&amp;lt;code&amp;gt;&amp;quot;&amp;lt;/code&amp;gt;), so &amp;lt;code&amp;gt;'Python'&amp;lt;/code&amp;gt; is the same as &amp;lt;code&amp;gt;&amp;quot;Python&amp;quot;&amp;lt;/code. You can also use three sets of quotes (&amp;lt;code&amp;gt;'''&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;&amp;quot;&amp;quot;&amp;quot;&amp;lt;/code&amp;gt;) to delineate a multiple-line string, like so:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
long_string = &amp;quot;&amp;quot;&amp;quot;This&lt;br /&gt;
is my&lt;br /&gt;
very long&lt;br /&gt;
multiple-line&lt;br /&gt;
string&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
To compare the equality of two objects, use the &amp;lt;code&amp;gt;==&amp;lt;/code&amp;gt; operator. To compare the identity of two objects (i.e. whether or not they are literally the same object, at the same place in memory), use the &amp;lt;code&amp;gt;is&amp;lt;/code&amp;gt; operator. These correspond, respectively to &amp;lt;code&amp;gt;.equals()&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;==&amp;lt;/code&amp;gt; in Java.&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
The &amp;lt;code&amp;gt;/&amp;lt;/code&amp;gt; operator performs floating-point division, not integer division, even when both its arguments are integers. If you want to do integer division, use the &amp;lt;code&amp;gt;//&amp;lt;/code&amp;gt; operator. Let's look at an example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
9   / 10    == 0.9 # Floating-point division&lt;br /&gt;
9.0 / 10.0  == 0.9 # Floating-point division&lt;br /&gt;
9   // 10   == 0   # Integer division&lt;br /&gt;
9.0 // 10.0 == 0.0 # Integer division, even though the resulting value is a float&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
As discussed in the section [[#Python's_Type_System|Python's Type System]], you can't combine strings and numbers using the &amp;lt;code&amp;gt;+&amp;lt;/code&amp;gt; operator. Instead, you'll have to use one of the following methods of string formatting:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
  &lt;br /&gt;
# Technique 1 – printf-style Formatting&lt;br /&gt;
# This is a classic style of string formatting, used in many programming languages, including in Java's String.format.&lt;br /&gt;
&amp;quot;You scored %d out of %d!&amp;quot; % (score, questions)&lt;br /&gt;
&lt;br /&gt;
# Technique 2 – str.format&lt;br /&gt;
&amp;quot;You scored {} out of {}!&amp;quot;.format(score, questions)&lt;br /&gt;
&lt;br /&gt;
# Technique 3 – f-strings&lt;br /&gt;
# These were only introduced in Python 3.6 but they're very convenient.&lt;br /&gt;
f&amp;quot;You scored {score} out of {questions}!&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# Technique 4 - String Concatenation&lt;br /&gt;
# This is fine for small things, but for more complicated stuff, use one of the other techniques.&lt;br /&gt;
&amp;quot;You scored &amp;quot; + str(score) + &amp;quot; out of &amp;quot; + str(questions) + &amp;quot;!&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&amp;lt;/ol&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Functions ===&lt;br /&gt;
&lt;br /&gt;
Define functions using the &amp;lt;code&amp;gt;def&amp;lt;/code&amp;gt; keyword:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def hello(name):&lt;br /&gt;
    print(f&amp;quot;Hello, {name}!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Invoke functions using parentheses:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
hello(&amp;quot;Batman&amp;quot;)&lt;br /&gt;
hello(&amp;quot;Superman&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Functions can have optional arguments; however, these must come after any required arguments:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def hello(name=&amp;quot;User&amp;quot;):&lt;br /&gt;
    print(f&amp;quot;Hello, {name}!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
hello() # Prints &amp;quot;Hello, User!&amp;quot;&lt;br /&gt;
hello(&amp;quot;Sarah&amp;quot;) # Prints &amp;quot;Hello, Sarah!&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Functions are just regular objects in Python, meaning you can do stuff like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def hello(name=&amp;quot;User&amp;quot;):&lt;br /&gt;
    print(f&amp;quot;Hello, {name}!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
greeting = hello&lt;br /&gt;
&lt;br /&gt;
greeting(&amp;quot;Siwei&amp;quot;) # Prints &amp;quot;Hello, Siwei!&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Collection Types ===&lt;br /&gt;
Python has a few basic, built-in collection types. They each have their own special use cases, but they share a lot of similarities. All built-in data structures in Python are zero-indexed, for instance.&lt;br /&gt;
&lt;br /&gt;
To obtain the number of elements in a collection, use the &amp;lt;code&amp;gt;len()&amp;lt;/code&amp;gt; function, like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish'] # This is a list; you'll learn about them below.&lt;br /&gt;
&lt;br /&gt;
len(pets) # Returns 3&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To check if a collection contains an item, use the &amp;lt;code&amp;gt;in&amp;lt;/code&amp;gt; operator:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish'] # This is a list; you'll learn about them below.&lt;br /&gt;
&lt;br /&gt;
'Dog' in pets # Returns True&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Helpfully, the Python Software Foundation maintains a page containing the asymptotic complexities of important operations on major Python data structures. It's available [https://wiki.python.org/moin/TimeComplexity here].&lt;br /&gt;
&lt;br /&gt;
==== Lists ====&lt;br /&gt;
&lt;br /&gt;
Unlike languages like Java and C, Python's array-like type doesn't have fixed length. Instead, a &amp;lt;code&amp;gt;list&amp;lt;/code&amp;gt; is a dynamic array (like Java's &amp;lt;code&amp;gt;ArrayList&amp;lt;/code&amp;gt;) of objects of any type. Here's an example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = [&amp;quot;Apple&amp;quot;, &amp;quot;Pear&amp;quot;, &amp;quot;Orange&amp;quot;] # Lists can be creating by placing their items between square brackets&lt;br /&gt;
&lt;br /&gt;
random_items = ['Apple', 12312, 2.0, [1, 2, 3]] # Lists can contain objects of different types - even other lists!&lt;br /&gt;
&lt;br /&gt;
pets.append('Turtle') # Adds 'Turtle' to the end of pets&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For the next few examples, we'll be using the following list:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish', 'Turtle', 'Lizard', 'Snake']&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access or assign elements of a list, use the &amp;lt;code&amp;gt;[]&amp;lt;/code&amp;gt; operator.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[0] # Returns 'Dog'&lt;br /&gt;
pets[1] = 'Cow' # Sets pets[1] to 'Cow'&lt;br /&gt;
pets[1] = 'Cat' # Sets pets[1] back to 'Cat' &lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You can also access or assign lists using negative indices, which will return elements starting from the end of the list:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[-1] # Returns 'Snake'&lt;br /&gt;
pets[-2] # Returns 'Lizard'&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You can also use 'slice notation' to obtain or assign subsets of lists:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[start:end] # Returns items from index start to index end - 1.&lt;br /&gt;
pets[start:]    # Returns items from index start to the end of the list, inclusive.&lt;br /&gt;
pets[:end]      # Returns items from the beginning of the list to index end - 1.&lt;br /&gt;
pets[:]         # Returns every item in the list&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
There's also a third, optional argument: &amp;lt;code&amp;gt;step&amp;lt;/code&amp;gt;, which lets you jump over values:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[start:end:step] # Returns items from index start to index end - 1, jumping step values at a time&lt;br /&gt;
&lt;br /&gt;
# Examples:&lt;br /&gt;
pets[1:5:2] # Returns items from index 1 to index 4, jumping 2 at a time, so ['Cat', 'Turtle']&lt;br /&gt;
pets[::3] # Returns all items in the list, jumping 3 at a time, so ['Dog', 'Turtle']&lt;br /&gt;
pets[::-1] # Returns all items in the list, jumping -1 at a time. This reverses the list, so ['Snake', 'Lizard', 'Turtle', 'Fish', 'Cat', 'Dog']&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Lists have all the performance characteristics you'd expect of a dynamic array - constant-time indexing, amortized constant-time appends, and so on.&lt;br /&gt;
&lt;br /&gt;
==== Tuples ====&lt;br /&gt;
&lt;br /&gt;
Python has a special data type called &amp;lt;code&amp;gt;tuple&amp;lt;/code&amp;gt;, which is exactly the same as a list except for the fact that it cannot be modified, so you can't append or replace items.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
cities = ('St. Louis', 'Los Angeles', 'Seattle') # Tuples are defined using parentheses.&lt;br /&gt;
numbers = 1, 2, 3 # You can also omit the parentheses if it's unambiguous&lt;br /&gt;
single_item_tuple = (1,) # To make a tuple with only one item, put a comma after it&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Tuples also enable you to have multiple return values from a function:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def compute_length(string):&lt;br /&gt;
    str_len = len(string)&lt;br /&gt;
    if str_len &amp;lt; 5:&lt;br /&gt;
        return str_len, &amp;quot;short&amp;quot;&lt;br /&gt;
    elif str_len &amp;lt; 40:&lt;br /&gt;
        return str_len, &amp;quot;medium&amp;quot;&lt;br /&gt;
    return str_len, &amp;quot;long&amp;quot;&lt;br /&gt;
&lt;br /&gt;
length, description = compute_length(&amp;quot;Four score and seven years ago&amp;quot;)&lt;br /&gt;
print(&amp;quot;The %s string is %d characters long.&amp;quot; % (description, length))&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
The above example also demonstrates Python's if...elif...else conditional structure.&lt;br /&gt;
&lt;br /&gt;
==== Dictionaries ====&lt;br /&gt;
&lt;br /&gt;
Python has another datatype called a '''dictionary''' (or &amp;lt;code&amp;gt;dict&amp;lt;/code&amp;gt;, for short), which are like ''Maps'' in Java, ''associative arrays'' in PHP, and ''object literals'' in JavaScript (coming up soon in Module 6). Essentially, they enable you to use any immutable object as the key in your data structure. &amp;lt;code&amp;gt;dict&amp;lt;/code&amp;gt; objects can be created using either the &amp;lt;code&amp;gt;dict&amp;lt;/code&amp;gt; function, or by placing items between curly braces, separating keys and values using colons:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits_in_bowl = {&lt;br /&gt;
    'apple': 4,&lt;br /&gt;
    'banana': 2,&lt;br /&gt;
    'cherry': 0,&lt;br /&gt;
    'date': 12&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
apple_count = fruits_in_bowl['apple'] # Equals 4&lt;br /&gt;
&lt;br /&gt;
fruits_in_bowl['pear'] = 9 # Sets 'pear' in the dictionary to 9.&lt;br /&gt;
&lt;br /&gt;
for fruit, num in fruits_in_bowl.items():&lt;br /&gt;
    print(f&amp;quot;There are {num} {fruit}(s) in the bowl.&amp;quot; % (num, fruit))&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If you only want the keys from a dictionary, you can just iterate over it directly, like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
for fruit in fruits_in_bowl:&lt;br /&gt;
    print(fruit)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If you want only the values but not the keys from a dictionary, use &amp;lt;code&amp;gt;my_dictionary.values()&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
==== Sets ==== &lt;br /&gt;
A &amp;lt;code&amp;gt;set&amp;lt;/code&amp;gt; is an unordered collection of unique items, with constant-time membership checking. &lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = {'Apple', 'Apple', 'Apple', 'Pear'} # The set removes duplicates, so it will only contain {'Apple', 'Pear'}&lt;br /&gt;
fruits = set(['Apple', 'Apple', 'Apple', 'Pear']) # This line transforms a list into a set&lt;br /&gt;
print('Apple' in fruits) # Constant-time!&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Loops ===&lt;br /&gt;
&lt;br /&gt;
In Python, while loops are written like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
i = 0&lt;br /&gt;
while i &amp;lt; 10:&lt;br /&gt;
    i += 1&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
For loops are written like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish']&lt;br /&gt;
&lt;br /&gt;
for pet in pets:&lt;br /&gt;
    print(pet)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
To iterate over a range of numbers, you can use the convenient &amp;lt;code&amp;gt;range&amp;lt;/code&amp;gt; function, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
for i in range(20, 30): # If you omit the first argument to range, it's assumed to be zero.&lt;br /&gt;
    print(i)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Note that &amp;lt;code&amp;gt;range&amp;lt;/code&amp;gt; provides a closed-open range. That is to say, it is inclusive of its lower bound and exclusive of its upper bound. To be very explicit about it:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
list(range(3, 6)) == [3, 4, 5]&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Unlike in other languages you may know, the following is not good practice in Python:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish']&lt;br /&gt;
&lt;br /&gt;
# BAD PRACTICE. DO NOT USE.&lt;br /&gt;
for i in range(len(pets)):&lt;br /&gt;
    pet = pets[i]&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Instead, if you need to access both a variable and its index, use the &amp;lt;code&amp;gt;enumerate&amp;lt;/code&amp;gt; function, which allows you to iterate through a group of items, along with their indexes, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish']&lt;br /&gt;
&lt;br /&gt;
for index, pet in enumerate(pets):&lt;br /&gt;
    print(f&amp;quot;{pet} at index {index}&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Generator Expressions and Comprehensions ===&lt;br /&gt;
&lt;br /&gt;
A generator is a special kind of object that, basically, represents a collection of items using a value and a function for generating the next value in the collection. In other words, it's a way of creating something that behaves like a list, but which only generates one value at a time, and discards a value when it's done with it. Say, for example, you wanted to do an operation on 10,000,000,000,000 numbers. You could put them all in a list, then iterate over the list, but that would take a lot of memory, plus you'd have to create and fill the entire list before beginning to actually work on your problem. Instead, you'd probably be better off using a generator; telling the computer, essentially: “The starting value is 0. When I ask for the next number in the collection, add 1 to current value and give me that.”&lt;br /&gt;
&lt;br /&gt;
A generator expression is an expression that is evaluated to create a generator. They're super useful. Generator expressions can take two forms – they can be used with and without a condition:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
(EXPRESSION for VARIABLE in ITERABLE) # Unconditional&lt;br /&gt;
(EXPRESSION for VARIABLE in ITERABLE if CONDITION) # Conditional&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
For our purposes, you can think of an iterable as anything you can do a for loop over. Let's take a look at a generator expression in use:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
double_even_digits = (number * 2 for number in range(10) if number % 2 == 0)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
That line says that &amp;lt;code&amp;gt;double_even_digits&amp;lt;/code&amp;gt; is every even number between 0 and 10 multiplied by two. Simple enough, right? If we wanted to use all of the numbers, not just the even ones, we could simply remove the if statement at the end of the expression.&lt;br /&gt;
&lt;br /&gt;
Here's the thing, though: if you were to print &amp;lt;code&amp;gt;double_even_digits&amp;lt;/code&amp;gt;, instead of a nice bunch of numbers, you'd get something that looks like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&amp;lt;generator object &amp;lt;genexpr&amp;gt;&amp;lt;code&amp;gt;at 0x107fc92b0&amp;gt;&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
That's because generators are lazy! They don't generate their values until those values are needed, and they discard values once they're no longer needed. As a result, '''you can only iterate over a generator once'''. In this case, you can't print out the whole generator, because it hasn't generated all the values yet. You can, however, iterate over the generator, and print its values one at a time, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
for number in double_even_digits:&lt;br /&gt;
    print(number)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
You can also make a list out of the generator, which will go through all the items in the generator and put them in a list, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
even_number_list = list(double_even_digits)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
That's actually a great segue to the second topic of this section: comprehensions. A comprehension is just a prettier way to make lists, sets, and dicts out of a generator expressions.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
# If you want a list:&lt;br /&gt;
list(i for i in range(10) if i % 2 == 0) # Don't do this&lt;br /&gt;
[i for i in range(10) if i % 2 == 0] # Use a list comprehension instead!&lt;br /&gt;
&lt;br /&gt;
# If you want a set:&lt;br /&gt;
set(i for i in range(10) if i % 2 == 0) # Don't do this&lt;br /&gt;
{i for i in range(10) if i % 2 == 0} # Use a set comprehension instead!&lt;br /&gt;
&lt;br /&gt;
# If you want a dict:&lt;br /&gt;
dict((i, i + 1) for i in range(10) if i % 2 == 0) # Don't do this&lt;br /&gt;
{i : i + 1 for i in range(10) if i % 2 == 0} # Use a dict comprehension instead!&lt;br /&gt;
&lt;br /&gt;
# If you want a tuple:&lt;br /&gt;
tuple(i for i in range(10) if i % 2 == 0) # Unfortunately, there's no better way to do this&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
In general, generators and comprehensions should be used whenever possible - they're the fastest and easiest way to build collections. If you ever see yourself writing code like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
# BAD PRACTICE! DO NOT USE!&lt;br /&gt;
digits = []&lt;br /&gt;
for digit in range(10):&lt;br /&gt;
    digits.append(digit)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Don't do it! Instead, use a generator expression or comprehension, as appropriate. A good way to decide whether a generator expression or comprehension is better for this situation is that, if you're just going to be iterating over your collection once, you should use an generator expression. If not, use a comprehension.&lt;br /&gt;
&lt;br /&gt;
=== Sorting ===&lt;br /&gt;
&lt;br /&gt;
Sorting in Python is frequently performed using the &amp;lt;code&amp;gt;sorted&amp;lt;/code&amp;gt; function, which takes two arguments: an iterable (anything you can do a for-loop over, including lists and tuples) and a function used to evaluate each item. If the function is omitted, Python will try to sort the lists by value.&lt;br /&gt;
&lt;br /&gt;
The following example demonstrates using an inline function, which Python calls a ''lambda''.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = ['apple', 'banana', 'cherry', 'date']&lt;br /&gt;
&lt;br /&gt;
# sort the fruits by string length&lt;br /&gt;
new_fruits = sorted(fruits, key=lambda v: len(v) // 2)&lt;br /&gt;
&lt;br /&gt;
print(new_fruits) # ['date', 'apple', 'banana', 'cherry']&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Alternatively, you can sort a &amp;lt;code&amp;gt;list&amp;lt;/code&amp;gt; using the &amp;lt;code&amp;gt;.sort&amp;lt;/code&amp;gt; method. This is faster than calling &amp;lt;code&amp;gt;sorted&amp;lt;/code&amp;gt;, but it modifies the list in-place and returns &amp;lt;code&amp;gt;None&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = ['apple', 'banana', 'cherry', 'date']&lt;br /&gt;
fruits.sort()&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
=== Import ===&lt;br /&gt;
&lt;br /&gt;
If you want to use functions from other libraries (including ones that you install using pip), use &amp;lt;code&amp;gt;import&amp;lt;/code&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
import time&lt;br /&gt;
&lt;br /&gt;
current_time = time.localtime()&lt;br /&gt;
print(time.strftime('%a, %d %b %Y %H:%M:%S', current_time))&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If you want to pull the functions out of their namespace, you can use &amp;lt;code&amp;gt;from ___ import ___&amp;lt;/code&amp;gt; syntax:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
from time import localtime, strftime&lt;br /&gt;
&lt;br /&gt;
current_time = localtime()&lt;br /&gt;
print(strftime('%a, %d %b %Y %H:%M:%S', current_time))&lt;br /&gt;
&lt;br /&gt;
# Be aware that this technique, although convenient, may cause unexpected behavior if the function names that you're pulling out of the namespace are already used for other purposes in Python.&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
=== File I/O ===&lt;br /&gt;
&lt;br /&gt;
You can read an entire file into a variable like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
f = open(&amp;quot;example.txt&amp;quot;)&lt;br /&gt;
file_contents = f.read()&lt;br /&gt;
&lt;br /&gt;
f.close() # free up memory when we're finished with the file&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
A better option is to use a with-block, which handles opening and closing the file for you automatically:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
with open(&amp;quot;example.txt&amp;quot;) as f:&lt;br /&gt;
    file_contents = f.read()&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
You can read a file line-by-line like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
with open(&amp;quot;example.txt&amp;quot;) as f:&lt;br /&gt;
    for line in f:&lt;br /&gt;
        print(&amp;quot;Read line: %s&amp;quot; % line.rstrip())&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
You can write to a file like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
with open(&amp;quot;example.txt&amp;quot;, &amp;quot;w&amp;quot;) as f:&lt;br /&gt;
    f.write(&amp;quot;Hello\nWorld\n&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
=== Command-Line Arguments ===&lt;br /&gt;
&lt;br /&gt;
Command line arguments are accessible in the variable &amp;lt;code&amp;gt;sys.argv&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
The following example shows a program that expects a filename as its argument, and it prints a usage message if the argument is not present ([https://stackoverflow.com/questions/983201/python-and-sys-argv source]).&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
import sys, os&lt;br /&gt;
&lt;br /&gt;
if len(sys.argv) &amp;lt; 2:&lt;br /&gt;
    sys.exit(f&amp;quot;Usage: {sys.argv[0]} filename&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
filename = sys.argv[1]&lt;br /&gt;
&lt;br /&gt;
if not os.path.exists(filename):&lt;br /&gt;
    sys.exit(f&amp;quot;Error: File '{sys.argv[1]}' not found&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Object-Oriented Programming ===&lt;br /&gt;
&lt;br /&gt;
You can define and use a class like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
class Food:&lt;br /&gt;
    # constructor:&lt;br /&gt;
    def __init__(self, name):&lt;br /&gt;
        self.name = name&lt;br /&gt;
    &lt;br /&gt;
    def format_name(self):&lt;br /&gt;
        return f&amp;quot;Gotta love to eat {self.name}&amp;quot;&lt;br /&gt;
&lt;br /&gt;
class Fruit(Food):&lt;br /&gt;
    def format_name(self):&lt;br /&gt;
        return f&amp;quot;{Food.format_name(self)} (fruit)&amp;quot;&lt;br /&gt;
&lt;br /&gt;
fruit = Fruit(&amp;quot;Cherry&amp;quot;)&lt;br /&gt;
print(fruit.format_name())&lt;br /&gt;
print(Food.get_definition())&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
This is the same example as in [[PHP#Object-Oriented_Programming|the PHP guide]].&lt;br /&gt;
&lt;br /&gt;
Some things to notice:&lt;br /&gt;
&lt;br /&gt;
* Instance methods ''always'' take &amp;lt;code&amp;gt;self&amp;lt;/code&amp;gt; as their first argument, followed by any number of additional parameters. This can be misleading for programmers familiar with other languages, because the number of arguments you feed to the method is actually ''one less than'' the number of declared parameters. Whenever you call a method on a class instance, that instance is implicitly fed into the explicitly-declared &amp;lt;code&amp;gt;self&amp;lt;/code&amp;gt; parameter of the method.&lt;br /&gt;
*: Note that the &amp;lt;code&amp;gt;self&amp;lt;/code&amp;gt; variable has the same purpose as the &amp;lt;code&amp;gt;this&amp;lt;/code&amp;gt; variable in languages like PHP, Java, JavaScript, and C++.&lt;br /&gt;
*There is no need for a &amp;lt;code&amp;gt;new&amp;lt;/code&amp;gt; keyword in Python.&lt;br /&gt;
&lt;br /&gt;
= Footnotes =&lt;br /&gt;
# {{note|interpreted}}This is an oversimplification. If you're interested, here's a quick explanation of how: In CPython (the reference implementation of Python) programs are compiled to bytecode, an intermediate representation, which is then interpreted.&lt;br /&gt;
[[Category:Module 4]]&lt;/div&gt;</summary>
		<author><name>Alex</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Python&amp;diff=2516</id>
		<title>Python</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Python&amp;diff=2516"/>
		<updated>2018-02-19T17:30:59Z</updated>

		<summary type="html">&lt;p&gt;Alex: /* Command-Line Arguments */ Format strings&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Languages like Java and C++ have lots of rules regarding variable types, syntax, return values, and so on. These can be cumbersome when you are trying to write short, quick scripts to perform tasks. This is where a ''scripting language'' comes into play.&lt;br /&gt;
&lt;br /&gt;
'''Python''' is a language well-suited to rapid prototype development. It is generally an ''interpreted language'', which means that, generally speaking, a Python program is converted line by line into instructions for the computer to execute as the program runs, instead of having a separate compilation step beforehand {{ref|interpreted}}. The syntax is clean, and it is usually clear at first glance what is going on when you write in Python.&lt;br /&gt;
&lt;br /&gt;
= Installation =&lt;br /&gt;
&lt;br /&gt;
Python may already be installed on your system. To see whether or not it is, enter the command&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ python --version&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If it tells you a version of Python '''greater than or equal to 3.5''' then you're good to go. If not, you need to do a quick package install to get it up and running. Using yum, it's just &amp;lt;code&amp;gt;sudo yum install python35; sudo alternatives --set python /usr/bin/python3&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
==== Python 2 vs Python 3 ====&lt;br /&gt;
&lt;br /&gt;
In 2008, a new version of Python – Python 3 – was released, with a number changes that made it incompatible with the previous version, Python 2. For several years, the Python community was slow to make the change to Python 3, but today, Python 3 is ''the'' standard for new code. The ''only'' reason to write Python 2 code today is because you have to work in an environment or with libraries that do not support Python 3, and that situation is becoming increasingly rare.&lt;br /&gt;
&lt;br /&gt;
'''For CSE 330 (and this guide), you ''must'' use Python 3.5 or greater.'''&lt;br /&gt;
&lt;br /&gt;
=== Pip ===&lt;br /&gt;
&lt;br /&gt;
Linux distributions have package managers like ''Apt'', ''Yum'', and ''YaST''. PHP has a package manager named ''PEAR''. It's now time to introduce Python's leading package manager: '''pip'''.&lt;br /&gt;
&lt;br /&gt;
You need to install Pip from Yum before you can use it. The package is called &amp;lt;code&amp;gt;python-pip&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Once you have pip installed, you can use it to install Python packages. Use the &amp;lt;code&amp;gt;pip-python&amp;lt;/code&amp;gt; command:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ pip-python install package_name # RHEL&lt;br /&gt;
$ pip install package_name # Debian&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
= Running Python =&lt;br /&gt;
&lt;br /&gt;
There are two common ways to run Python code: via the console, and via a Python script file.&lt;br /&gt;
&lt;br /&gt;
=== The Python Console ===&lt;br /&gt;
&lt;br /&gt;
The Python console enables you to experiment with code without opening a text editor. To enter the Python console, simply type the ''python'' command at the terminal:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ python&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
To leave the interactive console, either type &amp;lt;code&amp;gt;quit()&amp;lt;/code&amp;gt; or press &amp;lt;code&amp;gt;Ctrl-D&amp;lt;/code&amp;gt; (on both Mac and Windows).&lt;br /&gt;
&lt;br /&gt;
=== Python Script Files ===&lt;br /&gt;
&lt;br /&gt;
You can also save Python script files for later use. The extension for Python scripts is &amp;lt;code&amp;gt;*.py&amp;lt;/code&amp;gt;. To run a script file, simply feed its path as an argument to the &amp;lt;code&amp;gt;python&amp;lt;/code&amp;gt; command in Terminal:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ python my_script.py&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Python Syntax and Language Components =&lt;br /&gt;
&lt;br /&gt;
This section contains a very brief overview of Python syntax. For a more comprehensive introduction, see [http://docs.python.org/tutorial/ the Python docs].&lt;br /&gt;
&lt;br /&gt;
=== Python's Type System ===&lt;br /&gt;
&lt;br /&gt;
Python is a dynamically-typed, strongly-typed, and duck-typed language. What does that mean? Well, let's take those categories one by one:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;ol&amp;gt;&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
'''Dynamic typing''', in contrast to ''static typing'' means that the types of objects can be changed. In Java, for instance, if you tried to write the following code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
int c = 2;&lt;br /&gt;
c = &amp;quot;fish&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Your code would fail to compile, because the Java compiler wouldn't allow you to change the type of the variable &amp;lt;code&amp;gt;c&amp;lt;/code&amp;gt; from &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt; to &amp;lt;code&amp;gt;String&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Python, however, is just fine with that. You can write:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
c = 2&lt;br /&gt;
c = &amp;quot;fish&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
And Python will happily do what you ask.&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
'''Strong typing''', in contrast to ''weak typing'', means, roughly, that a language won't implicitly convert types for you. So far, you've used a lot of PHP, which is very weakly typed. For example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;php&amp;quot;&amp;gt;&lt;br /&gt;
echo &amp;quot;10&amp;quot; . 2;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In PHP, this works just fine. The PHP interpreter sees that &amp;lt;code&amp;gt;2&amp;lt;/code&amp;gt; is an int, and silently converts it to a string for you, so that &amp;lt;code&amp;gt;&amp;quot;10&amp;quot;. 2&amp;lt;/code&amp;gt; equals &amp;lt;code&amp;gt;&amp;quot;102&amp;quot;&amp;lt;/code&amp;gt;. The problem with weak typing is that it can make it unclear to the programmer why things are happening the way they are. For instance, in PHP, the expression &amp;lt;code&amp;gt;&amp;quot;10&amp;quot; == 10&amp;lt;/code&amp;gt; is true, which can be less than obvious. Python, however, tries to disallow that sort of thing:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
&amp;quot;10&amp;quot; + &amp;quot;10&amp;quot; # Allowed – concatenates the two strings.&lt;br /&gt;
10   +  10  # Allowed – adds the two ints.&lt;br /&gt;
&amp;quot;10&amp;quot; +  10  # Not allowed – raises a TypeError&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Perhaps the one exception to this rule is the relationship between numeric types; it's perfectly fine to add a float to an int, for example.&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
'''Duck-typing''' is a little bit different than the other categories, because it doesn't really have a direct opposite. Essentially, duck-typing is the philosophy that &amp;quot;If it walks like a duck, and quacks like a duck, it's a duck.&amp;quot; In programming terms, that means that we often don't care what type an object is, as long as it can do the things we ask.&lt;br /&gt;
&lt;br /&gt;
Let's look at an example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
# This function doubles the value it's passed.&lt;br /&gt;
def double(thing):&lt;br /&gt;
    return thing + thing&lt;br /&gt;
double(10) # Returns 20&lt;br /&gt;
double(&amp;quot;fish&amp;quot;) # Returns &amp;quot;fishfish&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If this were Java, we'd have to write two different methods here: one for things of type &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt;, and one for things of type &amp;lt;code&amp;gt;String&amp;lt;/code&amp;gt;. Since this is Python, though, we don't have to do that. Instead, Python lets us say, essentially: &amp;quot;This function uses the &amp;lt;code&amp;gt;+&amp;lt;/code&amp;gt; operator, so you can pass whatever object you want to the function, as long as the function supports the &amp;lt;code&amp;gt;+&amp;lt;/code&amp;gt; operator&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
To quote [https://groups.google.com/forum/?hl=en#!msg/comp.lang.python/CCs2oJdyuzc/NYjla5HKMOIJ Alex Martelli], one of the key people in the Python project,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;blockquote&amp;gt;&lt;br /&gt;
&amp;quot;[Don't] check whether it IS-a duck: check whether it QUACKS-like-a duck, WALKS-like-a duck, etc, etc, depending on exactly what subset of duck-like behaviour you need.&amp;quot;&lt;br /&gt;
&amp;lt;/blockquote&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&amp;lt;/ol&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Basic Types ===&lt;br /&gt;
&lt;br /&gt;
In Python, the basic scalar types are:&lt;br /&gt;
&lt;br /&gt;
# &amp;lt;code&amp;gt;str&amp;lt;/code&amp;gt; – a string.&lt;br /&gt;
# &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt; – an integer object with unlimited digits.&lt;br /&gt;
# &amp;lt;code&amp;gt;bool&amp;lt;/code&amp;gt; – a Boolean value.&lt;br /&gt;
# &amp;lt;code&amp;gt;float&amp;lt;/code&amp;gt; – a floating point number; generally equivalent to &amp;lt;code&amp;gt;double&amp;lt;/code&amp;gt; in Java.&lt;br /&gt;
# &amp;lt;code&amp;gt;bytes&amp;lt;/code&amp;gt; – represents a collection of bytes; you're unlikely to use this often.&lt;br /&gt;
&lt;br /&gt;
Casting is done in the C style - to parse an &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt; from a string, for instance, you'd write &amp;lt;code&amp;gt;int(&amp;quot;123&amp;quot;)&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== Basic Control Flow ===&lt;br /&gt;
In Python, blocks of code are delineated using colons and indentation instead of curly braces. '''''That means that proper indentation is mandatory.''''' Every time you use a colon, you must indent one step further, and every time a block ends, you must unindent a step.&lt;br /&gt;
&lt;br /&gt;
Conditional statements are done using the &amp;lt;code&amp;gt;if&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;elif&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;else&amp;lt;/code&amp;gt; operators, like in the example below - pay attention to the indentation:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
cookies_left = 10&lt;br /&gt;
cake_slices_left = 3&lt;br /&gt;
if cookies_left &amp;gt; 10:&lt;br /&gt;
    print(&amp;quot;Lots of cookies!&amp;quot;)&lt;br /&gt;
elif cookies_left &amp;gt; 8:&lt;br /&gt;
    print(&amp;quot;Plenty left!&amp;quot;)&lt;br /&gt;
elif cookies_left == 5:&lt;br /&gt;
    print(&amp;quot;Halfway done!&amp;quot;)&lt;br /&gt;
else:&lt;br /&gt;
    if cake_slices_left == 3:&lt;br /&gt;
        print(&amp;quot;Lots of cake!&amp;quot;)&lt;br /&gt;
    elif cake_slices_left == 2:&lt;br /&gt;
        print(&amp;quot;One slice gone!&amp;quot;)&lt;br /&gt;
    else:&lt;br /&gt;
        print(&amp;quot;Little to no cake left!&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== An Example Python Script ===&lt;br /&gt;
&lt;br /&gt;
In my mind, there's no better way to learn Python than to be immersed in a simple example script.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
print(&amp;quot;Hello World&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
fruits = [&amp;quot;apple&amp;quot;, &amp;quot;banana&amp;quot;, &amp;quot;cherry&amp;quot;, &amp;quot;date&amp;quot;]&lt;br /&gt;
for fruit in fruits:&lt;br /&gt;
    print(f&amp;quot;I always love to eat a fresh {fruit}&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Map the fruits list over to a new list containing the length of the fruit strings:&lt;br /&gt;
fruit_size = [len(fruit) for fruit in fruits]&lt;br /&gt;
&lt;br /&gt;
avg_fruit_size = sum(fruit_size) / len(fruit_size)&lt;br /&gt;
print(f&amp;quot;The average fruit string length is {avg_fruit_size:.2f}.&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Some things to notice:&lt;br /&gt;
&lt;br /&gt;
* Printing is achieved using the &amp;lt;code&amp;gt;print()&amp;lt;/code&amp;gt; function.&lt;br /&gt;
* Comments start with a pound symbol &amp;lt;code&amp;gt;#&amp;lt;/code&amp;gt;.&lt;br /&gt;
* We can transform/map a list to a new list in just one line!&lt;br /&gt;
&lt;br /&gt;
For some more examples, see [https://wiki.python.org/moin/SimplePrograms the Python wiki].&lt;br /&gt;
&lt;br /&gt;
=== A Few Gotchas ===&lt;br /&gt;
&lt;br /&gt;
Here are a few things you may not expect when starting out with Python:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;ol&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
Strings can be delimited using either single quotes (&amp;lt;code&amp;gt;'&amp;lt;/code&amp;gt;) or double quotes (&amp;lt;code&amp;gt;&amp;quot;&amp;lt;/code&amp;gt;), so &amp;lt;code&amp;gt;'Python'&amp;lt;/code&amp;gt; is the same as &amp;lt;code&amp;gt;&amp;quot;Python&amp;quot;&amp;lt;/code. You can also use three sets of quotes (&amp;lt;code&amp;gt;'''&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;&amp;quot;&amp;quot;&amp;quot;&amp;lt;/code&amp;gt;) to delineate a multiple-line string, like so:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
long_string = &amp;quot;&amp;quot;&amp;quot;This&lt;br /&gt;
is my&lt;br /&gt;
very long&lt;br /&gt;
multiple-line&lt;br /&gt;
string&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
To compare the equality of two objects, use the &amp;lt;code&amp;gt;==&amp;lt;/code&amp;gt; operator. To compare the identity of two objects (i.e. whether or not they are literally the same object, at the same place in memory), use the &amp;lt;code&amp;gt;is&amp;lt;/code&amp;gt; operator. These correspond, respectively to &amp;lt;code&amp;gt;.equals()&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;==&amp;lt;/code&amp;gt; in Java.&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
The &amp;lt;code&amp;gt;/&amp;lt;/code&amp;gt; operator performs floating-point division, not integer division, even when both its arguments are integers. If you want to do integer division, use the &amp;lt;code&amp;gt;//&amp;lt;/code&amp;gt; operator. Let's look at an example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
9   / 10    == 0.9 # Floating-point division&lt;br /&gt;
9.0 / 10.0  == 0.9 # Floating-point division&lt;br /&gt;
9   // 10   == 0   # Integer division&lt;br /&gt;
9.0 // 10.0 == 0.0 # Integer division, even though the resulting value is a float&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
As discussed in the section [[#Python's_Type_System|Python's Type System]], you can't combine strings and numbers using the &amp;lt;code&amp;gt;+&amp;lt;/code&amp;gt; operator. Instead, you'll have to use one of the following methods of string formatting:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
  &lt;br /&gt;
# Technique 1 – printf-style Formatting&lt;br /&gt;
# This is a classic style of string formatting, used in many programming languages, including in Java's String.format.&lt;br /&gt;
&amp;quot;You scored %d out of %d!&amp;quot; % (score, questions)&lt;br /&gt;
&lt;br /&gt;
# Technique 2 – str.format&lt;br /&gt;
&amp;quot;You scored {} out of {}!&amp;quot;.format(score, questions)&lt;br /&gt;
&lt;br /&gt;
# Technique 3 – f-strings&lt;br /&gt;
# These were only introduced in Python 3.6 but they're very convenient.&lt;br /&gt;
f&amp;quot;You scored {score} out of {questions}!&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# Technique 4 - String Concatenation&lt;br /&gt;
# This is fine for small things, but for more complicated stuff, use one of the other techniques.&lt;br /&gt;
&amp;quot;You scored &amp;quot; + str(score) + &amp;quot; out of &amp;quot; + str(questions) + &amp;quot;!&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&amp;lt;/ol&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Functions ===&lt;br /&gt;
&lt;br /&gt;
Define functions using the &amp;lt;code&amp;gt;def&amp;lt;/code&amp;gt; keyword:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def hello(name):&lt;br /&gt;
    print(f&amp;quot;Hello, {name}!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Invoke functions using parentheses:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
hello(&amp;quot;Batman&amp;quot;)&lt;br /&gt;
hello(&amp;quot;Superman&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Functions can have optional arguments; however, these must come after any required arguments:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def hello(name=&amp;quot;User&amp;quot;):&lt;br /&gt;
    print(f&amp;quot;Hello, {name}!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
hello() # Prints &amp;quot;Hello, User!&amp;quot;&lt;br /&gt;
hello(&amp;quot;Sarah&amp;quot;) # Prints &amp;quot;Hello, Sarah!&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Functions are just regular objects in Python, meaning you can do stuff like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def hello(name=&amp;quot;User&amp;quot;):&lt;br /&gt;
    print(f&amp;quot;Hello, {name}!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
greeting = hello&lt;br /&gt;
&lt;br /&gt;
greeting(&amp;quot;Siwei&amp;quot;) # Prints &amp;quot;Hello, Siwei!&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Collection Types ===&lt;br /&gt;
Python has a few basic, built-in collection types. They each have their own special use cases, but they share a lot of similarities. All built-in data structures in Python are zero-indexed, for instance.&lt;br /&gt;
&lt;br /&gt;
To obtain the number of elements in a collection, use the &amp;lt;code&amp;gt;len()&amp;lt;/code&amp;gt; function, like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish'] # This is a list; you'll learn about them below.&lt;br /&gt;
&lt;br /&gt;
len(pets) # Returns 3&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To check if a collection contains an item, use the &amp;lt;code&amp;gt;in&amp;lt;/code&amp;gt; operator:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish'] # This is a list; you'll learn about them below.&lt;br /&gt;
&lt;br /&gt;
'Dog' in pets # Returns True&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Helpfully, the Python Software Foundation maintains a page containing the asymptotic complexities of important operations on major Python data structures. It's available [https://wiki.python.org/moin/TimeComplexity here].&lt;br /&gt;
&lt;br /&gt;
==== Lists ====&lt;br /&gt;
&lt;br /&gt;
Unlike languages like Java and C, Python's array-like type doesn't have fixed length. Instead, a &amp;lt;code&amp;gt;list&amp;lt;/code&amp;gt; is a dynamic array (like Java's &amp;lt;code&amp;gt;ArrayList&amp;lt;/code&amp;gt;) of objects of any type. Here's an example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = [&amp;quot;Apple&amp;quot;, &amp;quot;Pear&amp;quot;, &amp;quot;Orange&amp;quot;] # Lists can be creating by placing their items between square brackets&lt;br /&gt;
&lt;br /&gt;
random_items = ['Apple', 12312, 2.0, [1, 2, 3]] # Lists can contain objects of different types - even other lists!&lt;br /&gt;
&lt;br /&gt;
pets.append('Turtle') # Adds 'Turtle' to the end of pets&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For the next few examples, we'll be using the following list:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish', 'Turtle', 'Lizard', 'Snake']&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access or assign elements of a list, use the &amp;lt;code&amp;gt;[]&amp;lt;/code&amp;gt; operator.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[0] # Returns 'Dog'&lt;br /&gt;
pets[1] = 'Cow' # Sets pets[1] to 'Cow'&lt;br /&gt;
pets[1] = 'Cat' # Sets pets[1] back to 'Cat' &lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You can also access or assign lists using negative indices, which will return elements starting from the end of the list:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[-1] # Returns 'Snake'&lt;br /&gt;
pets[-2] # Returns 'Lizard'&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You can also use 'slice notation' to obtain or assign subsets of lists:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[start:end] # Returns items from index start to index end - 1.&lt;br /&gt;
pets[start:]    # Returns items from index start to the end of the list, inclusive.&lt;br /&gt;
pets[:end]      # Returns items from the beginning of the list to index end - 1.&lt;br /&gt;
pets[:]         # Returns every item in the list&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
There's also a third, optional argument: &amp;lt;code&amp;gt;step&amp;lt;/code&amp;gt;, which lets you jump over values:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[start:end:step] # Returns items from index start to index end - 1, jumping step values at a time&lt;br /&gt;
&lt;br /&gt;
# Examples:&lt;br /&gt;
pets[1:5:2] # Returns items from index 1 to index 4, jumping 2 at a time, so ['Cat', 'Turtle']&lt;br /&gt;
pets[::3] # Returns all items in the list, jumping 3 at a time, so ['Dog', 'Turtle']&lt;br /&gt;
pets[::-1] # Returns all items in the list, jumping -1 at a time. This reverses the list, so ['Snake', 'Lizard', 'Turtle', 'Fish', 'Cat', 'Dog']&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Lists have all the performance characteristics you'd expect of a dynamic array - constant-time indexing, amortized constant-time appends, and so on.&lt;br /&gt;
&lt;br /&gt;
==== Tuples ====&lt;br /&gt;
&lt;br /&gt;
Python has a special data type called &amp;lt;code&amp;gt;tuple&amp;lt;/code&amp;gt;, which is exactly the same as a list except for the fact that it cannot be modified, so you can't append or replace items.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
cities = ('St. Louis', 'Los Angeles', 'Seattle') # Tuples are defined using parentheses.&lt;br /&gt;
numbers = 1, 2, 3 # You can also omit the parentheses if it's unambiguous&lt;br /&gt;
single_item_tuple = (1,) # To make a tuple with only one item, put a comma after it&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Tuples also enable you to have multiple return values from a function:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def compute_length(string):&lt;br /&gt;
    str_len = len(string)&lt;br /&gt;
    if str_len &amp;lt; 5:&lt;br /&gt;
        return str_len, &amp;quot;short&amp;quot;&lt;br /&gt;
    elif str_len &amp;lt; 40:&lt;br /&gt;
        return str_len, &amp;quot;medium&amp;quot;&lt;br /&gt;
    return str_len, &amp;quot;long&amp;quot;&lt;br /&gt;
&lt;br /&gt;
length, description = compute_length(&amp;quot;Four score and seven years ago&amp;quot;)&lt;br /&gt;
print(&amp;quot;The %s string is %d characters long.&amp;quot; % (description, length))&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
The above example also demonstrates Python's if...elif...else conditional structure.&lt;br /&gt;
&lt;br /&gt;
==== Dictionaries ====&lt;br /&gt;
&lt;br /&gt;
Python has another datatype called a '''dictionary''' (or &amp;lt;code&amp;gt;dict&amp;lt;/code&amp;gt;, for short), which are like ''Maps'' in Java, ''associative arrays'' in PHP, and ''object literals'' in JavaScript (coming up soon in Module 6). Essentially, they enable you to use any immutable object as the key in your data structure. &amp;lt;code&amp;gt;dict&amp;lt;/code&amp;gt; objects can be created using either the &amp;lt;code&amp;gt;dict&amp;lt;/code&amp;gt; function, or by placing items between curly braces, separating keys and values using colons:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits_in_bowl = {&lt;br /&gt;
    'apple': 4,&lt;br /&gt;
    'banana': 2,&lt;br /&gt;
    'cherry': 0,&lt;br /&gt;
    'date': 12&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
apple_count = fruits_in_bowl['apple'] # Equals 4&lt;br /&gt;
&lt;br /&gt;
fruits_in_bowl['pear'] = 9 # Sets 'pear' in the dictionary to 9.&lt;br /&gt;
&lt;br /&gt;
for fruit, num in fruits_in_bowl.items():&lt;br /&gt;
    print(f&amp;quot;There are {num} {fruit}(s) in the bowl.&amp;quot; % (num, fruit))&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If you only want the keys from a dictionary, you can just iterate over it directly, like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
for fruit in fruits_in_bowl:&lt;br /&gt;
    print(fruit)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If you want only the values but not the keys from a dictionary, use &amp;lt;code&amp;gt;my_dictionary.values()&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
==== Sets ==== &lt;br /&gt;
A &amp;lt;code&amp;gt;set&amp;lt;/code&amp;gt; is an unordered collection of unique items, with constant-time membership checking. &lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = {'Apple', 'Apple', 'Apple', 'Pear'} # The set removes duplicates, so it will only contain {'Apple', 'Pear'}&lt;br /&gt;
fruits = set(['Apple', 'Apple', 'Apple', 'Pear']) # This line transforms a list into a set&lt;br /&gt;
print('Apple' in fruits) # Constant-time!&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Loops ===&lt;br /&gt;
&lt;br /&gt;
In Python, while loops are written like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
i = 0&lt;br /&gt;
while i &amp;lt; 10:&lt;br /&gt;
    i += 1&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
For loops are written like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish']&lt;br /&gt;
&lt;br /&gt;
for pet in pets:&lt;br /&gt;
    print(pet)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
To iterate over a range of numbers, you can use the convenient &amp;lt;code&amp;gt;range&amp;lt;/code&amp;gt; function, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
for i in range(20, 30): # If you omit the first argument to range, it's assumed to be zero.&lt;br /&gt;
    print(i)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Note that &amp;lt;code&amp;gt;range&amp;lt;/code&amp;gt; provides a closed-open range. That is to say, it is inclusive of its lower bound and exclusive of its upper bound. To be very explicit about it:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
list(range(3, 6)) == [3, 4, 5]&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Unlike in other languages you may know, the following is not good practice in Python:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish']&lt;br /&gt;
&lt;br /&gt;
# BAD PRACTICE. DO NOT USE.&lt;br /&gt;
for i in range(len(pets)):&lt;br /&gt;
    pet = pets[i]&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Instead, if you need to access both a variable and its index, use the &amp;lt;code&amp;gt;enumerate&amp;lt;/code&amp;gt; function, which allows you to iterate through a group of items, along with their indexes, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish']&lt;br /&gt;
&lt;br /&gt;
for index, pet in enumerate(pets):&lt;br /&gt;
    print(f&amp;quot;{pet} at index {index}&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Generator Expressions and Comprehensions ===&lt;br /&gt;
&lt;br /&gt;
A generator is a special kind of object that, basically, represents a collection of items using a value and a function for generating the next value in the collection. In other words, it's a way of creating something that behaves like a list, but which only generates one value at a time, and discards a value when it's done with it. Say, for example, you wanted to do an operation on 10,000,000,000,000 numbers. You could put them all in a list, then iterate over the list, but that would take a lot of memory, plus you'd have to create and fill the entire list before beginning to actually work on your problem. Instead, you'd probably be better off using a generator; telling the computer, essentially: “The starting value is 0. When I ask for the next number in the collection, add 1 to current value and give me that.”&lt;br /&gt;
&lt;br /&gt;
A generator expression is an expression that is evaluated to create a generator. They're super useful. Generator expressions can take two forms – they can be used with and without a condition:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
(EXPRESSION for VARIABLE in ITERABLE) # Unconditional&lt;br /&gt;
(EXPRESSION for VARIABLE in ITERABLE if CONDITION) # Conditional&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
For our purposes, you can think of an iterable as anything you can do a for loop over. Let's take a look at a generator expression in use:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
double_even_digits = (number * 2 for number in range(10) if number % 2 == 0)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
That line says that &amp;lt;code&amp;gt;double_even_digits&amp;lt;/code&amp;gt; is every even number between 0 and 10 multiplied by two. Simple enough, right? If we wanted to use all of the numbers, not just the even ones, we could simply remove the if statement at the end of the expression.&lt;br /&gt;
&lt;br /&gt;
Here's the thing, though: if you were to print &amp;lt;code&amp;gt;double_even_digits&amp;lt;/code&amp;gt;, instead of a nice bunch of numbers, you'd get something that looks like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&amp;lt;generator object &amp;lt;genexpr&amp;gt;&amp;lt;code&amp;gt;at 0x107fc92b0&amp;gt;&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
That's because generators are lazy! They don't generate their values until those values are needed, and they discard values once they're no longer needed. As a result, '''you can only iterate over a generator once'''. In this case, you can't print out the whole generator, because it hasn't generated all the values yet. You can, however, iterate over the generator, and print its values one at a time, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
for number in double_even_digits:&lt;br /&gt;
    print(number)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
You can also make a list out of the generator, which will go through all the items in the generator and put them in a list, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
even_number_list = list(double_even_digits)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
That's actually a great segue to the second topic of this section: comprehensions. A comprehension is just a prettier way to make lists, sets, and dicts out of a generator expressions.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
# If you want a list:&lt;br /&gt;
list(i for i in range(10) if i % 2 == 0) # Don't do this&lt;br /&gt;
[i for i in range(10) if i % 2 == 0] # Use a list comprehension instead!&lt;br /&gt;
&lt;br /&gt;
# If you want a set:&lt;br /&gt;
set(i for i in range(10) if i % 2 == 0) # Don't do this&lt;br /&gt;
{i for i in range(10) if i % 2 == 0} # Use a set comprehension instead!&lt;br /&gt;
&lt;br /&gt;
# If you want a dict:&lt;br /&gt;
dict((i, i + 1) for i in range(10) if i % 2 == 0) # Don't do this&lt;br /&gt;
{i : i + 1 for i in range(10) if i % 2 == 0} # Use a dict comprehension instead!&lt;br /&gt;
&lt;br /&gt;
# If you want a tuple:&lt;br /&gt;
tuple(i for i in range(10) if i % 2 == 0) # Unfortunately, there's no better way to do this&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
In general, generators and comprehensions should be used whenever possible - they're the fastest and easiest way to build collections. If you ever see yourself writing code like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
# BAD PRACTICE! DO NOT USE!&lt;br /&gt;
digits = []&lt;br /&gt;
for digit in range(10):&lt;br /&gt;
    digits.append(digit)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Don't do it! Instead, use a generator expression or comprehension, as appropriate. A good way to decide whether a generator expression or comprehension is better for this situation is that, if you're just going to be iterating over your collection once, you should use an generator expression. If not, use a comprehension.&lt;br /&gt;
&lt;br /&gt;
=== Sorting ===&lt;br /&gt;
&lt;br /&gt;
Sorting in Python is frequently performed using the &amp;lt;code&amp;gt;sorted&amp;lt;/code&amp;gt; function, which takes two arguments: an iterable (anything you can do a for-loop over, including lists and tuples) and a function used to evaluate each item. If the function is omitted, Python will try to sort the lists by value.&lt;br /&gt;
&lt;br /&gt;
The following example demonstrates using an inline function, which Python calls a ''lambda''.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = ['apple', 'banana', 'cherry', 'date']&lt;br /&gt;
&lt;br /&gt;
# sort the fruits by string length&lt;br /&gt;
new_fruits = sorted(fruits, key=lambda v: len(v) // 2)&lt;br /&gt;
&lt;br /&gt;
print(new_fruits) # ['date', 'apple', 'banana', 'cherry']&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Alternatively, you can sort a &amp;lt;code&amp;gt;list&amp;lt;/code&amp;gt; using the &amp;lt;code&amp;gt;.sort&amp;lt;/code&amp;gt; method. This is faster than calling &amp;lt;code&amp;gt;sorted&amp;lt;/code&amp;gt;, but it modifies the list in-place and returns &amp;lt;code&amp;gt;None&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = ['apple', 'banana', 'cherry', 'date']&lt;br /&gt;
fruits.sort()&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
=== Import ===&lt;br /&gt;
&lt;br /&gt;
If you want to use functions from other libraries (including ones that you install using pip), use &amp;lt;code&amp;gt;import&amp;lt;/code&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
import time&lt;br /&gt;
&lt;br /&gt;
current_time = time.localtime()&lt;br /&gt;
print(time.strftime('%a, %d %b %Y %H:%M:%S', current_time))&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If you want to pull the functions out of their namespace, you can use &amp;lt;code&amp;gt;from ___ import ___&amp;lt;/code&amp;gt; syntax:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
from time import localtime, strftime&lt;br /&gt;
&lt;br /&gt;
current_time = localtime()&lt;br /&gt;
print(strftime('%a, %d %b %Y %H:%M:%S', current_time))&lt;br /&gt;
&lt;br /&gt;
# Be aware that this technique, although convenient, may cause unexpected behavior if the function names that you're pulling out of the namespace are already used for other purposes in Python.&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
=== File I/O ===&lt;br /&gt;
&lt;br /&gt;
You can read an entire file into a variable like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
f = open(&amp;quot;example.txt&amp;quot;)&lt;br /&gt;
file_contents = f.read()&lt;br /&gt;
&lt;br /&gt;
f.close() # free up memory when we're finished with the file&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
A better option is to use a with-block, which handles opening and closing the file for you automatically:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
with open(&amp;quot;example.txt&amp;quot;) as f:&lt;br /&gt;
    file_contents = f.read()&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
You can read a file line-by-line like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
with open(&amp;quot;example.txt&amp;quot;) as f:&lt;br /&gt;
    for line in f:&lt;br /&gt;
        print(&amp;quot;Read line: %s&amp;quot; % line.rstrip())&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
You can write to a file like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
with open(&amp;quot;example.txt&amp;quot;, &amp;quot;w&amp;quot;) as f:&lt;br /&gt;
    f.write(&amp;quot;Hello\nWorld\n&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
=== Command-Line Arguments ===&lt;br /&gt;
&lt;br /&gt;
Command line arguments are accessible in the variable &amp;lt;code&amp;gt;sys.argv&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
The following example shows a program that expects a filename as its argument, and it prints a usage message if the argument is not present ([https://stackoverflow.com/questions/983201/python-and-sys-argv source]).&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
import sys, os&lt;br /&gt;
&lt;br /&gt;
if len(sys.argv) &amp;lt; 2:&lt;br /&gt;
    sys.exit(f&amp;quot;Usage: {sys.argv[0]} filename&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
filename = sys.argv[1]&lt;br /&gt;
&lt;br /&gt;
if not os.path.exists(filename):&lt;br /&gt;
    sys.exit(f&amp;quot;Error: File '{sys.argv[1]}' not found&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Object-Oriented Programming ===&lt;br /&gt;
&lt;br /&gt;
You can define and use a class like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
class Food:&lt;br /&gt;
    # constructor:&lt;br /&gt;
    def __init__(self, name):&lt;br /&gt;
        self.name = name&lt;br /&gt;
    &lt;br /&gt;
    def format_name(self):&lt;br /&gt;
        return &amp;quot;Gotta love to eat &amp;quot; + self.name&lt;br /&gt;
&lt;br /&gt;
class Fruit(Food):&lt;br /&gt;
    def format_name(self):&lt;br /&gt;
        return Food.format_name(self) + &amp;quot; (fruit)&amp;quot;&lt;br /&gt;
&lt;br /&gt;
fruit = Fruit(&amp;quot;Cherry&amp;quot;)&lt;br /&gt;
print(fruit.format_name())&lt;br /&gt;
print(Food.get_definition())&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
This is the same example as in [[PHP#Object-Oriented_Programming|the PHP guide]].&lt;br /&gt;
&lt;br /&gt;
Some things to notice:&lt;br /&gt;
&lt;br /&gt;
* Instance methods ''always'' take &amp;lt;code&amp;gt;self&amp;lt;/code&amp;gt; as their first argument, followed by any number of additional parameters. This can be misleading for programmers familiar with other languages, because the number of arguments you feed to the method is actually ''one less than'' the number of declared parameters. Whenever you call a method on a class instance, that instance is implicitly fed into the explicitly-declared &amp;lt;code&amp;gt;self&amp;lt;/code&amp;gt; parameter of the method.&lt;br /&gt;
*: Note that the &amp;lt;code&amp;gt;self&amp;lt;/code&amp;gt; variable has the same purpose as the &amp;lt;code&amp;gt;this&amp;lt;/code&amp;gt; variable in languages like PHP, Java, JavaScript, and C++.&lt;br /&gt;
*There is no need for a &amp;lt;code&amp;gt;new&amp;lt;/code&amp;gt; keyword in Python.&lt;br /&gt;
&lt;br /&gt;
= Footnotes =&lt;br /&gt;
# {{note|interpreted}}This is an oversimplification. If you're interested, here's a quick explanation of how: In CPython (the reference implementation of Python) programs are compiled to bytecode, an intermediate representation, which is then interpreted.&lt;br /&gt;
[[Category:Module 4]]&lt;/div&gt;</summary>
		<author><name>Alex</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Python&amp;diff=2515</id>
		<title>Python</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Python&amp;diff=2515"/>
		<updated>2018-02-19T17:29:36Z</updated>

		<summary type="html">&lt;p&gt;Alex: /* Loops */  Format strings&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Languages like Java and C++ have lots of rules regarding variable types, syntax, return values, and so on. These can be cumbersome when you are trying to write short, quick scripts to perform tasks. This is where a ''scripting language'' comes into play.&lt;br /&gt;
&lt;br /&gt;
'''Python''' is a language well-suited to rapid prototype development. It is generally an ''interpreted language'', which means that, generally speaking, a Python program is converted line by line into instructions for the computer to execute as the program runs, instead of having a separate compilation step beforehand {{ref|interpreted}}. The syntax is clean, and it is usually clear at first glance what is going on when you write in Python.&lt;br /&gt;
&lt;br /&gt;
= Installation =&lt;br /&gt;
&lt;br /&gt;
Python may already be installed on your system. To see whether or not it is, enter the command&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ python --version&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If it tells you a version of Python '''greater than or equal to 3.5''' then you're good to go. If not, you need to do a quick package install to get it up and running. Using yum, it's just &amp;lt;code&amp;gt;sudo yum install python35; sudo alternatives --set python /usr/bin/python3&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
==== Python 2 vs Python 3 ====&lt;br /&gt;
&lt;br /&gt;
In 2008, a new version of Python – Python 3 – was released, with a number changes that made it incompatible with the previous version, Python 2. For several years, the Python community was slow to make the change to Python 3, but today, Python 3 is ''the'' standard for new code. The ''only'' reason to write Python 2 code today is because you have to work in an environment or with libraries that do not support Python 3, and that situation is becoming increasingly rare.&lt;br /&gt;
&lt;br /&gt;
'''For CSE 330 (and this guide), you ''must'' use Python 3.5 or greater.'''&lt;br /&gt;
&lt;br /&gt;
=== Pip ===&lt;br /&gt;
&lt;br /&gt;
Linux distributions have package managers like ''Apt'', ''Yum'', and ''YaST''. PHP has a package manager named ''PEAR''. It's now time to introduce Python's leading package manager: '''pip'''.&lt;br /&gt;
&lt;br /&gt;
You need to install Pip from Yum before you can use it. The package is called &amp;lt;code&amp;gt;python-pip&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Once you have pip installed, you can use it to install Python packages. Use the &amp;lt;code&amp;gt;pip-python&amp;lt;/code&amp;gt; command:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ pip-python install package_name # RHEL&lt;br /&gt;
$ pip install package_name # Debian&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
= Running Python =&lt;br /&gt;
&lt;br /&gt;
There are two common ways to run Python code: via the console, and via a Python script file.&lt;br /&gt;
&lt;br /&gt;
=== The Python Console ===&lt;br /&gt;
&lt;br /&gt;
The Python console enables you to experiment with code without opening a text editor. To enter the Python console, simply type the ''python'' command at the terminal:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ python&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
To leave the interactive console, either type &amp;lt;code&amp;gt;quit()&amp;lt;/code&amp;gt; or press &amp;lt;code&amp;gt;Ctrl-D&amp;lt;/code&amp;gt; (on both Mac and Windows).&lt;br /&gt;
&lt;br /&gt;
=== Python Script Files ===&lt;br /&gt;
&lt;br /&gt;
You can also save Python script files for later use. The extension for Python scripts is &amp;lt;code&amp;gt;*.py&amp;lt;/code&amp;gt;. To run a script file, simply feed its path as an argument to the &amp;lt;code&amp;gt;python&amp;lt;/code&amp;gt; command in Terminal:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ python my_script.py&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Python Syntax and Language Components =&lt;br /&gt;
&lt;br /&gt;
This section contains a very brief overview of Python syntax. For a more comprehensive introduction, see [http://docs.python.org/tutorial/ the Python docs].&lt;br /&gt;
&lt;br /&gt;
=== Python's Type System ===&lt;br /&gt;
&lt;br /&gt;
Python is a dynamically-typed, strongly-typed, and duck-typed language. What does that mean? Well, let's take those categories one by one:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;ol&amp;gt;&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
'''Dynamic typing''', in contrast to ''static typing'' means that the types of objects can be changed. In Java, for instance, if you tried to write the following code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
int c = 2;&lt;br /&gt;
c = &amp;quot;fish&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Your code would fail to compile, because the Java compiler wouldn't allow you to change the type of the variable &amp;lt;code&amp;gt;c&amp;lt;/code&amp;gt; from &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt; to &amp;lt;code&amp;gt;String&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Python, however, is just fine with that. You can write:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
c = 2&lt;br /&gt;
c = &amp;quot;fish&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
And Python will happily do what you ask.&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
'''Strong typing''', in contrast to ''weak typing'', means, roughly, that a language won't implicitly convert types for you. So far, you've used a lot of PHP, which is very weakly typed. For example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;php&amp;quot;&amp;gt;&lt;br /&gt;
echo &amp;quot;10&amp;quot; . 2;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In PHP, this works just fine. The PHP interpreter sees that &amp;lt;code&amp;gt;2&amp;lt;/code&amp;gt; is an int, and silently converts it to a string for you, so that &amp;lt;code&amp;gt;&amp;quot;10&amp;quot;. 2&amp;lt;/code&amp;gt; equals &amp;lt;code&amp;gt;&amp;quot;102&amp;quot;&amp;lt;/code&amp;gt;. The problem with weak typing is that it can make it unclear to the programmer why things are happening the way they are. For instance, in PHP, the expression &amp;lt;code&amp;gt;&amp;quot;10&amp;quot; == 10&amp;lt;/code&amp;gt; is true, which can be less than obvious. Python, however, tries to disallow that sort of thing:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
&amp;quot;10&amp;quot; + &amp;quot;10&amp;quot; # Allowed – concatenates the two strings.&lt;br /&gt;
10   +  10  # Allowed – adds the two ints.&lt;br /&gt;
&amp;quot;10&amp;quot; +  10  # Not allowed – raises a TypeError&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Perhaps the one exception to this rule is the relationship between numeric types; it's perfectly fine to add a float to an int, for example.&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
'''Duck-typing''' is a little bit different than the other categories, because it doesn't really have a direct opposite. Essentially, duck-typing is the philosophy that &amp;quot;If it walks like a duck, and quacks like a duck, it's a duck.&amp;quot; In programming terms, that means that we often don't care what type an object is, as long as it can do the things we ask.&lt;br /&gt;
&lt;br /&gt;
Let's look at an example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
# This function doubles the value it's passed.&lt;br /&gt;
def double(thing):&lt;br /&gt;
    return thing + thing&lt;br /&gt;
double(10) # Returns 20&lt;br /&gt;
double(&amp;quot;fish&amp;quot;) # Returns &amp;quot;fishfish&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If this were Java, we'd have to write two different methods here: one for things of type &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt;, and one for things of type &amp;lt;code&amp;gt;String&amp;lt;/code&amp;gt;. Since this is Python, though, we don't have to do that. Instead, Python lets us say, essentially: &amp;quot;This function uses the &amp;lt;code&amp;gt;+&amp;lt;/code&amp;gt; operator, so you can pass whatever object you want to the function, as long as the function supports the &amp;lt;code&amp;gt;+&amp;lt;/code&amp;gt; operator&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
To quote [https://groups.google.com/forum/?hl=en#!msg/comp.lang.python/CCs2oJdyuzc/NYjla5HKMOIJ Alex Martelli], one of the key people in the Python project,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;blockquote&amp;gt;&lt;br /&gt;
&amp;quot;[Don't] check whether it IS-a duck: check whether it QUACKS-like-a duck, WALKS-like-a duck, etc, etc, depending on exactly what subset of duck-like behaviour you need.&amp;quot;&lt;br /&gt;
&amp;lt;/blockquote&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&amp;lt;/ol&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Basic Types ===&lt;br /&gt;
&lt;br /&gt;
In Python, the basic scalar types are:&lt;br /&gt;
&lt;br /&gt;
# &amp;lt;code&amp;gt;str&amp;lt;/code&amp;gt; – a string.&lt;br /&gt;
# &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt; – an integer object with unlimited digits.&lt;br /&gt;
# &amp;lt;code&amp;gt;bool&amp;lt;/code&amp;gt; – a Boolean value.&lt;br /&gt;
# &amp;lt;code&amp;gt;float&amp;lt;/code&amp;gt; – a floating point number; generally equivalent to &amp;lt;code&amp;gt;double&amp;lt;/code&amp;gt; in Java.&lt;br /&gt;
# &amp;lt;code&amp;gt;bytes&amp;lt;/code&amp;gt; – represents a collection of bytes; you're unlikely to use this often.&lt;br /&gt;
&lt;br /&gt;
Casting is done in the C style - to parse an &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt; from a string, for instance, you'd write &amp;lt;code&amp;gt;int(&amp;quot;123&amp;quot;)&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== Basic Control Flow ===&lt;br /&gt;
In Python, blocks of code are delineated using colons and indentation instead of curly braces. '''''That means that proper indentation is mandatory.''''' Every time you use a colon, you must indent one step further, and every time a block ends, you must unindent a step.&lt;br /&gt;
&lt;br /&gt;
Conditional statements are done using the &amp;lt;code&amp;gt;if&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;elif&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;else&amp;lt;/code&amp;gt; operators, like in the example below - pay attention to the indentation:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
cookies_left = 10&lt;br /&gt;
cake_slices_left = 3&lt;br /&gt;
if cookies_left &amp;gt; 10:&lt;br /&gt;
    print(&amp;quot;Lots of cookies!&amp;quot;)&lt;br /&gt;
elif cookies_left &amp;gt; 8:&lt;br /&gt;
    print(&amp;quot;Plenty left!&amp;quot;)&lt;br /&gt;
elif cookies_left == 5:&lt;br /&gt;
    print(&amp;quot;Halfway done!&amp;quot;)&lt;br /&gt;
else:&lt;br /&gt;
    if cake_slices_left == 3:&lt;br /&gt;
        print(&amp;quot;Lots of cake!&amp;quot;)&lt;br /&gt;
    elif cake_slices_left == 2:&lt;br /&gt;
        print(&amp;quot;One slice gone!&amp;quot;)&lt;br /&gt;
    else:&lt;br /&gt;
        print(&amp;quot;Little to no cake left!&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== An Example Python Script ===&lt;br /&gt;
&lt;br /&gt;
In my mind, there's no better way to learn Python than to be immersed in a simple example script.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
print(&amp;quot;Hello World&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
fruits = [&amp;quot;apple&amp;quot;, &amp;quot;banana&amp;quot;, &amp;quot;cherry&amp;quot;, &amp;quot;date&amp;quot;]&lt;br /&gt;
for fruit in fruits:&lt;br /&gt;
    print(f&amp;quot;I always love to eat a fresh {fruit}&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Map the fruits list over to a new list containing the length of the fruit strings:&lt;br /&gt;
fruit_size = [len(fruit) for fruit in fruits]&lt;br /&gt;
&lt;br /&gt;
avg_fruit_size = sum(fruit_size) / len(fruit_size)&lt;br /&gt;
print(f&amp;quot;The average fruit string length is {avg_fruit_size:.2f}.&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Some things to notice:&lt;br /&gt;
&lt;br /&gt;
* Printing is achieved using the &amp;lt;code&amp;gt;print()&amp;lt;/code&amp;gt; function.&lt;br /&gt;
* Comments start with a pound symbol &amp;lt;code&amp;gt;#&amp;lt;/code&amp;gt;.&lt;br /&gt;
* We can transform/map a list to a new list in just one line!&lt;br /&gt;
&lt;br /&gt;
For some more examples, see [https://wiki.python.org/moin/SimplePrograms the Python wiki].&lt;br /&gt;
&lt;br /&gt;
=== A Few Gotchas ===&lt;br /&gt;
&lt;br /&gt;
Here are a few things you may not expect when starting out with Python:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;ol&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
Strings can be delimited using either single quotes (&amp;lt;code&amp;gt;'&amp;lt;/code&amp;gt;) or double quotes (&amp;lt;code&amp;gt;&amp;quot;&amp;lt;/code&amp;gt;), so &amp;lt;code&amp;gt;'Python'&amp;lt;/code&amp;gt; is the same as &amp;lt;code&amp;gt;&amp;quot;Python&amp;quot;&amp;lt;/code. You can also use three sets of quotes (&amp;lt;code&amp;gt;'''&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;&amp;quot;&amp;quot;&amp;quot;&amp;lt;/code&amp;gt;) to delineate a multiple-line string, like so:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
long_string = &amp;quot;&amp;quot;&amp;quot;This&lt;br /&gt;
is my&lt;br /&gt;
very long&lt;br /&gt;
multiple-line&lt;br /&gt;
string&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
To compare the equality of two objects, use the &amp;lt;code&amp;gt;==&amp;lt;/code&amp;gt; operator. To compare the identity of two objects (i.e. whether or not they are literally the same object, at the same place in memory), use the &amp;lt;code&amp;gt;is&amp;lt;/code&amp;gt; operator. These correspond, respectively to &amp;lt;code&amp;gt;.equals()&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;==&amp;lt;/code&amp;gt; in Java.&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
The &amp;lt;code&amp;gt;/&amp;lt;/code&amp;gt; operator performs floating-point division, not integer division, even when both its arguments are integers. If you want to do integer division, use the &amp;lt;code&amp;gt;//&amp;lt;/code&amp;gt; operator. Let's look at an example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
9   / 10    == 0.9 # Floating-point division&lt;br /&gt;
9.0 / 10.0  == 0.9 # Floating-point division&lt;br /&gt;
9   // 10   == 0   # Integer division&lt;br /&gt;
9.0 // 10.0 == 0.0 # Integer division, even though the resulting value is a float&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
As discussed in the section [[#Python's_Type_System|Python's Type System]], you can't combine strings and numbers using the &amp;lt;code&amp;gt;+&amp;lt;/code&amp;gt; operator. Instead, you'll have to use one of the following methods of string formatting:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
  &lt;br /&gt;
# Technique 1 – printf-style Formatting&lt;br /&gt;
# This is a classic style of string formatting, used in many programming languages, including in Java's String.format.&lt;br /&gt;
&amp;quot;You scored %d out of %d!&amp;quot; % (score, questions)&lt;br /&gt;
&lt;br /&gt;
# Technique 2 – str.format&lt;br /&gt;
&amp;quot;You scored {} out of {}!&amp;quot;.format(score, questions)&lt;br /&gt;
&lt;br /&gt;
# Technique 3 – f-strings&lt;br /&gt;
# These were only introduced in Python 3.6 but they're very convenient.&lt;br /&gt;
f&amp;quot;You scored {score} out of {questions}!&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# Technique 4 - String Concatenation&lt;br /&gt;
# This is fine for small things, but for more complicated stuff, use one of the other techniques.&lt;br /&gt;
&amp;quot;You scored &amp;quot; + str(score) + &amp;quot; out of &amp;quot; + str(questions) + &amp;quot;!&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&amp;lt;/ol&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Functions ===&lt;br /&gt;
&lt;br /&gt;
Define functions using the &amp;lt;code&amp;gt;def&amp;lt;/code&amp;gt; keyword:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def hello(name):&lt;br /&gt;
    print(f&amp;quot;Hello, {name}!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Invoke functions using parentheses:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
hello(&amp;quot;Batman&amp;quot;)&lt;br /&gt;
hello(&amp;quot;Superman&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Functions can have optional arguments; however, these must come after any required arguments:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def hello(name=&amp;quot;User&amp;quot;):&lt;br /&gt;
    print(f&amp;quot;Hello, {name}!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
hello() # Prints &amp;quot;Hello, User!&amp;quot;&lt;br /&gt;
hello(&amp;quot;Sarah&amp;quot;) # Prints &amp;quot;Hello, Sarah!&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Functions are just regular objects in Python, meaning you can do stuff like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def hello(name=&amp;quot;User&amp;quot;):&lt;br /&gt;
    print(f&amp;quot;Hello, {name}!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
greeting = hello&lt;br /&gt;
&lt;br /&gt;
greeting(&amp;quot;Siwei&amp;quot;) # Prints &amp;quot;Hello, Siwei!&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Collection Types ===&lt;br /&gt;
Python has a few basic, built-in collection types. They each have their own special use cases, but they share a lot of similarities. All built-in data structures in Python are zero-indexed, for instance.&lt;br /&gt;
&lt;br /&gt;
To obtain the number of elements in a collection, use the &amp;lt;code&amp;gt;len()&amp;lt;/code&amp;gt; function, like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish'] # This is a list; you'll learn about them below.&lt;br /&gt;
&lt;br /&gt;
len(pets) # Returns 3&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To check if a collection contains an item, use the &amp;lt;code&amp;gt;in&amp;lt;/code&amp;gt; operator:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish'] # This is a list; you'll learn about them below.&lt;br /&gt;
&lt;br /&gt;
'Dog' in pets # Returns True&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Helpfully, the Python Software Foundation maintains a page containing the asymptotic complexities of important operations on major Python data structures. It's available [https://wiki.python.org/moin/TimeComplexity here].&lt;br /&gt;
&lt;br /&gt;
==== Lists ====&lt;br /&gt;
&lt;br /&gt;
Unlike languages like Java and C, Python's array-like type doesn't have fixed length. Instead, a &amp;lt;code&amp;gt;list&amp;lt;/code&amp;gt; is a dynamic array (like Java's &amp;lt;code&amp;gt;ArrayList&amp;lt;/code&amp;gt;) of objects of any type. Here's an example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = [&amp;quot;Apple&amp;quot;, &amp;quot;Pear&amp;quot;, &amp;quot;Orange&amp;quot;] # Lists can be creating by placing their items between square brackets&lt;br /&gt;
&lt;br /&gt;
random_items = ['Apple', 12312, 2.0, [1, 2, 3]] # Lists can contain objects of different types - even other lists!&lt;br /&gt;
&lt;br /&gt;
pets.append('Turtle') # Adds 'Turtle' to the end of pets&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For the next few examples, we'll be using the following list:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish', 'Turtle', 'Lizard', 'Snake']&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access or assign elements of a list, use the &amp;lt;code&amp;gt;[]&amp;lt;/code&amp;gt; operator.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[0] # Returns 'Dog'&lt;br /&gt;
pets[1] = 'Cow' # Sets pets[1] to 'Cow'&lt;br /&gt;
pets[1] = 'Cat' # Sets pets[1] back to 'Cat' &lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You can also access or assign lists using negative indices, which will return elements starting from the end of the list:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[-1] # Returns 'Snake'&lt;br /&gt;
pets[-2] # Returns 'Lizard'&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You can also use 'slice notation' to obtain or assign subsets of lists:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[start:end] # Returns items from index start to index end - 1.&lt;br /&gt;
pets[start:]    # Returns items from index start to the end of the list, inclusive.&lt;br /&gt;
pets[:end]      # Returns items from the beginning of the list to index end - 1.&lt;br /&gt;
pets[:]         # Returns every item in the list&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
There's also a third, optional argument: &amp;lt;code&amp;gt;step&amp;lt;/code&amp;gt;, which lets you jump over values:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[start:end:step] # Returns items from index start to index end - 1, jumping step values at a time&lt;br /&gt;
&lt;br /&gt;
# Examples:&lt;br /&gt;
pets[1:5:2] # Returns items from index 1 to index 4, jumping 2 at a time, so ['Cat', 'Turtle']&lt;br /&gt;
pets[::3] # Returns all items in the list, jumping 3 at a time, so ['Dog', 'Turtle']&lt;br /&gt;
pets[::-1] # Returns all items in the list, jumping -1 at a time. This reverses the list, so ['Snake', 'Lizard', 'Turtle', 'Fish', 'Cat', 'Dog']&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Lists have all the performance characteristics you'd expect of a dynamic array - constant-time indexing, amortized constant-time appends, and so on.&lt;br /&gt;
&lt;br /&gt;
==== Tuples ====&lt;br /&gt;
&lt;br /&gt;
Python has a special data type called &amp;lt;code&amp;gt;tuple&amp;lt;/code&amp;gt;, which is exactly the same as a list except for the fact that it cannot be modified, so you can't append or replace items.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
cities = ('St. Louis', 'Los Angeles', 'Seattle') # Tuples are defined using parentheses.&lt;br /&gt;
numbers = 1, 2, 3 # You can also omit the parentheses if it's unambiguous&lt;br /&gt;
single_item_tuple = (1,) # To make a tuple with only one item, put a comma after it&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Tuples also enable you to have multiple return values from a function:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def compute_length(string):&lt;br /&gt;
    str_len = len(string)&lt;br /&gt;
    if str_len &amp;lt; 5:&lt;br /&gt;
        return str_len, &amp;quot;short&amp;quot;&lt;br /&gt;
    elif str_len &amp;lt; 40:&lt;br /&gt;
        return str_len, &amp;quot;medium&amp;quot;&lt;br /&gt;
    return str_len, &amp;quot;long&amp;quot;&lt;br /&gt;
&lt;br /&gt;
length, description = compute_length(&amp;quot;Four score and seven years ago&amp;quot;)&lt;br /&gt;
print(&amp;quot;The %s string is %d characters long.&amp;quot; % (description, length))&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
The above example also demonstrates Python's if...elif...else conditional structure.&lt;br /&gt;
&lt;br /&gt;
==== Dictionaries ====&lt;br /&gt;
&lt;br /&gt;
Python has another datatype called a '''dictionary''' (or &amp;lt;code&amp;gt;dict&amp;lt;/code&amp;gt;, for short), which are like ''Maps'' in Java, ''associative arrays'' in PHP, and ''object literals'' in JavaScript (coming up soon in Module 6). Essentially, they enable you to use any immutable object as the key in your data structure. &amp;lt;code&amp;gt;dict&amp;lt;/code&amp;gt; objects can be created using either the &amp;lt;code&amp;gt;dict&amp;lt;/code&amp;gt; function, or by placing items between curly braces, separating keys and values using colons:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits_in_bowl = {&lt;br /&gt;
    'apple': 4,&lt;br /&gt;
    'banana': 2,&lt;br /&gt;
    'cherry': 0,&lt;br /&gt;
    'date': 12&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
apple_count = fruits_in_bowl['apple'] # Equals 4&lt;br /&gt;
&lt;br /&gt;
fruits_in_bowl['pear'] = 9 # Sets 'pear' in the dictionary to 9.&lt;br /&gt;
&lt;br /&gt;
for fruit, num in fruits_in_bowl.items():&lt;br /&gt;
    print(f&amp;quot;There are {num} {fruit}(s) in the bowl.&amp;quot; % (num, fruit))&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If you only want the keys from a dictionary, you can just iterate over it directly, like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
for fruit in fruits_in_bowl:&lt;br /&gt;
    print(fruit)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If you want only the values but not the keys from a dictionary, use &amp;lt;code&amp;gt;my_dictionary.values()&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
==== Sets ==== &lt;br /&gt;
A &amp;lt;code&amp;gt;set&amp;lt;/code&amp;gt; is an unordered collection of unique items, with constant-time membership checking. &lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = {'Apple', 'Apple', 'Apple', 'Pear'} # The set removes duplicates, so it will only contain {'Apple', 'Pear'}&lt;br /&gt;
fruits = set(['Apple', 'Apple', 'Apple', 'Pear']) # This line transforms a list into a set&lt;br /&gt;
print('Apple' in fruits) # Constant-time!&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Loops ===&lt;br /&gt;
&lt;br /&gt;
In Python, while loops are written like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
i = 0&lt;br /&gt;
while i &amp;lt; 10:&lt;br /&gt;
    i += 1&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
For loops are written like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish']&lt;br /&gt;
&lt;br /&gt;
for pet in pets:&lt;br /&gt;
    print(pet)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
To iterate over a range of numbers, you can use the convenient &amp;lt;code&amp;gt;range&amp;lt;/code&amp;gt; function, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
for i in range(20, 30): # If you omit the first argument to range, it's assumed to be zero.&lt;br /&gt;
    print(i)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Note that &amp;lt;code&amp;gt;range&amp;lt;/code&amp;gt; provides a closed-open range. That is to say, it is inclusive of its lower bound and exclusive of its upper bound. To be very explicit about it:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
list(range(3, 6)) == [3, 4, 5]&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Unlike in other languages you may know, the following is not good practice in Python:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish']&lt;br /&gt;
&lt;br /&gt;
# BAD PRACTICE. DO NOT USE.&lt;br /&gt;
for i in range(len(pets)):&lt;br /&gt;
    pet = pets[i]&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Instead, if you need to access both a variable and its index, use the &amp;lt;code&amp;gt;enumerate&amp;lt;/code&amp;gt; function, which allows you to iterate through a group of items, along with their indexes, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish']&lt;br /&gt;
&lt;br /&gt;
for index, pet in enumerate(pets):&lt;br /&gt;
    print(f&amp;quot;{pet} at index {index}&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Generator Expressions and Comprehensions ===&lt;br /&gt;
&lt;br /&gt;
A generator is a special kind of object that, basically, represents a collection of items using a value and a function for generating the next value in the collection. In other words, it's a way of creating something that behaves like a list, but which only generates one value at a time, and discards a value when it's done with it. Say, for example, you wanted to do an operation on 10,000,000,000,000 numbers. You could put them all in a list, then iterate over the list, but that would take a lot of memory, plus you'd have to create and fill the entire list before beginning to actually work on your problem. Instead, you'd probably be better off using a generator; telling the computer, essentially: “The starting value is 0. When I ask for the next number in the collection, add 1 to current value and give me that.”&lt;br /&gt;
&lt;br /&gt;
A generator expression is an expression that is evaluated to create a generator. They're super useful. Generator expressions can take two forms – they can be used with and without a condition:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
(EXPRESSION for VARIABLE in ITERABLE) # Unconditional&lt;br /&gt;
(EXPRESSION for VARIABLE in ITERABLE if CONDITION) # Conditional&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
For our purposes, you can think of an iterable as anything you can do a for loop over. Let's take a look at a generator expression in use:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
double_even_digits = (number * 2 for number in range(10) if number % 2 == 0)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
That line says that &amp;lt;code&amp;gt;double_even_digits&amp;lt;/code&amp;gt; is every even number between 0 and 10 multiplied by two. Simple enough, right? If we wanted to use all of the numbers, not just the even ones, we could simply remove the if statement at the end of the expression.&lt;br /&gt;
&lt;br /&gt;
Here's the thing, though: if you were to print &amp;lt;code&amp;gt;double_even_digits&amp;lt;/code&amp;gt;, instead of a nice bunch of numbers, you'd get something that looks like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&amp;lt;generator object &amp;lt;genexpr&amp;gt;&amp;lt;code&amp;gt;at 0x107fc92b0&amp;gt;&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
That's because generators are lazy! They don't generate their values until those values are needed, and they discard values once they're no longer needed. As a result, '''you can only iterate over a generator once'''. In this case, you can't print out the whole generator, because it hasn't generated all the values yet. You can, however, iterate over the generator, and print its values one at a time, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
for number in double_even_digits:&lt;br /&gt;
    print(number)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
You can also make a list out of the generator, which will go through all the items in the generator and put them in a list, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
even_number_list = list(double_even_digits)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
That's actually a great segue to the second topic of this section: comprehensions. A comprehension is just a prettier way to make lists, sets, and dicts out of a generator expressions.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
# If you want a list:&lt;br /&gt;
list(i for i in range(10) if i % 2 == 0) # Don't do this&lt;br /&gt;
[i for i in range(10) if i % 2 == 0] # Use a list comprehension instead!&lt;br /&gt;
&lt;br /&gt;
# If you want a set:&lt;br /&gt;
set(i for i in range(10) if i % 2 == 0) # Don't do this&lt;br /&gt;
{i for i in range(10) if i % 2 == 0} # Use a set comprehension instead!&lt;br /&gt;
&lt;br /&gt;
# If you want a dict:&lt;br /&gt;
dict((i, i + 1) for i in range(10) if i % 2 == 0) # Don't do this&lt;br /&gt;
{i : i + 1 for i in range(10) if i % 2 == 0} # Use a dict comprehension instead!&lt;br /&gt;
&lt;br /&gt;
# If you want a tuple:&lt;br /&gt;
tuple(i for i in range(10) if i % 2 == 0) # Unfortunately, there's no better way to do this&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
In general, generators and comprehensions should be used whenever possible - they're the fastest and easiest way to build collections. If you ever see yourself writing code like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
# BAD PRACTICE! DO NOT USE!&lt;br /&gt;
digits = []&lt;br /&gt;
for digit in range(10):&lt;br /&gt;
    digits.append(digit)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Don't do it! Instead, use a generator expression or comprehension, as appropriate. A good way to decide whether a generator expression or comprehension is better for this situation is that, if you're just going to be iterating over your collection once, you should use an generator expression. If not, use a comprehension.&lt;br /&gt;
&lt;br /&gt;
=== Sorting ===&lt;br /&gt;
&lt;br /&gt;
Sorting in Python is frequently performed using the &amp;lt;code&amp;gt;sorted&amp;lt;/code&amp;gt; function, which takes two arguments: an iterable (anything you can do a for-loop over, including lists and tuples) and a function used to evaluate each item. If the function is omitted, Python will try to sort the lists by value.&lt;br /&gt;
&lt;br /&gt;
The following example demonstrates using an inline function, which Python calls a ''lambda''.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = ['apple', 'banana', 'cherry', 'date']&lt;br /&gt;
&lt;br /&gt;
# sort the fruits by string length&lt;br /&gt;
new_fruits = sorted(fruits, key=lambda v: len(v) // 2)&lt;br /&gt;
&lt;br /&gt;
print(new_fruits) # ['date', 'apple', 'banana', 'cherry']&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Alternatively, you can sort a &amp;lt;code&amp;gt;list&amp;lt;/code&amp;gt; using the &amp;lt;code&amp;gt;.sort&amp;lt;/code&amp;gt; method. This is faster than calling &amp;lt;code&amp;gt;sorted&amp;lt;/code&amp;gt;, but it modifies the list in-place and returns &amp;lt;code&amp;gt;None&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = ['apple', 'banana', 'cherry', 'date']&lt;br /&gt;
fruits.sort()&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
=== Import ===&lt;br /&gt;
&lt;br /&gt;
If you want to use functions from other libraries (including ones that you install using pip), use &amp;lt;code&amp;gt;import&amp;lt;/code&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
import time&lt;br /&gt;
&lt;br /&gt;
current_time = time.localtime()&lt;br /&gt;
print(time.strftime('%a, %d %b %Y %H:%M:%S', current_time))&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If you want to pull the functions out of their namespace, you can use &amp;lt;code&amp;gt;from ___ import ___&amp;lt;/code&amp;gt; syntax:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
from time import localtime, strftime&lt;br /&gt;
&lt;br /&gt;
current_time = localtime()&lt;br /&gt;
print(strftime('%a, %d %b %Y %H:%M:%S', current_time))&lt;br /&gt;
&lt;br /&gt;
# Be aware that this technique, although convenient, may cause unexpected behavior if the function names that you're pulling out of the namespace are already used for other purposes in Python.&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
=== File I/O ===&lt;br /&gt;
&lt;br /&gt;
You can read an entire file into a variable like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
f = open(&amp;quot;example.txt&amp;quot;)&lt;br /&gt;
file_contents = f.read()&lt;br /&gt;
&lt;br /&gt;
f.close() # free up memory when we're finished with the file&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
A better option is to use a with-block, which handles opening and closing the file for you automatically:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
with open(&amp;quot;example.txt&amp;quot;) as f:&lt;br /&gt;
    file_contents = f.read()&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
You can read a file line-by-line like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
with open(&amp;quot;example.txt&amp;quot;) as f:&lt;br /&gt;
    for line in f:&lt;br /&gt;
        print(&amp;quot;Read line: %s&amp;quot; % line.rstrip())&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
You can write to a file like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
with open(&amp;quot;example.txt&amp;quot;, &amp;quot;w&amp;quot;) as f:&lt;br /&gt;
    f.write(&amp;quot;Hello\nWorld\n&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
=== Command-Line Arguments ===&lt;br /&gt;
&lt;br /&gt;
Command line arguments are accessible in the variable &amp;lt;code&amp;gt;sys.argv&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
The following example shows a program that expects a filename as its argument, and it prints a usage message if the argument is not present ([https://stackoverflow.com/questions/983201/python-and-sys-argv source]).&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
import sys, os&lt;br /&gt;
&lt;br /&gt;
if len(sys.argv) &amp;lt; 2:&lt;br /&gt;
    sys.exit(&amp;quot;Usage: %s filename&amp;quot; % sys.argv[0])&lt;br /&gt;
&lt;br /&gt;
filename = sys.argv[1]&lt;br /&gt;
&lt;br /&gt;
if not os.path.exists(filename):&lt;br /&gt;
    sys.exit(&amp;quot;Error: File '%s' not found&amp;quot; % sys.argv[1])&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
=== Object-Oriented Programming ===&lt;br /&gt;
&lt;br /&gt;
You can define and use a class like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
class Food:&lt;br /&gt;
    # constructor:&lt;br /&gt;
    def __init__(self, name):&lt;br /&gt;
        self.name = name&lt;br /&gt;
    &lt;br /&gt;
    def format_name(self):&lt;br /&gt;
        return &amp;quot;Gotta love to eat &amp;quot; + self.name&lt;br /&gt;
&lt;br /&gt;
class Fruit(Food):&lt;br /&gt;
    def format_name(self):&lt;br /&gt;
        return Food.format_name(self) + &amp;quot; (fruit)&amp;quot;&lt;br /&gt;
&lt;br /&gt;
fruit = Fruit(&amp;quot;Cherry&amp;quot;)&lt;br /&gt;
print(fruit.format_name())&lt;br /&gt;
print(Food.get_definition())&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
This is the same example as in [[PHP#Object-Oriented_Programming|the PHP guide]].&lt;br /&gt;
&lt;br /&gt;
Some things to notice:&lt;br /&gt;
&lt;br /&gt;
* Instance methods ''always'' take &amp;lt;code&amp;gt;self&amp;lt;/code&amp;gt; as their first argument, followed by any number of additional parameters. This can be misleading for programmers familiar with other languages, because the number of arguments you feed to the method is actually ''one less than'' the number of declared parameters. Whenever you call a method on a class instance, that instance is implicitly fed into the explicitly-declared &amp;lt;code&amp;gt;self&amp;lt;/code&amp;gt; parameter of the method.&lt;br /&gt;
*: Note that the &amp;lt;code&amp;gt;self&amp;lt;/code&amp;gt; variable has the same purpose as the &amp;lt;code&amp;gt;this&amp;lt;/code&amp;gt; variable in languages like PHP, Java, JavaScript, and C++.&lt;br /&gt;
*There is no need for a &amp;lt;code&amp;gt;new&amp;lt;/code&amp;gt; keyword in Python.&lt;br /&gt;
&lt;br /&gt;
= Footnotes =&lt;br /&gt;
# {{note|interpreted}}This is an oversimplification. If you're interested, here's a quick explanation of how: In CPython (the reference implementation of Python) programs are compiled to bytecode, an intermediate representation, which is then interpreted.&lt;br /&gt;
[[Category:Module 4]]&lt;/div&gt;</summary>
		<author><name>Alex</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Python&amp;diff=2514</id>
		<title>Python</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Python&amp;diff=2514"/>
		<updated>2018-02-19T17:28:47Z</updated>

		<summary type="html">&lt;p&gt;Alex: /* Dictionaries */ Format strings&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Languages like Java and C++ have lots of rules regarding variable types, syntax, return values, and so on. These can be cumbersome when you are trying to write short, quick scripts to perform tasks. This is where a ''scripting language'' comes into play.&lt;br /&gt;
&lt;br /&gt;
'''Python''' is a language well-suited to rapid prototype development. It is generally an ''interpreted language'', which means that, generally speaking, a Python program is converted line by line into instructions for the computer to execute as the program runs, instead of having a separate compilation step beforehand {{ref|interpreted}}. The syntax is clean, and it is usually clear at first glance what is going on when you write in Python.&lt;br /&gt;
&lt;br /&gt;
= Installation =&lt;br /&gt;
&lt;br /&gt;
Python may already be installed on your system. To see whether or not it is, enter the command&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ python --version&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If it tells you a version of Python '''greater than or equal to 3.5''' then you're good to go. If not, you need to do a quick package install to get it up and running. Using yum, it's just &amp;lt;code&amp;gt;sudo yum install python35; sudo alternatives --set python /usr/bin/python3&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
==== Python 2 vs Python 3 ====&lt;br /&gt;
&lt;br /&gt;
In 2008, a new version of Python – Python 3 – was released, with a number changes that made it incompatible with the previous version, Python 2. For several years, the Python community was slow to make the change to Python 3, but today, Python 3 is ''the'' standard for new code. The ''only'' reason to write Python 2 code today is because you have to work in an environment or with libraries that do not support Python 3, and that situation is becoming increasingly rare.&lt;br /&gt;
&lt;br /&gt;
'''For CSE 330 (and this guide), you ''must'' use Python 3.5 or greater.'''&lt;br /&gt;
&lt;br /&gt;
=== Pip ===&lt;br /&gt;
&lt;br /&gt;
Linux distributions have package managers like ''Apt'', ''Yum'', and ''YaST''. PHP has a package manager named ''PEAR''. It's now time to introduce Python's leading package manager: '''pip'''.&lt;br /&gt;
&lt;br /&gt;
You need to install Pip from Yum before you can use it. The package is called &amp;lt;code&amp;gt;python-pip&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Once you have pip installed, you can use it to install Python packages. Use the &amp;lt;code&amp;gt;pip-python&amp;lt;/code&amp;gt; command:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ pip-python install package_name # RHEL&lt;br /&gt;
$ pip install package_name # Debian&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
= Running Python =&lt;br /&gt;
&lt;br /&gt;
There are two common ways to run Python code: via the console, and via a Python script file.&lt;br /&gt;
&lt;br /&gt;
=== The Python Console ===&lt;br /&gt;
&lt;br /&gt;
The Python console enables you to experiment with code without opening a text editor. To enter the Python console, simply type the ''python'' command at the terminal:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ python&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
To leave the interactive console, either type &amp;lt;code&amp;gt;quit()&amp;lt;/code&amp;gt; or press &amp;lt;code&amp;gt;Ctrl-D&amp;lt;/code&amp;gt; (on both Mac and Windows).&lt;br /&gt;
&lt;br /&gt;
=== Python Script Files ===&lt;br /&gt;
&lt;br /&gt;
You can also save Python script files for later use. The extension for Python scripts is &amp;lt;code&amp;gt;*.py&amp;lt;/code&amp;gt;. To run a script file, simply feed its path as an argument to the &amp;lt;code&amp;gt;python&amp;lt;/code&amp;gt; command in Terminal:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ python my_script.py&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Python Syntax and Language Components =&lt;br /&gt;
&lt;br /&gt;
This section contains a very brief overview of Python syntax. For a more comprehensive introduction, see [http://docs.python.org/tutorial/ the Python docs].&lt;br /&gt;
&lt;br /&gt;
=== Python's Type System ===&lt;br /&gt;
&lt;br /&gt;
Python is a dynamically-typed, strongly-typed, and duck-typed language. What does that mean? Well, let's take those categories one by one:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;ol&amp;gt;&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
'''Dynamic typing''', in contrast to ''static typing'' means that the types of objects can be changed. In Java, for instance, if you tried to write the following code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
int c = 2;&lt;br /&gt;
c = &amp;quot;fish&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Your code would fail to compile, because the Java compiler wouldn't allow you to change the type of the variable &amp;lt;code&amp;gt;c&amp;lt;/code&amp;gt; from &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt; to &amp;lt;code&amp;gt;String&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Python, however, is just fine with that. You can write:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
c = 2&lt;br /&gt;
c = &amp;quot;fish&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
And Python will happily do what you ask.&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
'''Strong typing''', in contrast to ''weak typing'', means, roughly, that a language won't implicitly convert types for you. So far, you've used a lot of PHP, which is very weakly typed. For example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;php&amp;quot;&amp;gt;&lt;br /&gt;
echo &amp;quot;10&amp;quot; . 2;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In PHP, this works just fine. The PHP interpreter sees that &amp;lt;code&amp;gt;2&amp;lt;/code&amp;gt; is an int, and silently converts it to a string for you, so that &amp;lt;code&amp;gt;&amp;quot;10&amp;quot;. 2&amp;lt;/code&amp;gt; equals &amp;lt;code&amp;gt;&amp;quot;102&amp;quot;&amp;lt;/code&amp;gt;. The problem with weak typing is that it can make it unclear to the programmer why things are happening the way they are. For instance, in PHP, the expression &amp;lt;code&amp;gt;&amp;quot;10&amp;quot; == 10&amp;lt;/code&amp;gt; is true, which can be less than obvious. Python, however, tries to disallow that sort of thing:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
&amp;quot;10&amp;quot; + &amp;quot;10&amp;quot; # Allowed – concatenates the two strings.&lt;br /&gt;
10   +  10  # Allowed – adds the two ints.&lt;br /&gt;
&amp;quot;10&amp;quot; +  10  # Not allowed – raises a TypeError&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Perhaps the one exception to this rule is the relationship between numeric types; it's perfectly fine to add a float to an int, for example.&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
'''Duck-typing''' is a little bit different than the other categories, because it doesn't really have a direct opposite. Essentially, duck-typing is the philosophy that &amp;quot;If it walks like a duck, and quacks like a duck, it's a duck.&amp;quot; In programming terms, that means that we often don't care what type an object is, as long as it can do the things we ask.&lt;br /&gt;
&lt;br /&gt;
Let's look at an example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
# This function doubles the value it's passed.&lt;br /&gt;
def double(thing):&lt;br /&gt;
    return thing + thing&lt;br /&gt;
double(10) # Returns 20&lt;br /&gt;
double(&amp;quot;fish&amp;quot;) # Returns &amp;quot;fishfish&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If this were Java, we'd have to write two different methods here: one for things of type &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt;, and one for things of type &amp;lt;code&amp;gt;String&amp;lt;/code&amp;gt;. Since this is Python, though, we don't have to do that. Instead, Python lets us say, essentially: &amp;quot;This function uses the &amp;lt;code&amp;gt;+&amp;lt;/code&amp;gt; operator, so you can pass whatever object you want to the function, as long as the function supports the &amp;lt;code&amp;gt;+&amp;lt;/code&amp;gt; operator&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
To quote [https://groups.google.com/forum/?hl=en#!msg/comp.lang.python/CCs2oJdyuzc/NYjla5HKMOIJ Alex Martelli], one of the key people in the Python project,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;blockquote&amp;gt;&lt;br /&gt;
&amp;quot;[Don't] check whether it IS-a duck: check whether it QUACKS-like-a duck, WALKS-like-a duck, etc, etc, depending on exactly what subset of duck-like behaviour you need.&amp;quot;&lt;br /&gt;
&amp;lt;/blockquote&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&amp;lt;/ol&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Basic Types ===&lt;br /&gt;
&lt;br /&gt;
In Python, the basic scalar types are:&lt;br /&gt;
&lt;br /&gt;
# &amp;lt;code&amp;gt;str&amp;lt;/code&amp;gt; – a string.&lt;br /&gt;
# &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt; – an integer object with unlimited digits.&lt;br /&gt;
# &amp;lt;code&amp;gt;bool&amp;lt;/code&amp;gt; – a Boolean value.&lt;br /&gt;
# &amp;lt;code&amp;gt;float&amp;lt;/code&amp;gt; – a floating point number; generally equivalent to &amp;lt;code&amp;gt;double&amp;lt;/code&amp;gt; in Java.&lt;br /&gt;
# &amp;lt;code&amp;gt;bytes&amp;lt;/code&amp;gt; – represents a collection of bytes; you're unlikely to use this often.&lt;br /&gt;
&lt;br /&gt;
Casting is done in the C style - to parse an &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt; from a string, for instance, you'd write &amp;lt;code&amp;gt;int(&amp;quot;123&amp;quot;)&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== Basic Control Flow ===&lt;br /&gt;
In Python, blocks of code are delineated using colons and indentation instead of curly braces. '''''That means that proper indentation is mandatory.''''' Every time you use a colon, you must indent one step further, and every time a block ends, you must unindent a step.&lt;br /&gt;
&lt;br /&gt;
Conditional statements are done using the &amp;lt;code&amp;gt;if&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;elif&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;else&amp;lt;/code&amp;gt; operators, like in the example below - pay attention to the indentation:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
cookies_left = 10&lt;br /&gt;
cake_slices_left = 3&lt;br /&gt;
if cookies_left &amp;gt; 10:&lt;br /&gt;
    print(&amp;quot;Lots of cookies!&amp;quot;)&lt;br /&gt;
elif cookies_left &amp;gt; 8:&lt;br /&gt;
    print(&amp;quot;Plenty left!&amp;quot;)&lt;br /&gt;
elif cookies_left == 5:&lt;br /&gt;
    print(&amp;quot;Halfway done!&amp;quot;)&lt;br /&gt;
else:&lt;br /&gt;
    if cake_slices_left == 3:&lt;br /&gt;
        print(&amp;quot;Lots of cake!&amp;quot;)&lt;br /&gt;
    elif cake_slices_left == 2:&lt;br /&gt;
        print(&amp;quot;One slice gone!&amp;quot;)&lt;br /&gt;
    else:&lt;br /&gt;
        print(&amp;quot;Little to no cake left!&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== An Example Python Script ===&lt;br /&gt;
&lt;br /&gt;
In my mind, there's no better way to learn Python than to be immersed in a simple example script.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
print(&amp;quot;Hello World&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
fruits = [&amp;quot;apple&amp;quot;, &amp;quot;banana&amp;quot;, &amp;quot;cherry&amp;quot;, &amp;quot;date&amp;quot;]&lt;br /&gt;
for fruit in fruits:&lt;br /&gt;
    print(f&amp;quot;I always love to eat a fresh {fruit}&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Map the fruits list over to a new list containing the length of the fruit strings:&lt;br /&gt;
fruit_size = [len(fruit) for fruit in fruits]&lt;br /&gt;
&lt;br /&gt;
avg_fruit_size = sum(fruit_size) / len(fruit_size)&lt;br /&gt;
print(f&amp;quot;The average fruit string length is {avg_fruit_size:.2f}.&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Some things to notice:&lt;br /&gt;
&lt;br /&gt;
* Printing is achieved using the &amp;lt;code&amp;gt;print()&amp;lt;/code&amp;gt; function.&lt;br /&gt;
* Comments start with a pound symbol &amp;lt;code&amp;gt;#&amp;lt;/code&amp;gt;.&lt;br /&gt;
* We can transform/map a list to a new list in just one line!&lt;br /&gt;
&lt;br /&gt;
For some more examples, see [https://wiki.python.org/moin/SimplePrograms the Python wiki].&lt;br /&gt;
&lt;br /&gt;
=== A Few Gotchas ===&lt;br /&gt;
&lt;br /&gt;
Here are a few things you may not expect when starting out with Python:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;ol&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
Strings can be delimited using either single quotes (&amp;lt;code&amp;gt;'&amp;lt;/code&amp;gt;) or double quotes (&amp;lt;code&amp;gt;&amp;quot;&amp;lt;/code&amp;gt;), so &amp;lt;code&amp;gt;'Python'&amp;lt;/code&amp;gt; is the same as &amp;lt;code&amp;gt;&amp;quot;Python&amp;quot;&amp;lt;/code. You can also use three sets of quotes (&amp;lt;code&amp;gt;'''&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;&amp;quot;&amp;quot;&amp;quot;&amp;lt;/code&amp;gt;) to delineate a multiple-line string, like so:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
long_string = &amp;quot;&amp;quot;&amp;quot;This&lt;br /&gt;
is my&lt;br /&gt;
very long&lt;br /&gt;
multiple-line&lt;br /&gt;
string&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
To compare the equality of two objects, use the &amp;lt;code&amp;gt;==&amp;lt;/code&amp;gt; operator. To compare the identity of two objects (i.e. whether or not they are literally the same object, at the same place in memory), use the &amp;lt;code&amp;gt;is&amp;lt;/code&amp;gt; operator. These correspond, respectively to &amp;lt;code&amp;gt;.equals()&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;==&amp;lt;/code&amp;gt; in Java.&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
The &amp;lt;code&amp;gt;/&amp;lt;/code&amp;gt; operator performs floating-point division, not integer division, even when both its arguments are integers. If you want to do integer division, use the &amp;lt;code&amp;gt;//&amp;lt;/code&amp;gt; operator. Let's look at an example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
9   / 10    == 0.9 # Floating-point division&lt;br /&gt;
9.0 / 10.0  == 0.9 # Floating-point division&lt;br /&gt;
9   // 10   == 0   # Integer division&lt;br /&gt;
9.0 // 10.0 == 0.0 # Integer division, even though the resulting value is a float&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
As discussed in the section [[#Python's_Type_System|Python's Type System]], you can't combine strings and numbers using the &amp;lt;code&amp;gt;+&amp;lt;/code&amp;gt; operator. Instead, you'll have to use one of the following methods of string formatting:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
  &lt;br /&gt;
# Technique 1 – printf-style Formatting&lt;br /&gt;
# This is a classic style of string formatting, used in many programming languages, including in Java's String.format.&lt;br /&gt;
&amp;quot;You scored %d out of %d!&amp;quot; % (score, questions)&lt;br /&gt;
&lt;br /&gt;
# Technique 2 – str.format&lt;br /&gt;
&amp;quot;You scored {} out of {}!&amp;quot;.format(score, questions)&lt;br /&gt;
&lt;br /&gt;
# Technique 3 – f-strings&lt;br /&gt;
# These were only introduced in Python 3.6 but they're very convenient.&lt;br /&gt;
f&amp;quot;You scored {score} out of {questions}!&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# Technique 4 - String Concatenation&lt;br /&gt;
# This is fine for small things, but for more complicated stuff, use one of the other techniques.&lt;br /&gt;
&amp;quot;You scored &amp;quot; + str(score) + &amp;quot; out of &amp;quot; + str(questions) + &amp;quot;!&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&amp;lt;/ol&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Functions ===&lt;br /&gt;
&lt;br /&gt;
Define functions using the &amp;lt;code&amp;gt;def&amp;lt;/code&amp;gt; keyword:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def hello(name):&lt;br /&gt;
    print(f&amp;quot;Hello, {name}!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Invoke functions using parentheses:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
hello(&amp;quot;Batman&amp;quot;)&lt;br /&gt;
hello(&amp;quot;Superman&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Functions can have optional arguments; however, these must come after any required arguments:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def hello(name=&amp;quot;User&amp;quot;):&lt;br /&gt;
    print(f&amp;quot;Hello, {name}!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
hello() # Prints &amp;quot;Hello, User!&amp;quot;&lt;br /&gt;
hello(&amp;quot;Sarah&amp;quot;) # Prints &amp;quot;Hello, Sarah!&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Functions are just regular objects in Python, meaning you can do stuff like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def hello(name=&amp;quot;User&amp;quot;):&lt;br /&gt;
    print(f&amp;quot;Hello, {name}!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
greeting = hello&lt;br /&gt;
&lt;br /&gt;
greeting(&amp;quot;Siwei&amp;quot;) # Prints &amp;quot;Hello, Siwei!&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Collection Types ===&lt;br /&gt;
Python has a few basic, built-in collection types. They each have their own special use cases, but they share a lot of similarities. All built-in data structures in Python are zero-indexed, for instance.&lt;br /&gt;
&lt;br /&gt;
To obtain the number of elements in a collection, use the &amp;lt;code&amp;gt;len()&amp;lt;/code&amp;gt; function, like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish'] # This is a list; you'll learn about them below.&lt;br /&gt;
&lt;br /&gt;
len(pets) # Returns 3&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To check if a collection contains an item, use the &amp;lt;code&amp;gt;in&amp;lt;/code&amp;gt; operator:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish'] # This is a list; you'll learn about them below.&lt;br /&gt;
&lt;br /&gt;
'Dog' in pets # Returns True&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Helpfully, the Python Software Foundation maintains a page containing the asymptotic complexities of important operations on major Python data structures. It's available [https://wiki.python.org/moin/TimeComplexity here].&lt;br /&gt;
&lt;br /&gt;
==== Lists ====&lt;br /&gt;
&lt;br /&gt;
Unlike languages like Java and C, Python's array-like type doesn't have fixed length. Instead, a &amp;lt;code&amp;gt;list&amp;lt;/code&amp;gt; is a dynamic array (like Java's &amp;lt;code&amp;gt;ArrayList&amp;lt;/code&amp;gt;) of objects of any type. Here's an example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = [&amp;quot;Apple&amp;quot;, &amp;quot;Pear&amp;quot;, &amp;quot;Orange&amp;quot;] # Lists can be creating by placing their items between square brackets&lt;br /&gt;
&lt;br /&gt;
random_items = ['Apple', 12312, 2.0, [1, 2, 3]] # Lists can contain objects of different types - even other lists!&lt;br /&gt;
&lt;br /&gt;
pets.append('Turtle') # Adds 'Turtle' to the end of pets&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For the next few examples, we'll be using the following list:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish', 'Turtle', 'Lizard', 'Snake']&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access or assign elements of a list, use the &amp;lt;code&amp;gt;[]&amp;lt;/code&amp;gt; operator.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[0] # Returns 'Dog'&lt;br /&gt;
pets[1] = 'Cow' # Sets pets[1] to 'Cow'&lt;br /&gt;
pets[1] = 'Cat' # Sets pets[1] back to 'Cat' &lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You can also access or assign lists using negative indices, which will return elements starting from the end of the list:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[-1] # Returns 'Snake'&lt;br /&gt;
pets[-2] # Returns 'Lizard'&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You can also use 'slice notation' to obtain or assign subsets of lists:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[start:end] # Returns items from index start to index end - 1.&lt;br /&gt;
pets[start:]    # Returns items from index start to the end of the list, inclusive.&lt;br /&gt;
pets[:end]      # Returns items from the beginning of the list to index end - 1.&lt;br /&gt;
pets[:]         # Returns every item in the list&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
There's also a third, optional argument: &amp;lt;code&amp;gt;step&amp;lt;/code&amp;gt;, which lets you jump over values:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[start:end:step] # Returns items from index start to index end - 1, jumping step values at a time&lt;br /&gt;
&lt;br /&gt;
# Examples:&lt;br /&gt;
pets[1:5:2] # Returns items from index 1 to index 4, jumping 2 at a time, so ['Cat', 'Turtle']&lt;br /&gt;
pets[::3] # Returns all items in the list, jumping 3 at a time, so ['Dog', 'Turtle']&lt;br /&gt;
pets[::-1] # Returns all items in the list, jumping -1 at a time. This reverses the list, so ['Snake', 'Lizard', 'Turtle', 'Fish', 'Cat', 'Dog']&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Lists have all the performance characteristics you'd expect of a dynamic array - constant-time indexing, amortized constant-time appends, and so on.&lt;br /&gt;
&lt;br /&gt;
==== Tuples ====&lt;br /&gt;
&lt;br /&gt;
Python has a special data type called &amp;lt;code&amp;gt;tuple&amp;lt;/code&amp;gt;, which is exactly the same as a list except for the fact that it cannot be modified, so you can't append or replace items.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
cities = ('St. Louis', 'Los Angeles', 'Seattle') # Tuples are defined using parentheses.&lt;br /&gt;
numbers = 1, 2, 3 # You can also omit the parentheses if it's unambiguous&lt;br /&gt;
single_item_tuple = (1,) # To make a tuple with only one item, put a comma after it&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Tuples also enable you to have multiple return values from a function:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def compute_length(string):&lt;br /&gt;
    str_len = len(string)&lt;br /&gt;
    if str_len &amp;lt; 5:&lt;br /&gt;
        return str_len, &amp;quot;short&amp;quot;&lt;br /&gt;
    elif str_len &amp;lt; 40:&lt;br /&gt;
        return str_len, &amp;quot;medium&amp;quot;&lt;br /&gt;
    return str_len, &amp;quot;long&amp;quot;&lt;br /&gt;
&lt;br /&gt;
length, description = compute_length(&amp;quot;Four score and seven years ago&amp;quot;)&lt;br /&gt;
print(&amp;quot;The %s string is %d characters long.&amp;quot; % (description, length))&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
The above example also demonstrates Python's if...elif...else conditional structure.&lt;br /&gt;
&lt;br /&gt;
==== Dictionaries ====&lt;br /&gt;
&lt;br /&gt;
Python has another datatype called a '''dictionary''' (or &amp;lt;code&amp;gt;dict&amp;lt;/code&amp;gt;, for short), which are like ''Maps'' in Java, ''associative arrays'' in PHP, and ''object literals'' in JavaScript (coming up soon in Module 6). Essentially, they enable you to use any immutable object as the key in your data structure. &amp;lt;code&amp;gt;dict&amp;lt;/code&amp;gt; objects can be created using either the &amp;lt;code&amp;gt;dict&amp;lt;/code&amp;gt; function, or by placing items between curly braces, separating keys and values using colons:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits_in_bowl = {&lt;br /&gt;
    'apple': 4,&lt;br /&gt;
    'banana': 2,&lt;br /&gt;
    'cherry': 0,&lt;br /&gt;
    'date': 12&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
apple_count = fruits_in_bowl['apple'] # Equals 4&lt;br /&gt;
&lt;br /&gt;
fruits_in_bowl['pear'] = 9 # Sets 'pear' in the dictionary to 9.&lt;br /&gt;
&lt;br /&gt;
for fruit, num in fruits_in_bowl.items():&lt;br /&gt;
    print(f&amp;quot;There are {num} {fruit}(s) in the bowl.&amp;quot; % (num, fruit))&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If you only want the keys from a dictionary, you can just iterate over it directly, like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
for fruit in fruits_in_bowl:&lt;br /&gt;
    print(fruit)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If you want only the values but not the keys from a dictionary, use &amp;lt;code&amp;gt;my_dictionary.values()&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
==== Sets ==== &lt;br /&gt;
A &amp;lt;code&amp;gt;set&amp;lt;/code&amp;gt; is an unordered collection of unique items, with constant-time membership checking. &lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = {'Apple', 'Apple', 'Apple', 'Pear'} # The set removes duplicates, so it will only contain {'Apple', 'Pear'}&lt;br /&gt;
fruits = set(['Apple', 'Apple', 'Apple', 'Pear']) # This line transforms a list into a set&lt;br /&gt;
print('Apple' in fruits) # Constant-time!&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Loops ===&lt;br /&gt;
&lt;br /&gt;
In Python, while loops are written like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
i = 0&lt;br /&gt;
while i &amp;lt; 10:&lt;br /&gt;
    i += 1&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
For loops are written like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish']&lt;br /&gt;
&lt;br /&gt;
for pet in pets:&lt;br /&gt;
    print(pet)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
To iterate over a range of numbers, you can use the convenient &amp;lt;code&amp;gt;range&amp;lt;/code&amp;gt; function, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
for i in range(20, 30): # If you omit the first argument to range, it's assumed to be zero.&lt;br /&gt;
    print(i)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Note that &amp;lt;code&amp;gt;range&amp;lt;/code&amp;gt; provides a closed-open range. That is to say, it is inclusive of its lower bound and exclusive of its upper bound. To be very explicit about it:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
list(range(3, 6)) == [3, 4, 5]&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Unlike in other languages you may know, the following is not good practice in Python:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish']&lt;br /&gt;
&lt;br /&gt;
# BAD PRACTICE. DO NOT USE.&lt;br /&gt;
for i in range(len(pets)):&lt;br /&gt;
    pet = pets[i]&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Instead, if you need to access both a variable and its index, use the &amp;lt;code&amp;gt;enumerate&amp;lt;/code&amp;gt; function, which allows you to iterate through a group of items, along with their indexes, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish']&lt;br /&gt;
&lt;br /&gt;
for index, pet in enumerate(pets):&lt;br /&gt;
    print(&amp;quot;%s at index %d&amp;quot;; % (pet, index))&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Generator Expressions and Comprehensions ===&lt;br /&gt;
&lt;br /&gt;
A generator is a special kind of object that, basically, represents a collection of items using a value and a function for generating the next value in the collection. In other words, it's a way of creating something that behaves like a list, but which only generates one value at a time, and discards a value when it's done with it. Say, for example, you wanted to do an operation on 10,000,000,000,000 numbers. You could put them all in a list, then iterate over the list, but that would take a lot of memory, plus you'd have to create and fill the entire list before beginning to actually work on your problem. Instead, you'd probably be better off using a generator; telling the computer, essentially: “The starting value is 0. When I ask for the next number in the collection, add 1 to current value and give me that.”&lt;br /&gt;
&lt;br /&gt;
A generator expression is an expression that is evaluated to create a generator. They're super useful. Generator expressions can take two forms – they can be used with and without a condition:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
(EXPRESSION for VARIABLE in ITERABLE) # Unconditional&lt;br /&gt;
(EXPRESSION for VARIABLE in ITERABLE if CONDITION) # Conditional&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
For our purposes, you can think of an iterable as anything you can do a for loop over. Let's take a look at a generator expression in use:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
double_even_digits = (number * 2 for number in range(10) if number % 2 == 0)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
That line says that &amp;lt;code&amp;gt;double_even_digits&amp;lt;/code&amp;gt; is every even number between 0 and 10 multiplied by two. Simple enough, right? If we wanted to use all of the numbers, not just the even ones, we could simply remove the if statement at the end of the expression.&lt;br /&gt;
&lt;br /&gt;
Here's the thing, though: if you were to print &amp;lt;code&amp;gt;double_even_digits&amp;lt;/code&amp;gt;, instead of a nice bunch of numbers, you'd get something that looks like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&amp;lt;generator object &amp;lt;genexpr&amp;gt;&amp;lt;code&amp;gt;at 0x107fc92b0&amp;gt;&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
That's because generators are lazy! They don't generate their values until those values are needed, and they discard values once they're no longer needed. As a result, '''you can only iterate over a generator once'''. In this case, you can't print out the whole generator, because it hasn't generated all the values yet. You can, however, iterate over the generator, and print its values one at a time, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
for number in double_even_digits:&lt;br /&gt;
    print(number)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
You can also make a list out of the generator, which will go through all the items in the generator and put them in a list, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
even_number_list = list(double_even_digits)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
That's actually a great segue to the second topic of this section: comprehensions. A comprehension is just a prettier way to make lists, sets, and dicts out of a generator expressions.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
# If you want a list:&lt;br /&gt;
list(i for i in range(10) if i % 2 == 0) # Don't do this&lt;br /&gt;
[i for i in range(10) if i % 2 == 0] # Use a list comprehension instead!&lt;br /&gt;
&lt;br /&gt;
# If you want a set:&lt;br /&gt;
set(i for i in range(10) if i % 2 == 0) # Don't do this&lt;br /&gt;
{i for i in range(10) if i % 2 == 0} # Use a set comprehension instead!&lt;br /&gt;
&lt;br /&gt;
# If you want a dict:&lt;br /&gt;
dict((i, i + 1) for i in range(10) if i % 2 == 0) # Don't do this&lt;br /&gt;
{i : i + 1 for i in range(10) if i % 2 == 0} # Use a dict comprehension instead!&lt;br /&gt;
&lt;br /&gt;
# If you want a tuple:&lt;br /&gt;
tuple(i for i in range(10) if i % 2 == 0) # Unfortunately, there's no better way to do this&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
In general, generators and comprehensions should be used whenever possible - they're the fastest and easiest way to build collections. If you ever see yourself writing code like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
# BAD PRACTICE! DO NOT USE!&lt;br /&gt;
digits = []&lt;br /&gt;
for digit in range(10):&lt;br /&gt;
    digits.append(digit)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Don't do it! Instead, use a generator expression or comprehension, as appropriate. A good way to decide whether a generator expression or comprehension is better for this situation is that, if you're just going to be iterating over your collection once, you should use an generator expression. If not, use a comprehension.&lt;br /&gt;
&lt;br /&gt;
=== Sorting ===&lt;br /&gt;
&lt;br /&gt;
Sorting in Python is frequently performed using the &amp;lt;code&amp;gt;sorted&amp;lt;/code&amp;gt; function, which takes two arguments: an iterable (anything you can do a for-loop over, including lists and tuples) and a function used to evaluate each item. If the function is omitted, Python will try to sort the lists by value.&lt;br /&gt;
&lt;br /&gt;
The following example demonstrates using an inline function, which Python calls a ''lambda''.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = ['apple', 'banana', 'cherry', 'date']&lt;br /&gt;
&lt;br /&gt;
# sort the fruits by string length&lt;br /&gt;
new_fruits = sorted(fruits, key=lambda v: len(v) // 2)&lt;br /&gt;
&lt;br /&gt;
print(new_fruits) # ['date', 'apple', 'banana', 'cherry']&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Alternatively, you can sort a &amp;lt;code&amp;gt;list&amp;lt;/code&amp;gt; using the &amp;lt;code&amp;gt;.sort&amp;lt;/code&amp;gt; method. This is faster than calling &amp;lt;code&amp;gt;sorted&amp;lt;/code&amp;gt;, but it modifies the list in-place and returns &amp;lt;code&amp;gt;None&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = ['apple', 'banana', 'cherry', 'date']&lt;br /&gt;
fruits.sort()&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
=== Import ===&lt;br /&gt;
&lt;br /&gt;
If you want to use functions from other libraries (including ones that you install using pip), use &amp;lt;code&amp;gt;import&amp;lt;/code&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
import time&lt;br /&gt;
&lt;br /&gt;
current_time = time.localtime()&lt;br /&gt;
print(time.strftime('%a, %d %b %Y %H:%M:%S', current_time))&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If you want to pull the functions out of their namespace, you can use &amp;lt;code&amp;gt;from ___ import ___&amp;lt;/code&amp;gt; syntax:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
from time import localtime, strftime&lt;br /&gt;
&lt;br /&gt;
current_time = localtime()&lt;br /&gt;
print(strftime('%a, %d %b %Y %H:%M:%S', current_time))&lt;br /&gt;
&lt;br /&gt;
# Be aware that this technique, although convenient, may cause unexpected behavior if the function names that you're pulling out of the namespace are already used for other purposes in Python.&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
=== File I/O ===&lt;br /&gt;
&lt;br /&gt;
You can read an entire file into a variable like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
f = open(&amp;quot;example.txt&amp;quot;)&lt;br /&gt;
file_contents = f.read()&lt;br /&gt;
&lt;br /&gt;
f.close() # free up memory when we're finished with the file&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
A better option is to use a with-block, which handles opening and closing the file for you automatically:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
with open(&amp;quot;example.txt&amp;quot;) as f:&lt;br /&gt;
    file_contents = f.read()&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
You can read a file line-by-line like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
with open(&amp;quot;example.txt&amp;quot;) as f:&lt;br /&gt;
    for line in f:&lt;br /&gt;
        print(&amp;quot;Read line: %s&amp;quot; % line.rstrip())&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
You can write to a file like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
with open(&amp;quot;example.txt&amp;quot;, &amp;quot;w&amp;quot;) as f:&lt;br /&gt;
    f.write(&amp;quot;Hello\nWorld\n&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
=== Command-Line Arguments ===&lt;br /&gt;
&lt;br /&gt;
Command line arguments are accessible in the variable &amp;lt;code&amp;gt;sys.argv&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
The following example shows a program that expects a filename as its argument, and it prints a usage message if the argument is not present ([https://stackoverflow.com/questions/983201/python-and-sys-argv source]).&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
import sys, os&lt;br /&gt;
&lt;br /&gt;
if len(sys.argv) &amp;lt; 2:&lt;br /&gt;
    sys.exit(&amp;quot;Usage: %s filename&amp;quot; % sys.argv[0])&lt;br /&gt;
&lt;br /&gt;
filename = sys.argv[1]&lt;br /&gt;
&lt;br /&gt;
if not os.path.exists(filename):&lt;br /&gt;
    sys.exit(&amp;quot;Error: File '%s' not found&amp;quot; % sys.argv[1])&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
=== Object-Oriented Programming ===&lt;br /&gt;
&lt;br /&gt;
You can define and use a class like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
class Food:&lt;br /&gt;
    # constructor:&lt;br /&gt;
    def __init__(self, name):&lt;br /&gt;
        self.name = name&lt;br /&gt;
    &lt;br /&gt;
    def format_name(self):&lt;br /&gt;
        return &amp;quot;Gotta love to eat &amp;quot; + self.name&lt;br /&gt;
&lt;br /&gt;
class Fruit(Food):&lt;br /&gt;
    def format_name(self):&lt;br /&gt;
        return Food.format_name(self) + &amp;quot; (fruit)&amp;quot;&lt;br /&gt;
&lt;br /&gt;
fruit = Fruit(&amp;quot;Cherry&amp;quot;)&lt;br /&gt;
print(fruit.format_name())&lt;br /&gt;
print(Food.get_definition())&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
This is the same example as in [[PHP#Object-Oriented_Programming|the PHP guide]].&lt;br /&gt;
&lt;br /&gt;
Some things to notice:&lt;br /&gt;
&lt;br /&gt;
* Instance methods ''always'' take &amp;lt;code&amp;gt;self&amp;lt;/code&amp;gt; as their first argument, followed by any number of additional parameters. This can be misleading for programmers familiar with other languages, because the number of arguments you feed to the method is actually ''one less than'' the number of declared parameters. Whenever you call a method on a class instance, that instance is implicitly fed into the explicitly-declared &amp;lt;code&amp;gt;self&amp;lt;/code&amp;gt; parameter of the method.&lt;br /&gt;
*: Note that the &amp;lt;code&amp;gt;self&amp;lt;/code&amp;gt; variable has the same purpose as the &amp;lt;code&amp;gt;this&amp;lt;/code&amp;gt; variable in languages like PHP, Java, JavaScript, and C++.&lt;br /&gt;
*There is no need for a &amp;lt;code&amp;gt;new&amp;lt;/code&amp;gt; keyword in Python.&lt;br /&gt;
&lt;br /&gt;
= Footnotes =&lt;br /&gt;
# {{note|interpreted}}This is an oversimplification. If you're interested, here's a quick explanation of how: In CPython (the reference implementation of Python) programs are compiled to bytecode, an intermediate representation, which is then interpreted.&lt;br /&gt;
[[Category:Module 4]]&lt;/div&gt;</summary>
		<author><name>Alex</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Python&amp;diff=2513</id>
		<title>Python</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Python&amp;diff=2513"/>
		<updated>2018-02-19T17:28:04Z</updated>

		<summary type="html">&lt;p&gt;Alex: /* Functions */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Languages like Java and C++ have lots of rules regarding variable types, syntax, return values, and so on. These can be cumbersome when you are trying to write short, quick scripts to perform tasks. This is where a ''scripting language'' comes into play.&lt;br /&gt;
&lt;br /&gt;
'''Python''' is a language well-suited to rapid prototype development. It is generally an ''interpreted language'', which means that, generally speaking, a Python program is converted line by line into instructions for the computer to execute as the program runs, instead of having a separate compilation step beforehand {{ref|interpreted}}. The syntax is clean, and it is usually clear at first glance what is going on when you write in Python.&lt;br /&gt;
&lt;br /&gt;
= Installation =&lt;br /&gt;
&lt;br /&gt;
Python may already be installed on your system. To see whether or not it is, enter the command&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ python --version&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If it tells you a version of Python '''greater than or equal to 3.5''' then you're good to go. If not, you need to do a quick package install to get it up and running. Using yum, it's just &amp;lt;code&amp;gt;sudo yum install python35; sudo alternatives --set python /usr/bin/python3&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
==== Python 2 vs Python 3 ====&lt;br /&gt;
&lt;br /&gt;
In 2008, a new version of Python – Python 3 – was released, with a number changes that made it incompatible with the previous version, Python 2. For several years, the Python community was slow to make the change to Python 3, but today, Python 3 is ''the'' standard for new code. The ''only'' reason to write Python 2 code today is because you have to work in an environment or with libraries that do not support Python 3, and that situation is becoming increasingly rare.&lt;br /&gt;
&lt;br /&gt;
'''For CSE 330 (and this guide), you ''must'' use Python 3.5 or greater.'''&lt;br /&gt;
&lt;br /&gt;
=== Pip ===&lt;br /&gt;
&lt;br /&gt;
Linux distributions have package managers like ''Apt'', ''Yum'', and ''YaST''. PHP has a package manager named ''PEAR''. It's now time to introduce Python's leading package manager: '''pip'''.&lt;br /&gt;
&lt;br /&gt;
You need to install Pip from Yum before you can use it. The package is called &amp;lt;code&amp;gt;python-pip&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Once you have pip installed, you can use it to install Python packages. Use the &amp;lt;code&amp;gt;pip-python&amp;lt;/code&amp;gt; command:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ pip-python install package_name # RHEL&lt;br /&gt;
$ pip install package_name # Debian&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
= Running Python =&lt;br /&gt;
&lt;br /&gt;
There are two common ways to run Python code: via the console, and via a Python script file.&lt;br /&gt;
&lt;br /&gt;
=== The Python Console ===&lt;br /&gt;
&lt;br /&gt;
The Python console enables you to experiment with code without opening a text editor. To enter the Python console, simply type the ''python'' command at the terminal:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ python&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
To leave the interactive console, either type &amp;lt;code&amp;gt;quit()&amp;lt;/code&amp;gt; or press &amp;lt;code&amp;gt;Ctrl-D&amp;lt;/code&amp;gt; (on both Mac and Windows).&lt;br /&gt;
&lt;br /&gt;
=== Python Script Files ===&lt;br /&gt;
&lt;br /&gt;
You can also save Python script files for later use. The extension for Python scripts is &amp;lt;code&amp;gt;*.py&amp;lt;/code&amp;gt;. To run a script file, simply feed its path as an argument to the &amp;lt;code&amp;gt;python&amp;lt;/code&amp;gt; command in Terminal:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ python my_script.py&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Python Syntax and Language Components =&lt;br /&gt;
&lt;br /&gt;
This section contains a very brief overview of Python syntax. For a more comprehensive introduction, see [http://docs.python.org/tutorial/ the Python docs].&lt;br /&gt;
&lt;br /&gt;
=== Python's Type System ===&lt;br /&gt;
&lt;br /&gt;
Python is a dynamically-typed, strongly-typed, and duck-typed language. What does that mean? Well, let's take those categories one by one:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;ol&amp;gt;&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
'''Dynamic typing''', in contrast to ''static typing'' means that the types of objects can be changed. In Java, for instance, if you tried to write the following code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
int c = 2;&lt;br /&gt;
c = &amp;quot;fish&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Your code would fail to compile, because the Java compiler wouldn't allow you to change the type of the variable &amp;lt;code&amp;gt;c&amp;lt;/code&amp;gt; from &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt; to &amp;lt;code&amp;gt;String&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Python, however, is just fine with that. You can write:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
c = 2&lt;br /&gt;
c = &amp;quot;fish&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
And Python will happily do what you ask.&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
'''Strong typing''', in contrast to ''weak typing'', means, roughly, that a language won't implicitly convert types for you. So far, you've used a lot of PHP, which is very weakly typed. For example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;php&amp;quot;&amp;gt;&lt;br /&gt;
echo &amp;quot;10&amp;quot; . 2;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In PHP, this works just fine. The PHP interpreter sees that &amp;lt;code&amp;gt;2&amp;lt;/code&amp;gt; is an int, and silently converts it to a string for you, so that &amp;lt;code&amp;gt;&amp;quot;10&amp;quot;. 2&amp;lt;/code&amp;gt; equals &amp;lt;code&amp;gt;&amp;quot;102&amp;quot;&amp;lt;/code&amp;gt;. The problem with weak typing is that it can make it unclear to the programmer why things are happening the way they are. For instance, in PHP, the expression &amp;lt;code&amp;gt;&amp;quot;10&amp;quot; == 10&amp;lt;/code&amp;gt; is true, which can be less than obvious. Python, however, tries to disallow that sort of thing:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
&amp;quot;10&amp;quot; + &amp;quot;10&amp;quot; # Allowed – concatenates the two strings.&lt;br /&gt;
10   +  10  # Allowed – adds the two ints.&lt;br /&gt;
&amp;quot;10&amp;quot; +  10  # Not allowed – raises a TypeError&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Perhaps the one exception to this rule is the relationship between numeric types; it's perfectly fine to add a float to an int, for example.&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
'''Duck-typing''' is a little bit different than the other categories, because it doesn't really have a direct opposite. Essentially, duck-typing is the philosophy that &amp;quot;If it walks like a duck, and quacks like a duck, it's a duck.&amp;quot; In programming terms, that means that we often don't care what type an object is, as long as it can do the things we ask.&lt;br /&gt;
&lt;br /&gt;
Let's look at an example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
# This function doubles the value it's passed.&lt;br /&gt;
def double(thing):&lt;br /&gt;
    return thing + thing&lt;br /&gt;
double(10) # Returns 20&lt;br /&gt;
double(&amp;quot;fish&amp;quot;) # Returns &amp;quot;fishfish&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If this were Java, we'd have to write two different methods here: one for things of type &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt;, and one for things of type &amp;lt;code&amp;gt;String&amp;lt;/code&amp;gt;. Since this is Python, though, we don't have to do that. Instead, Python lets us say, essentially: &amp;quot;This function uses the &amp;lt;code&amp;gt;+&amp;lt;/code&amp;gt; operator, so you can pass whatever object you want to the function, as long as the function supports the &amp;lt;code&amp;gt;+&amp;lt;/code&amp;gt; operator&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
To quote [https://groups.google.com/forum/?hl=en#!msg/comp.lang.python/CCs2oJdyuzc/NYjla5HKMOIJ Alex Martelli], one of the key people in the Python project,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;blockquote&amp;gt;&lt;br /&gt;
&amp;quot;[Don't] check whether it IS-a duck: check whether it QUACKS-like-a duck, WALKS-like-a duck, etc, etc, depending on exactly what subset of duck-like behaviour you need.&amp;quot;&lt;br /&gt;
&amp;lt;/blockquote&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&amp;lt;/ol&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Basic Types ===&lt;br /&gt;
&lt;br /&gt;
In Python, the basic scalar types are:&lt;br /&gt;
&lt;br /&gt;
# &amp;lt;code&amp;gt;str&amp;lt;/code&amp;gt; – a string.&lt;br /&gt;
# &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt; – an integer object with unlimited digits.&lt;br /&gt;
# &amp;lt;code&amp;gt;bool&amp;lt;/code&amp;gt; – a Boolean value.&lt;br /&gt;
# &amp;lt;code&amp;gt;float&amp;lt;/code&amp;gt; – a floating point number; generally equivalent to &amp;lt;code&amp;gt;double&amp;lt;/code&amp;gt; in Java.&lt;br /&gt;
# &amp;lt;code&amp;gt;bytes&amp;lt;/code&amp;gt; – represents a collection of bytes; you're unlikely to use this often.&lt;br /&gt;
&lt;br /&gt;
Casting is done in the C style - to parse an &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt; from a string, for instance, you'd write &amp;lt;code&amp;gt;int(&amp;quot;123&amp;quot;)&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== Basic Control Flow ===&lt;br /&gt;
In Python, blocks of code are delineated using colons and indentation instead of curly braces. '''''That means that proper indentation is mandatory.''''' Every time you use a colon, you must indent one step further, and every time a block ends, you must unindent a step.&lt;br /&gt;
&lt;br /&gt;
Conditional statements are done using the &amp;lt;code&amp;gt;if&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;elif&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;else&amp;lt;/code&amp;gt; operators, like in the example below - pay attention to the indentation:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
cookies_left = 10&lt;br /&gt;
cake_slices_left = 3&lt;br /&gt;
if cookies_left &amp;gt; 10:&lt;br /&gt;
    print(&amp;quot;Lots of cookies!&amp;quot;)&lt;br /&gt;
elif cookies_left &amp;gt; 8:&lt;br /&gt;
    print(&amp;quot;Plenty left!&amp;quot;)&lt;br /&gt;
elif cookies_left == 5:&lt;br /&gt;
    print(&amp;quot;Halfway done!&amp;quot;)&lt;br /&gt;
else:&lt;br /&gt;
    if cake_slices_left == 3:&lt;br /&gt;
        print(&amp;quot;Lots of cake!&amp;quot;)&lt;br /&gt;
    elif cake_slices_left == 2:&lt;br /&gt;
        print(&amp;quot;One slice gone!&amp;quot;)&lt;br /&gt;
    else:&lt;br /&gt;
        print(&amp;quot;Little to no cake left!&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== An Example Python Script ===&lt;br /&gt;
&lt;br /&gt;
In my mind, there's no better way to learn Python than to be immersed in a simple example script.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
print(&amp;quot;Hello World&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
fruits = [&amp;quot;apple&amp;quot;, &amp;quot;banana&amp;quot;, &amp;quot;cherry&amp;quot;, &amp;quot;date&amp;quot;]&lt;br /&gt;
for fruit in fruits:&lt;br /&gt;
    print(f&amp;quot;I always love to eat a fresh {fruit}&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Map the fruits list over to a new list containing the length of the fruit strings:&lt;br /&gt;
fruit_size = [len(fruit) for fruit in fruits]&lt;br /&gt;
&lt;br /&gt;
avg_fruit_size = sum(fruit_size) / len(fruit_size)&lt;br /&gt;
print(f&amp;quot;The average fruit string length is {avg_fruit_size:.2f}.&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Some things to notice:&lt;br /&gt;
&lt;br /&gt;
* Printing is achieved using the &amp;lt;code&amp;gt;print()&amp;lt;/code&amp;gt; function.&lt;br /&gt;
* Comments start with a pound symbol &amp;lt;code&amp;gt;#&amp;lt;/code&amp;gt;.&lt;br /&gt;
* We can transform/map a list to a new list in just one line!&lt;br /&gt;
&lt;br /&gt;
For some more examples, see [https://wiki.python.org/moin/SimplePrograms the Python wiki].&lt;br /&gt;
&lt;br /&gt;
=== A Few Gotchas ===&lt;br /&gt;
&lt;br /&gt;
Here are a few things you may not expect when starting out with Python:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;ol&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
Strings can be delimited using either single quotes (&amp;lt;code&amp;gt;'&amp;lt;/code&amp;gt;) or double quotes (&amp;lt;code&amp;gt;&amp;quot;&amp;lt;/code&amp;gt;), so &amp;lt;code&amp;gt;'Python'&amp;lt;/code&amp;gt; is the same as &amp;lt;code&amp;gt;&amp;quot;Python&amp;quot;&amp;lt;/code. You can also use three sets of quotes (&amp;lt;code&amp;gt;'''&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;&amp;quot;&amp;quot;&amp;quot;&amp;lt;/code&amp;gt;) to delineate a multiple-line string, like so:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
long_string = &amp;quot;&amp;quot;&amp;quot;This&lt;br /&gt;
is my&lt;br /&gt;
very long&lt;br /&gt;
multiple-line&lt;br /&gt;
string&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
To compare the equality of two objects, use the &amp;lt;code&amp;gt;==&amp;lt;/code&amp;gt; operator. To compare the identity of two objects (i.e. whether or not they are literally the same object, at the same place in memory), use the &amp;lt;code&amp;gt;is&amp;lt;/code&amp;gt; operator. These correspond, respectively to &amp;lt;code&amp;gt;.equals()&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;==&amp;lt;/code&amp;gt; in Java.&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
The &amp;lt;code&amp;gt;/&amp;lt;/code&amp;gt; operator performs floating-point division, not integer division, even when both its arguments are integers. If you want to do integer division, use the &amp;lt;code&amp;gt;//&amp;lt;/code&amp;gt; operator. Let's look at an example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
9   / 10    == 0.9 # Floating-point division&lt;br /&gt;
9.0 / 10.0  == 0.9 # Floating-point division&lt;br /&gt;
9   // 10   == 0   # Integer division&lt;br /&gt;
9.0 // 10.0 == 0.0 # Integer division, even though the resulting value is a float&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
As discussed in the section [[#Python's_Type_System|Python's Type System]], you can't combine strings and numbers using the &amp;lt;code&amp;gt;+&amp;lt;/code&amp;gt; operator. Instead, you'll have to use one of the following methods of string formatting:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
  &lt;br /&gt;
# Technique 1 – printf-style Formatting&lt;br /&gt;
# This is a classic style of string formatting, used in many programming languages, including in Java's String.format.&lt;br /&gt;
&amp;quot;You scored %d out of %d!&amp;quot; % (score, questions)&lt;br /&gt;
&lt;br /&gt;
# Technique 2 – str.format&lt;br /&gt;
&amp;quot;You scored {} out of {}!&amp;quot;.format(score, questions)&lt;br /&gt;
&lt;br /&gt;
# Technique 3 – f-strings&lt;br /&gt;
# These were only introduced in Python 3.6 but they're very convenient.&lt;br /&gt;
f&amp;quot;You scored {score} out of {questions}!&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# Technique 4 - String Concatenation&lt;br /&gt;
# This is fine for small things, but for more complicated stuff, use one of the other techniques.&lt;br /&gt;
&amp;quot;You scored &amp;quot; + str(score) + &amp;quot; out of &amp;quot; + str(questions) + &amp;quot;!&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&amp;lt;/ol&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Functions ===&lt;br /&gt;
&lt;br /&gt;
Define functions using the &amp;lt;code&amp;gt;def&amp;lt;/code&amp;gt; keyword:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def hello(name):&lt;br /&gt;
    print(f&amp;quot;Hello, {name}!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Invoke functions using parentheses:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
hello(&amp;quot;Batman&amp;quot;)&lt;br /&gt;
hello(&amp;quot;Superman&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Functions can have optional arguments; however, these must come after any required arguments:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def hello(name=&amp;quot;User&amp;quot;):&lt;br /&gt;
    print(f&amp;quot;Hello, {name}!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
hello() # Prints &amp;quot;Hello, User!&amp;quot;&lt;br /&gt;
hello(&amp;quot;Sarah&amp;quot;) # Prints &amp;quot;Hello, Sarah!&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Functions are just regular objects in Python, meaning you can do stuff like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def hello(name=&amp;quot;User&amp;quot;):&lt;br /&gt;
    print(f&amp;quot;Hello, {name}!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
greeting = hello&lt;br /&gt;
&lt;br /&gt;
greeting(&amp;quot;Siwei&amp;quot;) # Prints &amp;quot;Hello, Siwei!&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Collection Types ===&lt;br /&gt;
Python has a few basic, built-in collection types. They each have their own special use cases, but they share a lot of similarities. All built-in data structures in Python are zero-indexed, for instance.&lt;br /&gt;
&lt;br /&gt;
To obtain the number of elements in a collection, use the &amp;lt;code&amp;gt;len()&amp;lt;/code&amp;gt; function, like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish'] # This is a list; you'll learn about them below.&lt;br /&gt;
&lt;br /&gt;
len(pets) # Returns 3&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To check if a collection contains an item, use the &amp;lt;code&amp;gt;in&amp;lt;/code&amp;gt; operator:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish'] # This is a list; you'll learn about them below.&lt;br /&gt;
&lt;br /&gt;
'Dog' in pets # Returns True&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Helpfully, the Python Software Foundation maintains a page containing the asymptotic complexities of important operations on major Python data structures. It's available [https://wiki.python.org/moin/TimeComplexity here].&lt;br /&gt;
&lt;br /&gt;
==== Lists ====&lt;br /&gt;
&lt;br /&gt;
Unlike languages like Java and C, Python's array-like type doesn't have fixed length. Instead, a &amp;lt;code&amp;gt;list&amp;lt;/code&amp;gt; is a dynamic array (like Java's &amp;lt;code&amp;gt;ArrayList&amp;lt;/code&amp;gt;) of objects of any type. Here's an example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = [&amp;quot;Apple&amp;quot;, &amp;quot;Pear&amp;quot;, &amp;quot;Orange&amp;quot;] # Lists can be creating by placing their items between square brackets&lt;br /&gt;
&lt;br /&gt;
random_items = ['Apple', 12312, 2.0, [1, 2, 3]] # Lists can contain objects of different types - even other lists!&lt;br /&gt;
&lt;br /&gt;
pets.append('Turtle') # Adds 'Turtle' to the end of pets&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For the next few examples, we'll be using the following list:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish', 'Turtle', 'Lizard', 'Snake']&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access or assign elements of a list, use the &amp;lt;code&amp;gt;[]&amp;lt;/code&amp;gt; operator.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[0] # Returns 'Dog'&lt;br /&gt;
pets[1] = 'Cow' # Sets pets[1] to 'Cow'&lt;br /&gt;
pets[1] = 'Cat' # Sets pets[1] back to 'Cat' &lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You can also access or assign lists using negative indices, which will return elements starting from the end of the list:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[-1] # Returns 'Snake'&lt;br /&gt;
pets[-2] # Returns 'Lizard'&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You can also use 'slice notation' to obtain or assign subsets of lists:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[start:end] # Returns items from index start to index end - 1.&lt;br /&gt;
pets[start:]    # Returns items from index start to the end of the list, inclusive.&lt;br /&gt;
pets[:end]      # Returns items from the beginning of the list to index end - 1.&lt;br /&gt;
pets[:]         # Returns every item in the list&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
There's also a third, optional argument: &amp;lt;code&amp;gt;step&amp;lt;/code&amp;gt;, which lets you jump over values:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[start:end:step] # Returns items from index start to index end - 1, jumping step values at a time&lt;br /&gt;
&lt;br /&gt;
# Examples:&lt;br /&gt;
pets[1:5:2] # Returns items from index 1 to index 4, jumping 2 at a time, so ['Cat', 'Turtle']&lt;br /&gt;
pets[::3] # Returns all items in the list, jumping 3 at a time, so ['Dog', 'Turtle']&lt;br /&gt;
pets[::-1] # Returns all items in the list, jumping -1 at a time. This reverses the list, so ['Snake', 'Lizard', 'Turtle', 'Fish', 'Cat', 'Dog']&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Lists have all the performance characteristics you'd expect of a dynamic array - constant-time indexing, amortized constant-time appends, and so on.&lt;br /&gt;
&lt;br /&gt;
==== Tuples ====&lt;br /&gt;
&lt;br /&gt;
Python has a special data type called &amp;lt;code&amp;gt;tuple&amp;lt;/code&amp;gt;, which is exactly the same as a list except for the fact that it cannot be modified, so you can't append or replace items.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
cities = ('St. Louis', 'Los Angeles', 'Seattle') # Tuples are defined using parentheses.&lt;br /&gt;
numbers = 1, 2, 3 # You can also omit the parentheses if it's unambiguous&lt;br /&gt;
single_item_tuple = (1,) # To make a tuple with only one item, put a comma after it&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Tuples also enable you to have multiple return values from a function:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def compute_length(string):&lt;br /&gt;
    str_len = len(string)&lt;br /&gt;
    if str_len &amp;lt; 5:&lt;br /&gt;
        return str_len, &amp;quot;short&amp;quot;&lt;br /&gt;
    elif str_len &amp;lt; 40:&lt;br /&gt;
        return str_len, &amp;quot;medium&amp;quot;&lt;br /&gt;
    return str_len, &amp;quot;long&amp;quot;&lt;br /&gt;
&lt;br /&gt;
length, description = compute_length(&amp;quot;Four score and seven years ago&amp;quot;)&lt;br /&gt;
print(&amp;quot;The %s string is %d characters long.&amp;quot; % (description, length))&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
The above example also demonstrates Python's if...elif...else conditional structure.&lt;br /&gt;
&lt;br /&gt;
==== Dictionaries ====&lt;br /&gt;
&lt;br /&gt;
Python has another datatype called a '''dictionary''' (or &amp;lt;code&amp;gt;dict&amp;lt;/code&amp;gt;, for short), which are like ''Maps'' in Java, ''associative arrays'' in PHP, and ''object literals'' in JavaScript (coming up soon in Module 6). Essentially, they enable you to use any immutable object as the key in your data structure. &amp;lt;code&amp;gt;dict&amp;lt;/code&amp;gt; objects can be created using either the &amp;lt;code&amp;gt;dict&amp;lt;/code&amp;gt; function, or by placing items between curly braces, separating keys and values using colons:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits_in_bowl = {&lt;br /&gt;
    'apple': 4,&lt;br /&gt;
    'banana': 2,&lt;br /&gt;
    'cherry': 0,&lt;br /&gt;
    'date': 12&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
apple_count = fruits_in_bowl['apple'] # Equals 4&lt;br /&gt;
&lt;br /&gt;
fruits_in_bowl['pear'] = 9 # Sets 'pear' in the dictionary to 9.&lt;br /&gt;
&lt;br /&gt;
for fruit, num in fruits_in_bowl.items():&lt;br /&gt;
    print(&amp;quot;There are %d %s(s) in the bowl.&amp;quot; % (num, fruit))&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If you only want the keys from a dictionary, you can just iterate over it directly, like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
for fruit in fruits_in_bowl:&lt;br /&gt;
    print(fruit)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If you want only the values but not the keys from a dictionary, use &amp;lt;code&amp;gt;my_dictionary.values()&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
==== Sets ==== &lt;br /&gt;
A &amp;lt;code&amp;gt;set&amp;lt;/code&amp;gt; is an unordered collection of unique items, with constant-time membership checking. &lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = {'Apple', 'Apple', 'Apple', 'Pear'} # The set removes duplicates, so it will only contain {'Apple', 'Pear'}&lt;br /&gt;
fruits = set(['Apple', 'Apple', 'Apple', 'Pear']) # This line transforms a list into a set&lt;br /&gt;
print('Apple' in fruits) # Constant-time!&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Loops ===&lt;br /&gt;
&lt;br /&gt;
In Python, while loops are written like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
i = 0&lt;br /&gt;
while i &amp;lt; 10:&lt;br /&gt;
    i += 1&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
For loops are written like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish']&lt;br /&gt;
&lt;br /&gt;
for pet in pets:&lt;br /&gt;
    print(pet)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
To iterate over a range of numbers, you can use the convenient &amp;lt;code&amp;gt;range&amp;lt;/code&amp;gt; function, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
for i in range(20, 30): # If you omit the first argument to range, it's assumed to be zero.&lt;br /&gt;
    print(i)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Note that &amp;lt;code&amp;gt;range&amp;lt;/code&amp;gt; provides a closed-open range. That is to say, it is inclusive of its lower bound and exclusive of its upper bound. To be very explicit about it:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
list(range(3, 6)) == [3, 4, 5]&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Unlike in other languages you may know, the following is not good practice in Python:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish']&lt;br /&gt;
&lt;br /&gt;
# BAD PRACTICE. DO NOT USE.&lt;br /&gt;
for i in range(len(pets)):&lt;br /&gt;
    pet = pets[i]&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Instead, if you need to access both a variable and its index, use the &amp;lt;code&amp;gt;enumerate&amp;lt;/code&amp;gt; function, which allows you to iterate through a group of items, along with their indexes, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish']&lt;br /&gt;
&lt;br /&gt;
for index, pet in enumerate(pets):&lt;br /&gt;
    print(&amp;quot;%s at index %d&amp;quot;; % (pet, index))&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Generator Expressions and Comprehensions ===&lt;br /&gt;
&lt;br /&gt;
A generator is a special kind of object that, basically, represents a collection of items using a value and a function for generating the next value in the collection. In other words, it's a way of creating something that behaves like a list, but which only generates one value at a time, and discards a value when it's done with it. Say, for example, you wanted to do an operation on 10,000,000,000,000 numbers. You could put them all in a list, then iterate over the list, but that would take a lot of memory, plus you'd have to create and fill the entire list before beginning to actually work on your problem. Instead, you'd probably be better off using a generator; telling the computer, essentially: “The starting value is 0. When I ask for the next number in the collection, add 1 to current value and give me that.”&lt;br /&gt;
&lt;br /&gt;
A generator expression is an expression that is evaluated to create a generator. They're super useful. Generator expressions can take two forms – they can be used with and without a condition:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
(EXPRESSION for VARIABLE in ITERABLE) # Unconditional&lt;br /&gt;
(EXPRESSION for VARIABLE in ITERABLE if CONDITION) # Conditional&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
For our purposes, you can think of an iterable as anything you can do a for loop over. Let's take a look at a generator expression in use:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
double_even_digits = (number * 2 for number in range(10) if number % 2 == 0)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
That line says that &amp;lt;code&amp;gt;double_even_digits&amp;lt;/code&amp;gt; is every even number between 0 and 10 multiplied by two. Simple enough, right? If we wanted to use all of the numbers, not just the even ones, we could simply remove the if statement at the end of the expression.&lt;br /&gt;
&lt;br /&gt;
Here's the thing, though: if you were to print &amp;lt;code&amp;gt;double_even_digits&amp;lt;/code&amp;gt;, instead of a nice bunch of numbers, you'd get something that looks like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&amp;lt;generator object &amp;lt;genexpr&amp;gt;&amp;lt;code&amp;gt;at 0x107fc92b0&amp;gt;&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
That's because generators are lazy! They don't generate their values until those values are needed, and they discard values once they're no longer needed. As a result, '''you can only iterate over a generator once'''. In this case, you can't print out the whole generator, because it hasn't generated all the values yet. You can, however, iterate over the generator, and print its values one at a time, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
for number in double_even_digits:&lt;br /&gt;
    print(number)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
You can also make a list out of the generator, which will go through all the items in the generator and put them in a list, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
even_number_list = list(double_even_digits)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
That's actually a great segue to the second topic of this section: comprehensions. A comprehension is just a prettier way to make lists, sets, and dicts out of a generator expressions.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
# If you want a list:&lt;br /&gt;
list(i for i in range(10) if i % 2 == 0) # Don't do this&lt;br /&gt;
[i for i in range(10) if i % 2 == 0] # Use a list comprehension instead!&lt;br /&gt;
&lt;br /&gt;
# If you want a set:&lt;br /&gt;
set(i for i in range(10) if i % 2 == 0) # Don't do this&lt;br /&gt;
{i for i in range(10) if i % 2 == 0} # Use a set comprehension instead!&lt;br /&gt;
&lt;br /&gt;
# If you want a dict:&lt;br /&gt;
dict((i, i + 1) for i in range(10) if i % 2 == 0) # Don't do this&lt;br /&gt;
{i : i + 1 for i in range(10) if i % 2 == 0} # Use a dict comprehension instead!&lt;br /&gt;
&lt;br /&gt;
# If you want a tuple:&lt;br /&gt;
tuple(i for i in range(10) if i % 2 == 0) # Unfortunately, there's no better way to do this&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
In general, generators and comprehensions should be used whenever possible - they're the fastest and easiest way to build collections. If you ever see yourself writing code like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
# BAD PRACTICE! DO NOT USE!&lt;br /&gt;
digits = []&lt;br /&gt;
for digit in range(10):&lt;br /&gt;
    digits.append(digit)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Don't do it! Instead, use a generator expression or comprehension, as appropriate. A good way to decide whether a generator expression or comprehension is better for this situation is that, if you're just going to be iterating over your collection once, you should use an generator expression. If not, use a comprehension.&lt;br /&gt;
&lt;br /&gt;
=== Sorting ===&lt;br /&gt;
&lt;br /&gt;
Sorting in Python is frequently performed using the &amp;lt;code&amp;gt;sorted&amp;lt;/code&amp;gt; function, which takes two arguments: an iterable (anything you can do a for-loop over, including lists and tuples) and a function used to evaluate each item. If the function is omitted, Python will try to sort the lists by value.&lt;br /&gt;
&lt;br /&gt;
The following example demonstrates using an inline function, which Python calls a ''lambda''.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = ['apple', 'banana', 'cherry', 'date']&lt;br /&gt;
&lt;br /&gt;
# sort the fruits by string length&lt;br /&gt;
new_fruits = sorted(fruits, key=lambda v: len(v) // 2)&lt;br /&gt;
&lt;br /&gt;
print(new_fruits) # ['date', 'apple', 'banana', 'cherry']&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Alternatively, you can sort a &amp;lt;code&amp;gt;list&amp;lt;/code&amp;gt; using the &amp;lt;code&amp;gt;.sort&amp;lt;/code&amp;gt; method. This is faster than calling &amp;lt;code&amp;gt;sorted&amp;lt;/code&amp;gt;, but it modifies the list in-place and returns &amp;lt;code&amp;gt;None&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = ['apple', 'banana', 'cherry', 'date']&lt;br /&gt;
fruits.sort()&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
=== Import ===&lt;br /&gt;
&lt;br /&gt;
If you want to use functions from other libraries (including ones that you install using pip), use &amp;lt;code&amp;gt;import&amp;lt;/code&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
import time&lt;br /&gt;
&lt;br /&gt;
current_time = time.localtime()&lt;br /&gt;
print(time.strftime('%a, %d %b %Y %H:%M:%S', current_time))&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If you want to pull the functions out of their namespace, you can use &amp;lt;code&amp;gt;from ___ import ___&amp;lt;/code&amp;gt; syntax:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
from time import localtime, strftime&lt;br /&gt;
&lt;br /&gt;
current_time = localtime()&lt;br /&gt;
print(strftime('%a, %d %b %Y %H:%M:%S', current_time))&lt;br /&gt;
&lt;br /&gt;
# Be aware that this technique, although convenient, may cause unexpected behavior if the function names that you're pulling out of the namespace are already used for other purposes in Python.&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
=== File I/O ===&lt;br /&gt;
&lt;br /&gt;
You can read an entire file into a variable like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
f = open(&amp;quot;example.txt&amp;quot;)&lt;br /&gt;
file_contents = f.read()&lt;br /&gt;
&lt;br /&gt;
f.close() # free up memory when we're finished with the file&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
A better option is to use a with-block, which handles opening and closing the file for you automatically:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
with open(&amp;quot;example.txt&amp;quot;) as f:&lt;br /&gt;
    file_contents = f.read()&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
You can read a file line-by-line like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
with open(&amp;quot;example.txt&amp;quot;) as f:&lt;br /&gt;
    for line in f:&lt;br /&gt;
        print(&amp;quot;Read line: %s&amp;quot; % line.rstrip())&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
You can write to a file like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
with open(&amp;quot;example.txt&amp;quot;, &amp;quot;w&amp;quot;) as f:&lt;br /&gt;
    f.write(&amp;quot;Hello\nWorld\n&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
=== Command-Line Arguments ===&lt;br /&gt;
&lt;br /&gt;
Command line arguments are accessible in the variable &amp;lt;code&amp;gt;sys.argv&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
The following example shows a program that expects a filename as its argument, and it prints a usage message if the argument is not present ([https://stackoverflow.com/questions/983201/python-and-sys-argv source]).&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
import sys, os&lt;br /&gt;
&lt;br /&gt;
if len(sys.argv) &amp;lt; 2:&lt;br /&gt;
    sys.exit(&amp;quot;Usage: %s filename&amp;quot; % sys.argv[0])&lt;br /&gt;
&lt;br /&gt;
filename = sys.argv[1]&lt;br /&gt;
&lt;br /&gt;
if not os.path.exists(filename):&lt;br /&gt;
    sys.exit(&amp;quot;Error: File '%s' not found&amp;quot; % sys.argv[1])&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
=== Object-Oriented Programming ===&lt;br /&gt;
&lt;br /&gt;
You can define and use a class like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
class Food:&lt;br /&gt;
    # constructor:&lt;br /&gt;
    def __init__(self, name):&lt;br /&gt;
        self.name = name&lt;br /&gt;
    &lt;br /&gt;
    def format_name(self):&lt;br /&gt;
        return &amp;quot;Gotta love to eat &amp;quot; + self.name&lt;br /&gt;
&lt;br /&gt;
class Fruit(Food):&lt;br /&gt;
    def format_name(self):&lt;br /&gt;
        return Food.format_name(self) + &amp;quot; (fruit)&amp;quot;&lt;br /&gt;
&lt;br /&gt;
fruit = Fruit(&amp;quot;Cherry&amp;quot;)&lt;br /&gt;
print(fruit.format_name())&lt;br /&gt;
print(Food.get_definition())&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
This is the same example as in [[PHP#Object-Oriented_Programming|the PHP guide]].&lt;br /&gt;
&lt;br /&gt;
Some things to notice:&lt;br /&gt;
&lt;br /&gt;
* Instance methods ''always'' take &amp;lt;code&amp;gt;self&amp;lt;/code&amp;gt; as their first argument, followed by any number of additional parameters. This can be misleading for programmers familiar with other languages, because the number of arguments you feed to the method is actually ''one less than'' the number of declared parameters. Whenever you call a method on a class instance, that instance is implicitly fed into the explicitly-declared &amp;lt;code&amp;gt;self&amp;lt;/code&amp;gt; parameter of the method.&lt;br /&gt;
*: Note that the &amp;lt;code&amp;gt;self&amp;lt;/code&amp;gt; variable has the same purpose as the &amp;lt;code&amp;gt;this&amp;lt;/code&amp;gt; variable in languages like PHP, Java, JavaScript, and C++.&lt;br /&gt;
*There is no need for a &amp;lt;code&amp;gt;new&amp;lt;/code&amp;gt; keyword in Python.&lt;br /&gt;
&lt;br /&gt;
= Footnotes =&lt;br /&gt;
# {{note|interpreted}}This is an oversimplification. If you're interested, here's a quick explanation of how: In CPython (the reference implementation of Python) programs are compiled to bytecode, an intermediate representation, which is then interpreted.&lt;br /&gt;
[[Category:Module 4]]&lt;/div&gt;</summary>
		<author><name>Alex</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Python&amp;diff=2512</id>
		<title>Python</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Python&amp;diff=2512"/>
		<updated>2018-02-19T17:27:38Z</updated>

		<summary type="html">&lt;p&gt;Alex: /* Functions */  Format strings&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Languages like Java and C++ have lots of rules regarding variable types, syntax, return values, and so on. These can be cumbersome when you are trying to write short, quick scripts to perform tasks. This is where a ''scripting language'' comes into play.&lt;br /&gt;
&lt;br /&gt;
'''Python''' is a language well-suited to rapid prototype development. It is generally an ''interpreted language'', which means that, generally speaking, a Python program is converted line by line into instructions for the computer to execute as the program runs, instead of having a separate compilation step beforehand {{ref|interpreted}}. The syntax is clean, and it is usually clear at first glance what is going on when you write in Python.&lt;br /&gt;
&lt;br /&gt;
= Installation =&lt;br /&gt;
&lt;br /&gt;
Python may already be installed on your system. To see whether or not it is, enter the command&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ python --version&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If it tells you a version of Python '''greater than or equal to 3.5''' then you're good to go. If not, you need to do a quick package install to get it up and running. Using yum, it's just &amp;lt;code&amp;gt;sudo yum install python35; sudo alternatives --set python /usr/bin/python3&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
==== Python 2 vs Python 3 ====&lt;br /&gt;
&lt;br /&gt;
In 2008, a new version of Python – Python 3 – was released, with a number changes that made it incompatible with the previous version, Python 2. For several years, the Python community was slow to make the change to Python 3, but today, Python 3 is ''the'' standard for new code. The ''only'' reason to write Python 2 code today is because you have to work in an environment or with libraries that do not support Python 3, and that situation is becoming increasingly rare.&lt;br /&gt;
&lt;br /&gt;
'''For CSE 330 (and this guide), you ''must'' use Python 3.5 or greater.'''&lt;br /&gt;
&lt;br /&gt;
=== Pip ===&lt;br /&gt;
&lt;br /&gt;
Linux distributions have package managers like ''Apt'', ''Yum'', and ''YaST''. PHP has a package manager named ''PEAR''. It's now time to introduce Python's leading package manager: '''pip'''.&lt;br /&gt;
&lt;br /&gt;
You need to install Pip from Yum before you can use it. The package is called &amp;lt;code&amp;gt;python-pip&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Once you have pip installed, you can use it to install Python packages. Use the &amp;lt;code&amp;gt;pip-python&amp;lt;/code&amp;gt; command:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ pip-python install package_name # RHEL&lt;br /&gt;
$ pip install package_name # Debian&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
= Running Python =&lt;br /&gt;
&lt;br /&gt;
There are two common ways to run Python code: via the console, and via a Python script file.&lt;br /&gt;
&lt;br /&gt;
=== The Python Console ===&lt;br /&gt;
&lt;br /&gt;
The Python console enables you to experiment with code without opening a text editor. To enter the Python console, simply type the ''python'' command at the terminal:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ python&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
To leave the interactive console, either type &amp;lt;code&amp;gt;quit()&amp;lt;/code&amp;gt; or press &amp;lt;code&amp;gt;Ctrl-D&amp;lt;/code&amp;gt; (on both Mac and Windows).&lt;br /&gt;
&lt;br /&gt;
=== Python Script Files ===&lt;br /&gt;
&lt;br /&gt;
You can also save Python script files for later use. The extension for Python scripts is &amp;lt;code&amp;gt;*.py&amp;lt;/code&amp;gt;. To run a script file, simply feed its path as an argument to the &amp;lt;code&amp;gt;python&amp;lt;/code&amp;gt; command in Terminal:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ python my_script.py&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Python Syntax and Language Components =&lt;br /&gt;
&lt;br /&gt;
This section contains a very brief overview of Python syntax. For a more comprehensive introduction, see [http://docs.python.org/tutorial/ the Python docs].&lt;br /&gt;
&lt;br /&gt;
=== Python's Type System ===&lt;br /&gt;
&lt;br /&gt;
Python is a dynamically-typed, strongly-typed, and duck-typed language. What does that mean? Well, let's take those categories one by one:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;ol&amp;gt;&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
'''Dynamic typing''', in contrast to ''static typing'' means that the types of objects can be changed. In Java, for instance, if you tried to write the following code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
int c = 2;&lt;br /&gt;
c = &amp;quot;fish&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Your code would fail to compile, because the Java compiler wouldn't allow you to change the type of the variable &amp;lt;code&amp;gt;c&amp;lt;/code&amp;gt; from &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt; to &amp;lt;code&amp;gt;String&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Python, however, is just fine with that. You can write:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
c = 2&lt;br /&gt;
c = &amp;quot;fish&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
And Python will happily do what you ask.&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
'''Strong typing''', in contrast to ''weak typing'', means, roughly, that a language won't implicitly convert types for you. So far, you've used a lot of PHP, which is very weakly typed. For example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;php&amp;quot;&amp;gt;&lt;br /&gt;
echo &amp;quot;10&amp;quot; . 2;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In PHP, this works just fine. The PHP interpreter sees that &amp;lt;code&amp;gt;2&amp;lt;/code&amp;gt; is an int, and silently converts it to a string for you, so that &amp;lt;code&amp;gt;&amp;quot;10&amp;quot;. 2&amp;lt;/code&amp;gt; equals &amp;lt;code&amp;gt;&amp;quot;102&amp;quot;&amp;lt;/code&amp;gt;. The problem with weak typing is that it can make it unclear to the programmer why things are happening the way they are. For instance, in PHP, the expression &amp;lt;code&amp;gt;&amp;quot;10&amp;quot; == 10&amp;lt;/code&amp;gt; is true, which can be less than obvious. Python, however, tries to disallow that sort of thing:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
&amp;quot;10&amp;quot; + &amp;quot;10&amp;quot; # Allowed – concatenates the two strings.&lt;br /&gt;
10   +  10  # Allowed – adds the two ints.&lt;br /&gt;
&amp;quot;10&amp;quot; +  10  # Not allowed – raises a TypeError&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Perhaps the one exception to this rule is the relationship between numeric types; it's perfectly fine to add a float to an int, for example.&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
'''Duck-typing''' is a little bit different than the other categories, because it doesn't really have a direct opposite. Essentially, duck-typing is the philosophy that &amp;quot;If it walks like a duck, and quacks like a duck, it's a duck.&amp;quot; In programming terms, that means that we often don't care what type an object is, as long as it can do the things we ask.&lt;br /&gt;
&lt;br /&gt;
Let's look at an example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
# This function doubles the value it's passed.&lt;br /&gt;
def double(thing):&lt;br /&gt;
    return thing + thing&lt;br /&gt;
double(10) # Returns 20&lt;br /&gt;
double(&amp;quot;fish&amp;quot;) # Returns &amp;quot;fishfish&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If this were Java, we'd have to write two different methods here: one for things of type &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt;, and one for things of type &amp;lt;code&amp;gt;String&amp;lt;/code&amp;gt;. Since this is Python, though, we don't have to do that. Instead, Python lets us say, essentially: &amp;quot;This function uses the &amp;lt;code&amp;gt;+&amp;lt;/code&amp;gt; operator, so you can pass whatever object you want to the function, as long as the function supports the &amp;lt;code&amp;gt;+&amp;lt;/code&amp;gt; operator&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
To quote [https://groups.google.com/forum/?hl=en#!msg/comp.lang.python/CCs2oJdyuzc/NYjla5HKMOIJ Alex Martelli], one of the key people in the Python project,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;blockquote&amp;gt;&lt;br /&gt;
&amp;quot;[Don't] check whether it IS-a duck: check whether it QUACKS-like-a duck, WALKS-like-a duck, etc, etc, depending on exactly what subset of duck-like behaviour you need.&amp;quot;&lt;br /&gt;
&amp;lt;/blockquote&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&amp;lt;/ol&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Basic Types ===&lt;br /&gt;
&lt;br /&gt;
In Python, the basic scalar types are:&lt;br /&gt;
&lt;br /&gt;
# &amp;lt;code&amp;gt;str&amp;lt;/code&amp;gt; – a string.&lt;br /&gt;
# &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt; – an integer object with unlimited digits.&lt;br /&gt;
# &amp;lt;code&amp;gt;bool&amp;lt;/code&amp;gt; – a Boolean value.&lt;br /&gt;
# &amp;lt;code&amp;gt;float&amp;lt;/code&amp;gt; – a floating point number; generally equivalent to &amp;lt;code&amp;gt;double&amp;lt;/code&amp;gt; in Java.&lt;br /&gt;
# &amp;lt;code&amp;gt;bytes&amp;lt;/code&amp;gt; – represents a collection of bytes; you're unlikely to use this often.&lt;br /&gt;
&lt;br /&gt;
Casting is done in the C style - to parse an &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt; from a string, for instance, you'd write &amp;lt;code&amp;gt;int(&amp;quot;123&amp;quot;)&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== Basic Control Flow ===&lt;br /&gt;
In Python, blocks of code are delineated using colons and indentation instead of curly braces. '''''That means that proper indentation is mandatory.''''' Every time you use a colon, you must indent one step further, and every time a block ends, you must unindent a step.&lt;br /&gt;
&lt;br /&gt;
Conditional statements are done using the &amp;lt;code&amp;gt;if&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;elif&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;else&amp;lt;/code&amp;gt; operators, like in the example below - pay attention to the indentation:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
cookies_left = 10&lt;br /&gt;
cake_slices_left = 3&lt;br /&gt;
if cookies_left &amp;gt; 10:&lt;br /&gt;
    print(&amp;quot;Lots of cookies!&amp;quot;)&lt;br /&gt;
elif cookies_left &amp;gt; 8:&lt;br /&gt;
    print(&amp;quot;Plenty left!&amp;quot;)&lt;br /&gt;
elif cookies_left == 5:&lt;br /&gt;
    print(&amp;quot;Halfway done!&amp;quot;)&lt;br /&gt;
else:&lt;br /&gt;
    if cake_slices_left == 3:&lt;br /&gt;
        print(&amp;quot;Lots of cake!&amp;quot;)&lt;br /&gt;
    elif cake_slices_left == 2:&lt;br /&gt;
        print(&amp;quot;One slice gone!&amp;quot;)&lt;br /&gt;
    else:&lt;br /&gt;
        print(&amp;quot;Little to no cake left!&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== An Example Python Script ===&lt;br /&gt;
&lt;br /&gt;
In my mind, there's no better way to learn Python than to be immersed in a simple example script.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
print(&amp;quot;Hello World&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
fruits = [&amp;quot;apple&amp;quot;, &amp;quot;banana&amp;quot;, &amp;quot;cherry&amp;quot;, &amp;quot;date&amp;quot;]&lt;br /&gt;
for fruit in fruits:&lt;br /&gt;
    print(f&amp;quot;I always love to eat a fresh {fruit}&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Map the fruits list over to a new list containing the length of the fruit strings:&lt;br /&gt;
fruit_size = [len(fruit) for fruit in fruits]&lt;br /&gt;
&lt;br /&gt;
avg_fruit_size = sum(fruit_size) / len(fruit_size)&lt;br /&gt;
print(f&amp;quot;The average fruit string length is {avg_fruit_size:.2f}.&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Some things to notice:&lt;br /&gt;
&lt;br /&gt;
* Printing is achieved using the &amp;lt;code&amp;gt;print()&amp;lt;/code&amp;gt; function.&lt;br /&gt;
* Comments start with a pound symbol &amp;lt;code&amp;gt;#&amp;lt;/code&amp;gt;.&lt;br /&gt;
* We can transform/map a list to a new list in just one line!&lt;br /&gt;
&lt;br /&gt;
For some more examples, see [https://wiki.python.org/moin/SimplePrograms the Python wiki].&lt;br /&gt;
&lt;br /&gt;
=== A Few Gotchas ===&lt;br /&gt;
&lt;br /&gt;
Here are a few things you may not expect when starting out with Python:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;ol&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
Strings can be delimited using either single quotes (&amp;lt;code&amp;gt;'&amp;lt;/code&amp;gt;) or double quotes (&amp;lt;code&amp;gt;&amp;quot;&amp;lt;/code&amp;gt;), so &amp;lt;code&amp;gt;'Python'&amp;lt;/code&amp;gt; is the same as &amp;lt;code&amp;gt;&amp;quot;Python&amp;quot;&amp;lt;/code. You can also use three sets of quotes (&amp;lt;code&amp;gt;'''&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;&amp;quot;&amp;quot;&amp;quot;&amp;lt;/code&amp;gt;) to delineate a multiple-line string, like so:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
long_string = &amp;quot;&amp;quot;&amp;quot;This&lt;br /&gt;
is my&lt;br /&gt;
very long&lt;br /&gt;
multiple-line&lt;br /&gt;
string&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
To compare the equality of two objects, use the &amp;lt;code&amp;gt;==&amp;lt;/code&amp;gt; operator. To compare the identity of two objects (i.e. whether or not they are literally the same object, at the same place in memory), use the &amp;lt;code&amp;gt;is&amp;lt;/code&amp;gt; operator. These correspond, respectively to &amp;lt;code&amp;gt;.equals()&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;==&amp;lt;/code&amp;gt; in Java.&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
The &amp;lt;code&amp;gt;/&amp;lt;/code&amp;gt; operator performs floating-point division, not integer division, even when both its arguments are integers. If you want to do integer division, use the &amp;lt;code&amp;gt;//&amp;lt;/code&amp;gt; operator. Let's look at an example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
9   / 10    == 0.9 # Floating-point division&lt;br /&gt;
9.0 / 10.0  == 0.9 # Floating-point division&lt;br /&gt;
9   // 10   == 0   # Integer division&lt;br /&gt;
9.0 // 10.0 == 0.0 # Integer division, even though the resulting value is a float&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
As discussed in the section [[#Python's_Type_System|Python's Type System]], you can't combine strings and numbers using the &amp;lt;code&amp;gt;+&amp;lt;/code&amp;gt; operator. Instead, you'll have to use one of the following methods of string formatting:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
  &lt;br /&gt;
# Technique 1 – printf-style Formatting&lt;br /&gt;
# This is a classic style of string formatting, used in many programming languages, including in Java's String.format.&lt;br /&gt;
&amp;quot;You scored %d out of %d!&amp;quot; % (score, questions)&lt;br /&gt;
&lt;br /&gt;
# Technique 2 – str.format&lt;br /&gt;
&amp;quot;You scored {} out of {}!&amp;quot;.format(score, questions)&lt;br /&gt;
&lt;br /&gt;
# Technique 3 – f-strings&lt;br /&gt;
# These were only introduced in Python 3.6 but they're very convenient.&lt;br /&gt;
f&amp;quot;You scored {score} out of {questions}!&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# Technique 4 - String Concatenation&lt;br /&gt;
# This is fine for small things, but for more complicated stuff, use one of the other techniques.&lt;br /&gt;
&amp;quot;You scored &amp;quot; + str(score) + &amp;quot; out of &amp;quot; + str(questions) + &amp;quot;!&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&amp;lt;/ol&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Functions ===&lt;br /&gt;
&lt;br /&gt;
Define functions using the &amp;lt;code&amp;gt;def&amp;lt;/code&amp;gt; keyword:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def hello(name):&lt;br /&gt;
    print(f&amp;quot;Hello, {name}!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Invoke functions using parentheses:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
hello(&amp;quot;Batman&amp;quot;)&lt;br /&gt;
hello(&amp;quot;Superman&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Functions can have optional arguments; however, these must come after any required arguments:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def hello(name=&amp;quot;User&amp;quot;):&lt;br /&gt;
    print(f&amp;quot;Hello, {name}!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
hello() # Prints &amp;quot;Hello, User!&amp;quot;&lt;br /&gt;
hello(&amp;quot;Sarah&amp;quot;) # Prints &amp;quot;Hello, Sarah!&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Functions are just regular objects in Python, meaning you can do stuff like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def hello(name=&amp;quot;User&amp;quot;):&lt;br /&gt;
    print(&amp;quot;Hello, {name}!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
greeting = hello&lt;br /&gt;
&lt;br /&gt;
greeting(&amp;quot;Siwei&amp;quot;) # Prints &amp;quot;Hello, Siwei!&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Collection Types ===&lt;br /&gt;
Python has a few basic, built-in collection types. They each have their own special use cases, but they share a lot of similarities. All built-in data structures in Python are zero-indexed, for instance.&lt;br /&gt;
&lt;br /&gt;
To obtain the number of elements in a collection, use the &amp;lt;code&amp;gt;len()&amp;lt;/code&amp;gt; function, like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish'] # This is a list; you'll learn about them below.&lt;br /&gt;
&lt;br /&gt;
len(pets) # Returns 3&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To check if a collection contains an item, use the &amp;lt;code&amp;gt;in&amp;lt;/code&amp;gt; operator:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish'] # This is a list; you'll learn about them below.&lt;br /&gt;
&lt;br /&gt;
'Dog' in pets # Returns True&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Helpfully, the Python Software Foundation maintains a page containing the asymptotic complexities of important operations on major Python data structures. It's available [https://wiki.python.org/moin/TimeComplexity here].&lt;br /&gt;
&lt;br /&gt;
==== Lists ====&lt;br /&gt;
&lt;br /&gt;
Unlike languages like Java and C, Python's array-like type doesn't have fixed length. Instead, a &amp;lt;code&amp;gt;list&amp;lt;/code&amp;gt; is a dynamic array (like Java's &amp;lt;code&amp;gt;ArrayList&amp;lt;/code&amp;gt;) of objects of any type. Here's an example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = [&amp;quot;Apple&amp;quot;, &amp;quot;Pear&amp;quot;, &amp;quot;Orange&amp;quot;] # Lists can be creating by placing their items between square brackets&lt;br /&gt;
&lt;br /&gt;
random_items = ['Apple', 12312, 2.0, [1, 2, 3]] # Lists can contain objects of different types - even other lists!&lt;br /&gt;
&lt;br /&gt;
pets.append('Turtle') # Adds 'Turtle' to the end of pets&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For the next few examples, we'll be using the following list:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish', 'Turtle', 'Lizard', 'Snake']&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access or assign elements of a list, use the &amp;lt;code&amp;gt;[]&amp;lt;/code&amp;gt; operator.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[0] # Returns 'Dog'&lt;br /&gt;
pets[1] = 'Cow' # Sets pets[1] to 'Cow'&lt;br /&gt;
pets[1] = 'Cat' # Sets pets[1] back to 'Cat' &lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You can also access or assign lists using negative indices, which will return elements starting from the end of the list:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[-1] # Returns 'Snake'&lt;br /&gt;
pets[-2] # Returns 'Lizard'&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You can also use 'slice notation' to obtain or assign subsets of lists:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[start:end] # Returns items from index start to index end - 1.&lt;br /&gt;
pets[start:]    # Returns items from index start to the end of the list, inclusive.&lt;br /&gt;
pets[:end]      # Returns items from the beginning of the list to index end - 1.&lt;br /&gt;
pets[:]         # Returns every item in the list&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
There's also a third, optional argument: &amp;lt;code&amp;gt;step&amp;lt;/code&amp;gt;, which lets you jump over values:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[start:end:step] # Returns items from index start to index end - 1, jumping step values at a time&lt;br /&gt;
&lt;br /&gt;
# Examples:&lt;br /&gt;
pets[1:5:2] # Returns items from index 1 to index 4, jumping 2 at a time, so ['Cat', 'Turtle']&lt;br /&gt;
pets[::3] # Returns all items in the list, jumping 3 at a time, so ['Dog', 'Turtle']&lt;br /&gt;
pets[::-1] # Returns all items in the list, jumping -1 at a time. This reverses the list, so ['Snake', 'Lizard', 'Turtle', 'Fish', 'Cat', 'Dog']&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Lists have all the performance characteristics you'd expect of a dynamic array - constant-time indexing, amortized constant-time appends, and so on.&lt;br /&gt;
&lt;br /&gt;
==== Tuples ====&lt;br /&gt;
&lt;br /&gt;
Python has a special data type called &amp;lt;code&amp;gt;tuple&amp;lt;/code&amp;gt;, which is exactly the same as a list except for the fact that it cannot be modified, so you can't append or replace items.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
cities = ('St. Louis', 'Los Angeles', 'Seattle') # Tuples are defined using parentheses.&lt;br /&gt;
numbers = 1, 2, 3 # You can also omit the parentheses if it's unambiguous&lt;br /&gt;
single_item_tuple = (1,) # To make a tuple with only one item, put a comma after it&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Tuples also enable you to have multiple return values from a function:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def compute_length(string):&lt;br /&gt;
    str_len = len(string)&lt;br /&gt;
    if str_len &amp;lt; 5:&lt;br /&gt;
        return str_len, &amp;quot;short&amp;quot;&lt;br /&gt;
    elif str_len &amp;lt; 40:&lt;br /&gt;
        return str_len, &amp;quot;medium&amp;quot;&lt;br /&gt;
    return str_len, &amp;quot;long&amp;quot;&lt;br /&gt;
&lt;br /&gt;
length, description = compute_length(&amp;quot;Four score and seven years ago&amp;quot;)&lt;br /&gt;
print(&amp;quot;The %s string is %d characters long.&amp;quot; % (description, length))&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
The above example also demonstrates Python's if...elif...else conditional structure.&lt;br /&gt;
&lt;br /&gt;
==== Dictionaries ====&lt;br /&gt;
&lt;br /&gt;
Python has another datatype called a '''dictionary''' (or &amp;lt;code&amp;gt;dict&amp;lt;/code&amp;gt;, for short), which are like ''Maps'' in Java, ''associative arrays'' in PHP, and ''object literals'' in JavaScript (coming up soon in Module 6). Essentially, they enable you to use any immutable object as the key in your data structure. &amp;lt;code&amp;gt;dict&amp;lt;/code&amp;gt; objects can be created using either the &amp;lt;code&amp;gt;dict&amp;lt;/code&amp;gt; function, or by placing items between curly braces, separating keys and values using colons:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits_in_bowl = {&lt;br /&gt;
    'apple': 4,&lt;br /&gt;
    'banana': 2,&lt;br /&gt;
    'cherry': 0,&lt;br /&gt;
    'date': 12&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
apple_count = fruits_in_bowl['apple'] # Equals 4&lt;br /&gt;
&lt;br /&gt;
fruits_in_bowl['pear'] = 9 # Sets 'pear' in the dictionary to 9.&lt;br /&gt;
&lt;br /&gt;
for fruit, num in fruits_in_bowl.items():&lt;br /&gt;
    print(&amp;quot;There are %d %s(s) in the bowl.&amp;quot; % (num, fruit))&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If you only want the keys from a dictionary, you can just iterate over it directly, like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
for fruit in fruits_in_bowl:&lt;br /&gt;
    print(fruit)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If you want only the values but not the keys from a dictionary, use &amp;lt;code&amp;gt;my_dictionary.values()&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
==== Sets ==== &lt;br /&gt;
A &amp;lt;code&amp;gt;set&amp;lt;/code&amp;gt; is an unordered collection of unique items, with constant-time membership checking. &lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = {'Apple', 'Apple', 'Apple', 'Pear'} # The set removes duplicates, so it will only contain {'Apple', 'Pear'}&lt;br /&gt;
fruits = set(['Apple', 'Apple', 'Apple', 'Pear']) # This line transforms a list into a set&lt;br /&gt;
print('Apple' in fruits) # Constant-time!&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Loops ===&lt;br /&gt;
&lt;br /&gt;
In Python, while loops are written like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
i = 0&lt;br /&gt;
while i &amp;lt; 10:&lt;br /&gt;
    i += 1&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
For loops are written like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish']&lt;br /&gt;
&lt;br /&gt;
for pet in pets:&lt;br /&gt;
    print(pet)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
To iterate over a range of numbers, you can use the convenient &amp;lt;code&amp;gt;range&amp;lt;/code&amp;gt; function, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
for i in range(20, 30): # If you omit the first argument to range, it's assumed to be zero.&lt;br /&gt;
    print(i)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Note that &amp;lt;code&amp;gt;range&amp;lt;/code&amp;gt; provides a closed-open range. That is to say, it is inclusive of its lower bound and exclusive of its upper bound. To be very explicit about it:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
list(range(3, 6)) == [3, 4, 5]&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Unlike in other languages you may know, the following is not good practice in Python:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish']&lt;br /&gt;
&lt;br /&gt;
# BAD PRACTICE. DO NOT USE.&lt;br /&gt;
for i in range(len(pets)):&lt;br /&gt;
    pet = pets[i]&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Instead, if you need to access both a variable and its index, use the &amp;lt;code&amp;gt;enumerate&amp;lt;/code&amp;gt; function, which allows you to iterate through a group of items, along with their indexes, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish']&lt;br /&gt;
&lt;br /&gt;
for index, pet in enumerate(pets):&lt;br /&gt;
    print(&amp;quot;%s at index %d&amp;quot;; % (pet, index))&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Generator Expressions and Comprehensions ===&lt;br /&gt;
&lt;br /&gt;
A generator is a special kind of object that, basically, represents a collection of items using a value and a function for generating the next value in the collection. In other words, it's a way of creating something that behaves like a list, but which only generates one value at a time, and discards a value when it's done with it. Say, for example, you wanted to do an operation on 10,000,000,000,000 numbers. You could put them all in a list, then iterate over the list, but that would take a lot of memory, plus you'd have to create and fill the entire list before beginning to actually work on your problem. Instead, you'd probably be better off using a generator; telling the computer, essentially: “The starting value is 0. When I ask for the next number in the collection, add 1 to current value and give me that.”&lt;br /&gt;
&lt;br /&gt;
A generator expression is an expression that is evaluated to create a generator. They're super useful. Generator expressions can take two forms – they can be used with and without a condition:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
(EXPRESSION for VARIABLE in ITERABLE) # Unconditional&lt;br /&gt;
(EXPRESSION for VARIABLE in ITERABLE if CONDITION) # Conditional&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
For our purposes, you can think of an iterable as anything you can do a for loop over. Let's take a look at a generator expression in use:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
double_even_digits = (number * 2 for number in range(10) if number % 2 == 0)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
That line says that &amp;lt;code&amp;gt;double_even_digits&amp;lt;/code&amp;gt; is every even number between 0 and 10 multiplied by two. Simple enough, right? If we wanted to use all of the numbers, not just the even ones, we could simply remove the if statement at the end of the expression.&lt;br /&gt;
&lt;br /&gt;
Here's the thing, though: if you were to print &amp;lt;code&amp;gt;double_even_digits&amp;lt;/code&amp;gt;, instead of a nice bunch of numbers, you'd get something that looks like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&amp;lt;generator object &amp;lt;genexpr&amp;gt;&amp;lt;code&amp;gt;at 0x107fc92b0&amp;gt;&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
That's because generators are lazy! They don't generate their values until those values are needed, and they discard values once they're no longer needed. As a result, '''you can only iterate over a generator once'''. In this case, you can't print out the whole generator, because it hasn't generated all the values yet. You can, however, iterate over the generator, and print its values one at a time, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
for number in double_even_digits:&lt;br /&gt;
    print(number)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
You can also make a list out of the generator, which will go through all the items in the generator and put them in a list, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
even_number_list = list(double_even_digits)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
That's actually a great segue to the second topic of this section: comprehensions. A comprehension is just a prettier way to make lists, sets, and dicts out of a generator expressions.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
# If you want a list:&lt;br /&gt;
list(i for i in range(10) if i % 2 == 0) # Don't do this&lt;br /&gt;
[i for i in range(10) if i % 2 == 0] # Use a list comprehension instead!&lt;br /&gt;
&lt;br /&gt;
# If you want a set:&lt;br /&gt;
set(i for i in range(10) if i % 2 == 0) # Don't do this&lt;br /&gt;
{i for i in range(10) if i % 2 == 0} # Use a set comprehension instead!&lt;br /&gt;
&lt;br /&gt;
# If you want a dict:&lt;br /&gt;
dict((i, i + 1) for i in range(10) if i % 2 == 0) # Don't do this&lt;br /&gt;
{i : i + 1 for i in range(10) if i % 2 == 0} # Use a dict comprehension instead!&lt;br /&gt;
&lt;br /&gt;
# If you want a tuple:&lt;br /&gt;
tuple(i for i in range(10) if i % 2 == 0) # Unfortunately, there's no better way to do this&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
In general, generators and comprehensions should be used whenever possible - they're the fastest and easiest way to build collections. If you ever see yourself writing code like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
# BAD PRACTICE! DO NOT USE!&lt;br /&gt;
digits = []&lt;br /&gt;
for digit in range(10):&lt;br /&gt;
    digits.append(digit)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Don't do it! Instead, use a generator expression or comprehension, as appropriate. A good way to decide whether a generator expression or comprehension is better for this situation is that, if you're just going to be iterating over your collection once, you should use an generator expression. If not, use a comprehension.&lt;br /&gt;
&lt;br /&gt;
=== Sorting ===&lt;br /&gt;
&lt;br /&gt;
Sorting in Python is frequently performed using the &amp;lt;code&amp;gt;sorted&amp;lt;/code&amp;gt; function, which takes two arguments: an iterable (anything you can do a for-loop over, including lists and tuples) and a function used to evaluate each item. If the function is omitted, Python will try to sort the lists by value.&lt;br /&gt;
&lt;br /&gt;
The following example demonstrates using an inline function, which Python calls a ''lambda''.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = ['apple', 'banana', 'cherry', 'date']&lt;br /&gt;
&lt;br /&gt;
# sort the fruits by string length&lt;br /&gt;
new_fruits = sorted(fruits, key=lambda v: len(v) // 2)&lt;br /&gt;
&lt;br /&gt;
print(new_fruits) # ['date', 'apple', 'banana', 'cherry']&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Alternatively, you can sort a &amp;lt;code&amp;gt;list&amp;lt;/code&amp;gt; using the &amp;lt;code&amp;gt;.sort&amp;lt;/code&amp;gt; method. This is faster than calling &amp;lt;code&amp;gt;sorted&amp;lt;/code&amp;gt;, but it modifies the list in-place and returns &amp;lt;code&amp;gt;None&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = ['apple', 'banana', 'cherry', 'date']&lt;br /&gt;
fruits.sort()&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
=== Import ===&lt;br /&gt;
&lt;br /&gt;
If you want to use functions from other libraries (including ones that you install using pip), use &amp;lt;code&amp;gt;import&amp;lt;/code&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
import time&lt;br /&gt;
&lt;br /&gt;
current_time = time.localtime()&lt;br /&gt;
print(time.strftime('%a, %d %b %Y %H:%M:%S', current_time))&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If you want to pull the functions out of their namespace, you can use &amp;lt;code&amp;gt;from ___ import ___&amp;lt;/code&amp;gt; syntax:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
from time import localtime, strftime&lt;br /&gt;
&lt;br /&gt;
current_time = localtime()&lt;br /&gt;
print(strftime('%a, %d %b %Y %H:%M:%S', current_time))&lt;br /&gt;
&lt;br /&gt;
# Be aware that this technique, although convenient, may cause unexpected behavior if the function names that you're pulling out of the namespace are already used for other purposes in Python.&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
=== File I/O ===&lt;br /&gt;
&lt;br /&gt;
You can read an entire file into a variable like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
f = open(&amp;quot;example.txt&amp;quot;)&lt;br /&gt;
file_contents = f.read()&lt;br /&gt;
&lt;br /&gt;
f.close() # free up memory when we're finished with the file&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
A better option is to use a with-block, which handles opening and closing the file for you automatically:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
with open(&amp;quot;example.txt&amp;quot;) as f:&lt;br /&gt;
    file_contents = f.read()&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
You can read a file line-by-line like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
with open(&amp;quot;example.txt&amp;quot;) as f:&lt;br /&gt;
    for line in f:&lt;br /&gt;
        print(&amp;quot;Read line: %s&amp;quot; % line.rstrip())&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
You can write to a file like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
with open(&amp;quot;example.txt&amp;quot;, &amp;quot;w&amp;quot;) as f:&lt;br /&gt;
    f.write(&amp;quot;Hello\nWorld\n&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
=== Command-Line Arguments ===&lt;br /&gt;
&lt;br /&gt;
Command line arguments are accessible in the variable &amp;lt;code&amp;gt;sys.argv&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
The following example shows a program that expects a filename as its argument, and it prints a usage message if the argument is not present ([https://stackoverflow.com/questions/983201/python-and-sys-argv source]).&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
import sys, os&lt;br /&gt;
&lt;br /&gt;
if len(sys.argv) &amp;lt; 2:&lt;br /&gt;
    sys.exit(&amp;quot;Usage: %s filename&amp;quot; % sys.argv[0])&lt;br /&gt;
&lt;br /&gt;
filename = sys.argv[1]&lt;br /&gt;
&lt;br /&gt;
if not os.path.exists(filename):&lt;br /&gt;
    sys.exit(&amp;quot;Error: File '%s' not found&amp;quot; % sys.argv[1])&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
=== Object-Oriented Programming ===&lt;br /&gt;
&lt;br /&gt;
You can define and use a class like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
class Food:&lt;br /&gt;
    # constructor:&lt;br /&gt;
    def __init__(self, name):&lt;br /&gt;
        self.name = name&lt;br /&gt;
    &lt;br /&gt;
    def format_name(self):&lt;br /&gt;
        return &amp;quot;Gotta love to eat &amp;quot; + self.name&lt;br /&gt;
&lt;br /&gt;
class Fruit(Food):&lt;br /&gt;
    def format_name(self):&lt;br /&gt;
        return Food.format_name(self) + &amp;quot; (fruit)&amp;quot;&lt;br /&gt;
&lt;br /&gt;
fruit = Fruit(&amp;quot;Cherry&amp;quot;)&lt;br /&gt;
print(fruit.format_name())&lt;br /&gt;
print(Food.get_definition())&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
This is the same example as in [[PHP#Object-Oriented_Programming|the PHP guide]].&lt;br /&gt;
&lt;br /&gt;
Some things to notice:&lt;br /&gt;
&lt;br /&gt;
* Instance methods ''always'' take &amp;lt;code&amp;gt;self&amp;lt;/code&amp;gt; as their first argument, followed by any number of additional parameters. This can be misleading for programmers familiar with other languages, because the number of arguments you feed to the method is actually ''one less than'' the number of declared parameters. Whenever you call a method on a class instance, that instance is implicitly fed into the explicitly-declared &amp;lt;code&amp;gt;self&amp;lt;/code&amp;gt; parameter of the method.&lt;br /&gt;
*: Note that the &amp;lt;code&amp;gt;self&amp;lt;/code&amp;gt; variable has the same purpose as the &amp;lt;code&amp;gt;this&amp;lt;/code&amp;gt; variable in languages like PHP, Java, JavaScript, and C++.&lt;br /&gt;
*There is no need for a &amp;lt;code&amp;gt;new&amp;lt;/code&amp;gt; keyword in Python.&lt;br /&gt;
&lt;br /&gt;
= Footnotes =&lt;br /&gt;
# {{note|interpreted}}This is an oversimplification. If you're interested, here's a quick explanation of how: In CPython (the reference implementation of Python) programs are compiled to bytecode, an intermediate representation, which is then interpreted.&lt;br /&gt;
[[Category:Module 4]]&lt;/div&gt;</summary>
		<author><name>Alex</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Python&amp;diff=2511</id>
		<title>Python</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Python&amp;diff=2511"/>
		<updated>2018-02-19T17:25:53Z</updated>

		<summary type="html">&lt;p&gt;Alex: /* An Example Python Script */  Updated format strings&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Languages like Java and C++ have lots of rules regarding variable types, syntax, return values, and so on. These can be cumbersome when you are trying to write short, quick scripts to perform tasks. This is where a ''scripting language'' comes into play.&lt;br /&gt;
&lt;br /&gt;
'''Python''' is a language well-suited to rapid prototype development. It is generally an ''interpreted language'', which means that, generally speaking, a Python program is converted line by line into instructions for the computer to execute as the program runs, instead of having a separate compilation step beforehand {{ref|interpreted}}. The syntax is clean, and it is usually clear at first glance what is going on when you write in Python.&lt;br /&gt;
&lt;br /&gt;
= Installation =&lt;br /&gt;
&lt;br /&gt;
Python may already be installed on your system. To see whether or not it is, enter the command&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ python --version&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If it tells you a version of Python '''greater than or equal to 3.5''' then you're good to go. If not, you need to do a quick package install to get it up and running. Using yum, it's just &amp;lt;code&amp;gt;sudo yum install python35; sudo alternatives --set python /usr/bin/python3&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
==== Python 2 vs Python 3 ====&lt;br /&gt;
&lt;br /&gt;
In 2008, a new version of Python – Python 3 – was released, with a number changes that made it incompatible with the previous version, Python 2. For several years, the Python community was slow to make the change to Python 3, but today, Python 3 is ''the'' standard for new code. The ''only'' reason to write Python 2 code today is because you have to work in an environment or with libraries that do not support Python 3, and that situation is becoming increasingly rare.&lt;br /&gt;
&lt;br /&gt;
'''For CSE 330 (and this guide), you ''must'' use Python 3.5 or greater.'''&lt;br /&gt;
&lt;br /&gt;
=== Pip ===&lt;br /&gt;
&lt;br /&gt;
Linux distributions have package managers like ''Apt'', ''Yum'', and ''YaST''. PHP has a package manager named ''PEAR''. It's now time to introduce Python's leading package manager: '''pip'''.&lt;br /&gt;
&lt;br /&gt;
You need to install Pip from Yum before you can use it. The package is called &amp;lt;code&amp;gt;python-pip&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Once you have pip installed, you can use it to install Python packages. Use the &amp;lt;code&amp;gt;pip-python&amp;lt;/code&amp;gt; command:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ pip-python install package_name # RHEL&lt;br /&gt;
$ pip install package_name # Debian&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
= Running Python =&lt;br /&gt;
&lt;br /&gt;
There are two common ways to run Python code: via the console, and via a Python script file.&lt;br /&gt;
&lt;br /&gt;
=== The Python Console ===&lt;br /&gt;
&lt;br /&gt;
The Python console enables you to experiment with code without opening a text editor. To enter the Python console, simply type the ''python'' command at the terminal:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ python&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
To leave the interactive console, either type &amp;lt;code&amp;gt;quit()&amp;lt;/code&amp;gt; or press &amp;lt;code&amp;gt;Ctrl-D&amp;lt;/code&amp;gt; (on both Mac and Windows).&lt;br /&gt;
&lt;br /&gt;
=== Python Script Files ===&lt;br /&gt;
&lt;br /&gt;
You can also save Python script files for later use. The extension for Python scripts is &amp;lt;code&amp;gt;*.py&amp;lt;/code&amp;gt;. To run a script file, simply feed its path as an argument to the &amp;lt;code&amp;gt;python&amp;lt;/code&amp;gt; command in Terminal:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ python my_script.py&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Python Syntax and Language Components =&lt;br /&gt;
&lt;br /&gt;
This section contains a very brief overview of Python syntax. For a more comprehensive introduction, see [http://docs.python.org/tutorial/ the Python docs].&lt;br /&gt;
&lt;br /&gt;
=== Python's Type System ===&lt;br /&gt;
&lt;br /&gt;
Python is a dynamically-typed, strongly-typed, and duck-typed language. What does that mean? Well, let's take those categories one by one:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;ol&amp;gt;&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
'''Dynamic typing''', in contrast to ''static typing'' means that the types of objects can be changed. In Java, for instance, if you tried to write the following code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
int c = 2;&lt;br /&gt;
c = &amp;quot;fish&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Your code would fail to compile, because the Java compiler wouldn't allow you to change the type of the variable &amp;lt;code&amp;gt;c&amp;lt;/code&amp;gt; from &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt; to &amp;lt;code&amp;gt;String&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Python, however, is just fine with that. You can write:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
c = 2&lt;br /&gt;
c = &amp;quot;fish&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
And Python will happily do what you ask.&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
'''Strong typing''', in contrast to ''weak typing'', means, roughly, that a language won't implicitly convert types for you. So far, you've used a lot of PHP, which is very weakly typed. For example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;php&amp;quot;&amp;gt;&lt;br /&gt;
echo &amp;quot;10&amp;quot; . 2;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In PHP, this works just fine. The PHP interpreter sees that &amp;lt;code&amp;gt;2&amp;lt;/code&amp;gt; is an int, and silently converts it to a string for you, so that &amp;lt;code&amp;gt;&amp;quot;10&amp;quot;. 2&amp;lt;/code&amp;gt; equals &amp;lt;code&amp;gt;&amp;quot;102&amp;quot;&amp;lt;/code&amp;gt;. The problem with weak typing is that it can make it unclear to the programmer why things are happening the way they are. For instance, in PHP, the expression &amp;lt;code&amp;gt;&amp;quot;10&amp;quot; == 10&amp;lt;/code&amp;gt; is true, which can be less than obvious. Python, however, tries to disallow that sort of thing:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
&amp;quot;10&amp;quot; + &amp;quot;10&amp;quot; # Allowed – concatenates the two strings.&lt;br /&gt;
10   +  10  # Allowed – adds the two ints.&lt;br /&gt;
&amp;quot;10&amp;quot; +  10  # Not allowed – raises a TypeError&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Perhaps the one exception to this rule is the relationship between numeric types; it's perfectly fine to add a float to an int, for example.&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
'''Duck-typing''' is a little bit different than the other categories, because it doesn't really have a direct opposite. Essentially, duck-typing is the philosophy that &amp;quot;If it walks like a duck, and quacks like a duck, it's a duck.&amp;quot; In programming terms, that means that we often don't care what type an object is, as long as it can do the things we ask.&lt;br /&gt;
&lt;br /&gt;
Let's look at an example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
# This function doubles the value it's passed.&lt;br /&gt;
def double(thing):&lt;br /&gt;
    return thing + thing&lt;br /&gt;
double(10) # Returns 20&lt;br /&gt;
double(&amp;quot;fish&amp;quot;) # Returns &amp;quot;fishfish&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If this were Java, we'd have to write two different methods here: one for things of type &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt;, and one for things of type &amp;lt;code&amp;gt;String&amp;lt;/code&amp;gt;. Since this is Python, though, we don't have to do that. Instead, Python lets us say, essentially: &amp;quot;This function uses the &amp;lt;code&amp;gt;+&amp;lt;/code&amp;gt; operator, so you can pass whatever object you want to the function, as long as the function supports the &amp;lt;code&amp;gt;+&amp;lt;/code&amp;gt; operator&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
To quote [https://groups.google.com/forum/?hl=en#!msg/comp.lang.python/CCs2oJdyuzc/NYjla5HKMOIJ Alex Martelli], one of the key people in the Python project,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;blockquote&amp;gt;&lt;br /&gt;
&amp;quot;[Don't] check whether it IS-a duck: check whether it QUACKS-like-a duck, WALKS-like-a duck, etc, etc, depending on exactly what subset of duck-like behaviour you need.&amp;quot;&lt;br /&gt;
&amp;lt;/blockquote&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&amp;lt;/ol&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Basic Types ===&lt;br /&gt;
&lt;br /&gt;
In Python, the basic scalar types are:&lt;br /&gt;
&lt;br /&gt;
# &amp;lt;code&amp;gt;str&amp;lt;/code&amp;gt; – a string.&lt;br /&gt;
# &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt; – an integer object with unlimited digits.&lt;br /&gt;
# &amp;lt;code&amp;gt;bool&amp;lt;/code&amp;gt; – a Boolean value.&lt;br /&gt;
# &amp;lt;code&amp;gt;float&amp;lt;/code&amp;gt; – a floating point number; generally equivalent to &amp;lt;code&amp;gt;double&amp;lt;/code&amp;gt; in Java.&lt;br /&gt;
# &amp;lt;code&amp;gt;bytes&amp;lt;/code&amp;gt; – represents a collection of bytes; you're unlikely to use this often.&lt;br /&gt;
&lt;br /&gt;
Casting is done in the C style - to parse an &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt; from a string, for instance, you'd write &amp;lt;code&amp;gt;int(&amp;quot;123&amp;quot;)&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== Basic Control Flow ===&lt;br /&gt;
In Python, blocks of code are delineated using colons and indentation instead of curly braces. '''''That means that proper indentation is mandatory.''''' Every time you use a colon, you must indent one step further, and every time a block ends, you must unindent a step.&lt;br /&gt;
&lt;br /&gt;
Conditional statements are done using the &amp;lt;code&amp;gt;if&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;elif&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;else&amp;lt;/code&amp;gt; operators, like in the example below - pay attention to the indentation:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
cookies_left = 10&lt;br /&gt;
cake_slices_left = 3&lt;br /&gt;
if cookies_left &amp;gt; 10:&lt;br /&gt;
    print(&amp;quot;Lots of cookies!&amp;quot;)&lt;br /&gt;
elif cookies_left &amp;gt; 8:&lt;br /&gt;
    print(&amp;quot;Plenty left!&amp;quot;)&lt;br /&gt;
elif cookies_left == 5:&lt;br /&gt;
    print(&amp;quot;Halfway done!&amp;quot;)&lt;br /&gt;
else:&lt;br /&gt;
    if cake_slices_left == 3:&lt;br /&gt;
        print(&amp;quot;Lots of cake!&amp;quot;)&lt;br /&gt;
    elif cake_slices_left == 2:&lt;br /&gt;
        print(&amp;quot;One slice gone!&amp;quot;)&lt;br /&gt;
    else:&lt;br /&gt;
        print(&amp;quot;Little to no cake left!&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== An Example Python Script ===&lt;br /&gt;
&lt;br /&gt;
In my mind, there's no better way to learn Python than to be immersed in a simple example script.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
print(&amp;quot;Hello World&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
fruits = [&amp;quot;apple&amp;quot;, &amp;quot;banana&amp;quot;, &amp;quot;cherry&amp;quot;, &amp;quot;date&amp;quot;]&lt;br /&gt;
for fruit in fruits:&lt;br /&gt;
    print(f&amp;quot;I always love to eat a fresh {fruit}&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Map the fruits list over to a new list containing the length of the fruit strings:&lt;br /&gt;
fruit_size = [len(fruit) for fruit in fruits]&lt;br /&gt;
&lt;br /&gt;
avg_fruit_size = sum(fruit_size) / len(fruit_size)&lt;br /&gt;
print(f&amp;quot;The average fruit string length is {avg_fruit_size:.2f}.&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Some things to notice:&lt;br /&gt;
&lt;br /&gt;
* Printing is achieved using the &amp;lt;code&amp;gt;print()&amp;lt;/code&amp;gt; function.&lt;br /&gt;
* Comments start with a pound symbol &amp;lt;code&amp;gt;#&amp;lt;/code&amp;gt;.&lt;br /&gt;
* We can transform/map a list to a new list in just one line!&lt;br /&gt;
&lt;br /&gt;
For some more examples, see [https://wiki.python.org/moin/SimplePrograms the Python wiki].&lt;br /&gt;
&lt;br /&gt;
=== A Few Gotchas ===&lt;br /&gt;
&lt;br /&gt;
Here are a few things you may not expect when starting out with Python:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;ol&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
Strings can be delimited using either single quotes (&amp;lt;code&amp;gt;'&amp;lt;/code&amp;gt;) or double quotes (&amp;lt;code&amp;gt;&amp;quot;&amp;lt;/code&amp;gt;), so &amp;lt;code&amp;gt;'Python'&amp;lt;/code&amp;gt; is the same as &amp;lt;code&amp;gt;&amp;quot;Python&amp;quot;&amp;lt;/code. You can also use three sets of quotes (&amp;lt;code&amp;gt;'''&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;&amp;quot;&amp;quot;&amp;quot;&amp;lt;/code&amp;gt;) to delineate a multiple-line string, like so:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
long_string = &amp;quot;&amp;quot;&amp;quot;This&lt;br /&gt;
is my&lt;br /&gt;
very long&lt;br /&gt;
multiple-line&lt;br /&gt;
string&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
To compare the equality of two objects, use the &amp;lt;code&amp;gt;==&amp;lt;/code&amp;gt; operator. To compare the identity of two objects (i.e. whether or not they are literally the same object, at the same place in memory), use the &amp;lt;code&amp;gt;is&amp;lt;/code&amp;gt; operator. These correspond, respectively to &amp;lt;code&amp;gt;.equals()&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;==&amp;lt;/code&amp;gt; in Java.&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
The &amp;lt;code&amp;gt;/&amp;lt;/code&amp;gt; operator performs floating-point division, not integer division, even when both its arguments are integers. If you want to do integer division, use the &amp;lt;code&amp;gt;//&amp;lt;/code&amp;gt; operator. Let's look at an example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
9   / 10    == 0.9 # Floating-point division&lt;br /&gt;
9.0 / 10.0  == 0.9 # Floating-point division&lt;br /&gt;
9   // 10   == 0   # Integer division&lt;br /&gt;
9.0 // 10.0 == 0.0 # Integer division, even though the resulting value is a float&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;li&amp;gt;&lt;br /&gt;
As discussed in the section [[#Python's_Type_System|Python's Type System]], you can't combine strings and numbers using the &amp;lt;code&amp;gt;+&amp;lt;/code&amp;gt; operator. Instead, you'll have to use one of the following methods of string formatting:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
  &lt;br /&gt;
# Technique 1 – printf-style Formatting&lt;br /&gt;
# This is a classic style of string formatting, used in many programming languages, including in Java's String.format.&lt;br /&gt;
&amp;quot;You scored %d out of %d!&amp;quot; % (score, questions)&lt;br /&gt;
&lt;br /&gt;
# Technique 2 – str.format&lt;br /&gt;
&amp;quot;You scored {} out of {}!&amp;quot;.format(score, questions)&lt;br /&gt;
&lt;br /&gt;
# Technique 3 – f-strings&lt;br /&gt;
# These were only introduced in Python 3.6 but they're very convenient.&lt;br /&gt;
f&amp;quot;You scored {score} out of {questions}!&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# Technique 4 - String Concatenation&lt;br /&gt;
# This is fine for small things, but for more complicated stuff, use one of the other techniques.&lt;br /&gt;
&amp;quot;You scored &amp;quot; + str(score) + &amp;quot; out of &amp;quot; + str(questions) + &amp;quot;!&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&amp;lt;/li&amp;gt;&lt;br /&gt;
&amp;lt;/ol&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Functions ===&lt;br /&gt;
&lt;br /&gt;
Define functions using the &amp;lt;code&amp;gt;def&amp;lt;/code&amp;gt; keyword:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def hello(name):&lt;br /&gt;
    print(&amp;quot;Hello, %s!&amp;quot; % name)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Invoke functions using parentheses:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
hello(&amp;quot;Batman&amp;quot;)&lt;br /&gt;
hello(&amp;quot;Superman&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Functions can have optional arguments; however, these must come after any required arguments:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def hello(name=&amp;quot;User&amp;quot;):&lt;br /&gt;
    print(&amp;quot;Hello, %s!&amp;quot; % name)&lt;br /&gt;
&lt;br /&gt;
hello() # Prints &amp;quot;Hello, User!&amp;quot;&lt;br /&gt;
hello(&amp;quot;Sarah&amp;quot;) # Prints &amp;quot;Hello, Sarah!&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Functions are just regular objects in Python, meaning you can do stuff like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def hello(name=&amp;quot;User&amp;quot;):&lt;br /&gt;
    print(&amp;quot;Hello, %s!&amp;quot; % name)&lt;br /&gt;
&lt;br /&gt;
greeting = hello&lt;br /&gt;
&lt;br /&gt;
greeting(&amp;quot;Siwei&amp;quot;) # Prints &amp;quot;Hello, Siwei!&amp;quot;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Collection Types ===&lt;br /&gt;
Python has a few basic, built-in collection types. They each have their own special use cases, but they share a lot of similarities. All built-in data structures in Python are zero-indexed, for instance.&lt;br /&gt;
&lt;br /&gt;
To obtain the number of elements in a collection, use the &amp;lt;code&amp;gt;len()&amp;lt;/code&amp;gt; function, like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish'] # This is a list; you'll learn about them below.&lt;br /&gt;
&lt;br /&gt;
len(pets) # Returns 3&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To check if a collection contains an item, use the &amp;lt;code&amp;gt;in&amp;lt;/code&amp;gt; operator:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish'] # This is a list; you'll learn about them below.&lt;br /&gt;
&lt;br /&gt;
'Dog' in pets # Returns True&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Helpfully, the Python Software Foundation maintains a page containing the asymptotic complexities of important operations on major Python data structures. It's available [https://wiki.python.org/moin/TimeComplexity here].&lt;br /&gt;
&lt;br /&gt;
==== Lists ====&lt;br /&gt;
&lt;br /&gt;
Unlike languages like Java and C, Python's array-like type doesn't have fixed length. Instead, a &amp;lt;code&amp;gt;list&amp;lt;/code&amp;gt; is a dynamic array (like Java's &amp;lt;code&amp;gt;ArrayList&amp;lt;/code&amp;gt;) of objects of any type. Here's an example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = [&amp;quot;Apple&amp;quot;, &amp;quot;Pear&amp;quot;, &amp;quot;Orange&amp;quot;] # Lists can be creating by placing their items between square brackets&lt;br /&gt;
&lt;br /&gt;
random_items = ['Apple', 12312, 2.0, [1, 2, 3]] # Lists can contain objects of different types - even other lists!&lt;br /&gt;
&lt;br /&gt;
pets.append('Turtle') # Adds 'Turtle' to the end of pets&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For the next few examples, we'll be using the following list:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish', 'Turtle', 'Lizard', 'Snake']&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access or assign elements of a list, use the &amp;lt;code&amp;gt;[]&amp;lt;/code&amp;gt; operator.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[0] # Returns 'Dog'&lt;br /&gt;
pets[1] = 'Cow' # Sets pets[1] to 'Cow'&lt;br /&gt;
pets[1] = 'Cat' # Sets pets[1] back to 'Cat' &lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You can also access or assign lists using negative indices, which will return elements starting from the end of the list:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[-1] # Returns 'Snake'&lt;br /&gt;
pets[-2] # Returns 'Lizard'&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You can also use 'slice notation' to obtain or assign subsets of lists:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[start:end] # Returns items from index start to index end - 1.&lt;br /&gt;
pets[start:]    # Returns items from index start to the end of the list, inclusive.&lt;br /&gt;
pets[:end]      # Returns items from the beginning of the list to index end - 1.&lt;br /&gt;
pets[:]         # Returns every item in the list&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
There's also a third, optional argument: &amp;lt;code&amp;gt;step&amp;lt;/code&amp;gt;, which lets you jump over values:&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets[start:end:step] # Returns items from index start to index end - 1, jumping step values at a time&lt;br /&gt;
&lt;br /&gt;
# Examples:&lt;br /&gt;
pets[1:5:2] # Returns items from index 1 to index 4, jumping 2 at a time, so ['Cat', 'Turtle']&lt;br /&gt;
pets[::3] # Returns all items in the list, jumping 3 at a time, so ['Dog', 'Turtle']&lt;br /&gt;
pets[::-1] # Returns all items in the list, jumping -1 at a time. This reverses the list, so ['Snake', 'Lizard', 'Turtle', 'Fish', 'Cat', 'Dog']&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Lists have all the performance characteristics you'd expect of a dynamic array - constant-time indexing, amortized constant-time appends, and so on.&lt;br /&gt;
&lt;br /&gt;
==== Tuples ====&lt;br /&gt;
&lt;br /&gt;
Python has a special data type called &amp;lt;code&amp;gt;tuple&amp;lt;/code&amp;gt;, which is exactly the same as a list except for the fact that it cannot be modified, so you can't append or replace items.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
cities = ('St. Louis', 'Los Angeles', 'Seattle') # Tuples are defined using parentheses.&lt;br /&gt;
numbers = 1, 2, 3 # You can also omit the parentheses if it's unambiguous&lt;br /&gt;
single_item_tuple = (1,) # To make a tuple with only one item, put a comma after it&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Tuples also enable you to have multiple return values from a function:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def compute_length(string):&lt;br /&gt;
    str_len = len(string)&lt;br /&gt;
    if str_len &amp;lt; 5:&lt;br /&gt;
        return str_len, &amp;quot;short&amp;quot;&lt;br /&gt;
    elif str_len &amp;lt; 40:&lt;br /&gt;
        return str_len, &amp;quot;medium&amp;quot;&lt;br /&gt;
    return str_len, &amp;quot;long&amp;quot;&lt;br /&gt;
&lt;br /&gt;
length, description = compute_length(&amp;quot;Four score and seven years ago&amp;quot;)&lt;br /&gt;
print(&amp;quot;The %s string is %d characters long.&amp;quot; % (description, length))&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
The above example also demonstrates Python's if...elif...else conditional structure.&lt;br /&gt;
&lt;br /&gt;
==== Dictionaries ====&lt;br /&gt;
&lt;br /&gt;
Python has another datatype called a '''dictionary''' (or &amp;lt;code&amp;gt;dict&amp;lt;/code&amp;gt;, for short), which are like ''Maps'' in Java, ''associative arrays'' in PHP, and ''object literals'' in JavaScript (coming up soon in Module 6). Essentially, they enable you to use any immutable object as the key in your data structure. &amp;lt;code&amp;gt;dict&amp;lt;/code&amp;gt; objects can be created using either the &amp;lt;code&amp;gt;dict&amp;lt;/code&amp;gt; function, or by placing items between curly braces, separating keys and values using colons:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits_in_bowl = {&lt;br /&gt;
    'apple': 4,&lt;br /&gt;
    'banana': 2,&lt;br /&gt;
    'cherry': 0,&lt;br /&gt;
    'date': 12&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
apple_count = fruits_in_bowl['apple'] # Equals 4&lt;br /&gt;
&lt;br /&gt;
fruits_in_bowl['pear'] = 9 # Sets 'pear' in the dictionary to 9.&lt;br /&gt;
&lt;br /&gt;
for fruit, num in fruits_in_bowl.items():&lt;br /&gt;
    print(&amp;quot;There are %d %s(s) in the bowl.&amp;quot; % (num, fruit))&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If you only want the keys from a dictionary, you can just iterate over it directly, like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
for fruit in fruits_in_bowl:&lt;br /&gt;
    print(fruit)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If you want only the values but not the keys from a dictionary, use &amp;lt;code&amp;gt;my_dictionary.values()&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
==== Sets ==== &lt;br /&gt;
A &amp;lt;code&amp;gt;set&amp;lt;/code&amp;gt; is an unordered collection of unique items, with constant-time membership checking. &lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = {'Apple', 'Apple', 'Apple', 'Pear'} # The set removes duplicates, so it will only contain {'Apple', 'Pear'}&lt;br /&gt;
fruits = set(['Apple', 'Apple', 'Apple', 'Pear']) # This line transforms a list into a set&lt;br /&gt;
print('Apple' in fruits) # Constant-time!&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Loops ===&lt;br /&gt;
&lt;br /&gt;
In Python, while loops are written like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
i = 0&lt;br /&gt;
while i &amp;lt; 10:&lt;br /&gt;
    i += 1&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
For loops are written like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish']&lt;br /&gt;
&lt;br /&gt;
for pet in pets:&lt;br /&gt;
    print(pet)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
To iterate over a range of numbers, you can use the convenient &amp;lt;code&amp;gt;range&amp;lt;/code&amp;gt; function, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
for i in range(20, 30): # If you omit the first argument to range, it's assumed to be zero.&lt;br /&gt;
    print(i)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Note that &amp;lt;code&amp;gt;range&amp;lt;/code&amp;gt; provides a closed-open range. That is to say, it is inclusive of its lower bound and exclusive of its upper bound. To be very explicit about it:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
list(range(3, 6)) == [3, 4, 5]&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Unlike in other languages you may know, the following is not good practice in Python:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish']&lt;br /&gt;
&lt;br /&gt;
# BAD PRACTICE. DO NOT USE.&lt;br /&gt;
for i in range(len(pets)):&lt;br /&gt;
    pet = pets[i]&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Instead, if you need to access both a variable and its index, use the &amp;lt;code&amp;gt;enumerate&amp;lt;/code&amp;gt; function, which allows you to iterate through a group of items, along with their indexes, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
pets = ['Dog', 'Cat', 'Fish']&lt;br /&gt;
&lt;br /&gt;
for index, pet in enumerate(pets):&lt;br /&gt;
    print(&amp;quot;%s at index %d&amp;quot;; % (pet, index))&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Generator Expressions and Comprehensions ===&lt;br /&gt;
&lt;br /&gt;
A generator is a special kind of object that, basically, represents a collection of items using a value and a function for generating the next value in the collection. In other words, it's a way of creating something that behaves like a list, but which only generates one value at a time, and discards a value when it's done with it. Say, for example, you wanted to do an operation on 10,000,000,000,000 numbers. You could put them all in a list, then iterate over the list, but that would take a lot of memory, plus you'd have to create and fill the entire list before beginning to actually work on your problem. Instead, you'd probably be better off using a generator; telling the computer, essentially: “The starting value is 0. When I ask for the next number in the collection, add 1 to current value and give me that.”&lt;br /&gt;
&lt;br /&gt;
A generator expression is an expression that is evaluated to create a generator. They're super useful. Generator expressions can take two forms – they can be used with and without a condition:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
(EXPRESSION for VARIABLE in ITERABLE) # Unconditional&lt;br /&gt;
(EXPRESSION for VARIABLE in ITERABLE if CONDITION) # Conditional&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
For our purposes, you can think of an iterable as anything you can do a for loop over. Let's take a look at a generator expression in use:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
double_even_digits = (number * 2 for number in range(10) if number % 2 == 0)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
That line says that &amp;lt;code&amp;gt;double_even_digits&amp;lt;/code&amp;gt; is every even number between 0 and 10 multiplied by two. Simple enough, right? If we wanted to use all of the numbers, not just the even ones, we could simply remove the if statement at the end of the expression.&lt;br /&gt;
&lt;br /&gt;
Here's the thing, though: if you were to print &amp;lt;code&amp;gt;double_even_digits&amp;lt;/code&amp;gt;, instead of a nice bunch of numbers, you'd get something that looks like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&amp;lt;generator object &amp;lt;genexpr&amp;gt;&amp;lt;code&amp;gt;at 0x107fc92b0&amp;gt;&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
That's because generators are lazy! They don't generate their values until those values are needed, and they discard values once they're no longer needed. As a result, '''you can only iterate over a generator once'''. In this case, you can't print out the whole generator, because it hasn't generated all the values yet. You can, however, iterate over the generator, and print its values one at a time, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
for number in double_even_digits:&lt;br /&gt;
    print(number)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
You can also make a list out of the generator, which will go through all the items in the generator and put them in a list, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
even_number_list = list(double_even_digits)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
That's actually a great segue to the second topic of this section: comprehensions. A comprehension is just a prettier way to make lists, sets, and dicts out of a generator expressions.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
# If you want a list:&lt;br /&gt;
list(i for i in range(10) if i % 2 == 0) # Don't do this&lt;br /&gt;
[i for i in range(10) if i % 2 == 0] # Use a list comprehension instead!&lt;br /&gt;
&lt;br /&gt;
# If you want a set:&lt;br /&gt;
set(i for i in range(10) if i % 2 == 0) # Don't do this&lt;br /&gt;
{i for i in range(10) if i % 2 == 0} # Use a set comprehension instead!&lt;br /&gt;
&lt;br /&gt;
# If you want a dict:&lt;br /&gt;
dict((i, i + 1) for i in range(10) if i % 2 == 0) # Don't do this&lt;br /&gt;
{i : i + 1 for i in range(10) if i % 2 == 0} # Use a dict comprehension instead!&lt;br /&gt;
&lt;br /&gt;
# If you want a tuple:&lt;br /&gt;
tuple(i for i in range(10) if i % 2 == 0) # Unfortunately, there's no better way to do this&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
In general, generators and comprehensions should be used whenever possible - they're the fastest and easiest way to build collections. If you ever see yourself writing code like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
# BAD PRACTICE! DO NOT USE!&lt;br /&gt;
digits = []&lt;br /&gt;
for digit in range(10):&lt;br /&gt;
    digits.append(digit)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Don't do it! Instead, use a generator expression or comprehension, as appropriate. A good way to decide whether a generator expression or comprehension is better for this situation is that, if you're just going to be iterating over your collection once, you should use an generator expression. If not, use a comprehension.&lt;br /&gt;
&lt;br /&gt;
=== Sorting ===&lt;br /&gt;
&lt;br /&gt;
Sorting in Python is frequently performed using the &amp;lt;code&amp;gt;sorted&amp;lt;/code&amp;gt; function, which takes two arguments: an iterable (anything you can do a for-loop over, including lists and tuples) and a function used to evaluate each item. If the function is omitted, Python will try to sort the lists by value.&lt;br /&gt;
&lt;br /&gt;
The following example demonstrates using an inline function, which Python calls a ''lambda''.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = ['apple', 'banana', 'cherry', 'date']&lt;br /&gt;
&lt;br /&gt;
# sort the fruits by string length&lt;br /&gt;
new_fruits = sorted(fruits, key=lambda v: len(v) // 2)&lt;br /&gt;
&lt;br /&gt;
print(new_fruits) # ['date', 'apple', 'banana', 'cherry']&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
Alternatively, you can sort a &amp;lt;code&amp;gt;list&amp;lt;/code&amp;gt; using the &amp;lt;code&amp;gt;.sort&amp;lt;/code&amp;gt; method. This is faster than calling &amp;lt;code&amp;gt;sorted&amp;lt;/code&amp;gt;, but it modifies the list in-place and returns &amp;lt;code&amp;gt;None&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
fruits = ['apple', 'banana', 'cherry', 'date']&lt;br /&gt;
fruits.sort()&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
=== Import ===&lt;br /&gt;
&lt;br /&gt;
If you want to use functions from other libraries (including ones that you install using pip), use &amp;lt;code&amp;gt;import&amp;lt;/code&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
import time&lt;br /&gt;
&lt;br /&gt;
current_time = time.localtime()&lt;br /&gt;
print(time.strftime('%a, %d %b %Y %H:%M:%S', current_time))&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
If you want to pull the functions out of their namespace, you can use &amp;lt;code&amp;gt;from ___ import ___&amp;lt;/code&amp;gt; syntax:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
from time import localtime, strftime&lt;br /&gt;
&lt;br /&gt;
current_time = localtime()&lt;br /&gt;
print(strftime('%a, %d %b %Y %H:%M:%S', current_time))&lt;br /&gt;
&lt;br /&gt;
# Be aware that this technique, although convenient, may cause unexpected behavior if the function names that you're pulling out of the namespace are already used for other purposes in Python.&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
=== File I/O ===&lt;br /&gt;
&lt;br /&gt;
You can read an entire file into a variable like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
f = open(&amp;quot;example.txt&amp;quot;)&lt;br /&gt;
file_contents = f.read()&lt;br /&gt;
&lt;br /&gt;
f.close() # free up memory when we're finished with the file&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
A better option is to use a with-block, which handles opening and closing the file for you automatically:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
with open(&amp;quot;example.txt&amp;quot;) as f:&lt;br /&gt;
    file_contents = f.read()&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
You can read a file line-by-line like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
with open(&amp;quot;example.txt&amp;quot;) as f:&lt;br /&gt;
    for line in f:&lt;br /&gt;
        print(&amp;quot;Read line: %s&amp;quot; % line.rstrip())&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
You can write to a file like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
with open(&amp;quot;example.txt&amp;quot;, &amp;quot;w&amp;quot;) as f:&lt;br /&gt;
    f.write(&amp;quot;Hello\nWorld\n&amp;quot;)&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
=== Command-Line Arguments ===&lt;br /&gt;
&lt;br /&gt;
Command line arguments are accessible in the variable &amp;lt;code&amp;gt;sys.argv&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
The following example shows a program that expects a filename as its argument, and it prints a usage message if the argument is not present ([https://stackoverflow.com/questions/983201/python-and-sys-argv source]).&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
import sys, os&lt;br /&gt;
&lt;br /&gt;
if len(sys.argv) &amp;lt; 2:&lt;br /&gt;
    sys.exit(&amp;quot;Usage: %s filename&amp;quot; % sys.argv[0])&lt;br /&gt;
&lt;br /&gt;
filename = sys.argv[1]&lt;br /&gt;
&lt;br /&gt;
if not os.path.exists(filename):&lt;br /&gt;
    sys.exit(&amp;quot;Error: File '%s' not found&amp;quot; % sys.argv[1])&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
=== Object-Oriented Programming ===&lt;br /&gt;
&lt;br /&gt;
You can define and use a class like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
class Food:&lt;br /&gt;
    # constructor:&lt;br /&gt;
    def __init__(self, name):&lt;br /&gt;
        self.name = name&lt;br /&gt;
    &lt;br /&gt;
    def format_name(self):&lt;br /&gt;
        return &amp;quot;Gotta love to eat &amp;quot; + self.name&lt;br /&gt;
&lt;br /&gt;
class Fruit(Food):&lt;br /&gt;
    def format_name(self):&lt;br /&gt;
        return Food.format_name(self) + &amp;quot; (fruit)&amp;quot;&lt;br /&gt;
&lt;br /&gt;
fruit = Fruit(&amp;quot;Cherry&amp;quot;)&lt;br /&gt;
print(fruit.format_name())&lt;br /&gt;
print(Food.get_definition())&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
This is the same example as in [[PHP#Object-Oriented_Programming|the PHP guide]].&lt;br /&gt;
&lt;br /&gt;
Some things to notice:&lt;br /&gt;
&lt;br /&gt;
* Instance methods ''always'' take &amp;lt;code&amp;gt;self&amp;lt;/code&amp;gt; as their first argument, followed by any number of additional parameters. This can be misleading for programmers familiar with other languages, because the number of arguments you feed to the method is actually ''one less than'' the number of declared parameters. Whenever you call a method on a class instance, that instance is implicitly fed into the explicitly-declared &amp;lt;code&amp;gt;self&amp;lt;/code&amp;gt; parameter of the method.&lt;br /&gt;
*: Note that the &amp;lt;code&amp;gt;self&amp;lt;/code&amp;gt; variable has the same purpose as the &amp;lt;code&amp;gt;this&amp;lt;/code&amp;gt; variable in languages like PHP, Java, JavaScript, and C++.&lt;br /&gt;
*There is no need for a &amp;lt;code&amp;gt;new&amp;lt;/code&amp;gt; keyword in Python.&lt;br /&gt;
&lt;br /&gt;
= Footnotes =&lt;br /&gt;
# {{note|interpreted}}This is an oversimplification. If you're interested, here's a quick explanation of how: In CPython (the reference implementation of Python) programs are compiled to bytecode, an intermediate representation, which is then interpreted.&lt;br /&gt;
[[Category:Module 4]]&lt;/div&gt;</summary>
		<author><name>Alex</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Module_3&amp;diff=2510</id>
		<title>Module 3</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Module_3&amp;diff=2510"/>
		<updated>2018-02-15T00:02:24Z</updated>

		<summary type="html">&lt;p&gt;Alex: /* Grading */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;__NOTOC__&lt;br /&gt;
In Module 3, you will learn about MySQL, a web application database.&lt;br /&gt;
&lt;br /&gt;
This article contains your assignments for Module 3.&lt;br /&gt;
&lt;br /&gt;
== Reading ==&lt;br /&gt;
&lt;br /&gt;
The following articles on the online class wiki textbook contain information that will help you complete the assignments.&lt;br /&gt;
&lt;br /&gt;
* [[Introduction to MySQL]]&lt;br /&gt;
* [[MySQL Schema and State]]&lt;br /&gt;
* [[PHP and MySQL]]&lt;br /&gt;
* [[Web Application Security, Part 2]]&lt;br /&gt;
&lt;br /&gt;
== Individual Assignments ==&lt;br /&gt;
&lt;br /&gt;
You will create a simple grades database containing four tables.&lt;br /&gt;
&lt;br /&gt;
'''IMPORTANT:''' The individual assignment is to be done by writing queries by hand.  (You can use phpMyAdmin to run the queries, but '''do not let phpMyAdmin write your queries for you!''')  Writing your own queries gives you a greater understanding of the underlying mechanisms and databases in general.  Additionally, having SQL knowledge and experience is a very marketable trait.&lt;br /&gt;
&lt;br /&gt;
=== Install MySQL and phpMyAdmin ===&lt;br /&gt;
&lt;br /&gt;
Before you start, '''you need to install MySQL''' on your EC2 instance.  You may also install phpMyAdmin, a web frontend to MySQL, if you choose to do so.&lt;br /&gt;
&lt;br /&gt;
=== Set Up a Database ===&lt;br /&gt;
&lt;br /&gt;
You may find the following article to be very helpful: [[Introduction to MySQL]]&lt;br /&gt;
&lt;br /&gt;
# Create a database named '''wustl''' &lt;br /&gt;
# Create a user named '''wustl_inst''' and give them the password '''wustl_pass'''&lt;br /&gt;
&lt;br /&gt;
=== Create Tables ===&lt;br /&gt;
&lt;br /&gt;
You may find the following article to be very helpful: [[MySQL Schema and State]]&lt;br /&gt;
&lt;br /&gt;
When creating tables, keep the following items in mind:&lt;br /&gt;
&lt;br /&gt;
* You should create all tables such that they use the InnoDB storage engine, since we wish to make use of its support of foreign keys. In other database engines, foreign key constraints are not enforced.  (If you mess up, you can use ALTER TABLE to change the storage engine.)&lt;br /&gt;
* Where it is appropriate, you should take advantage of the ability to define fields NOT NULL so that you do not inadvertently insert incomplete data for a row.&lt;br /&gt;
&lt;br /&gt;
Create the following tables:&lt;br /&gt;
&lt;br /&gt;
# Create a table named '''students''' with the following fields:&lt;br /&gt;
#* '''id''' of an appropriately-sized unsigned integer type (we will never need to process more than a million students)&lt;br /&gt;
#* '''first_name''' of type '''VARCHAR(50)'''&lt;br /&gt;
#* '''last_name''' of type '''VARCHAR(50)'''&lt;br /&gt;
#* '''email_address''' of type '''VARCHAR(50)'''&lt;br /&gt;
#: The primary key should be on the '''id''' field.&lt;br /&gt;
# Create a table named '''departments''' with the following fields:&lt;br /&gt;
#* '''school_code''' of type '''ENUM''' (e.g. &amp;quot;L&amp;quot; for ArtSci and &amp;quot;E&amp;quot; for Engineering).  The options are as follows:&lt;br /&gt;
#*: 'L', 'B', 'A', 'F', 'E', 'T', 'I', 'W', 'S', 'U', 'M'&lt;br /&gt;
#* '''dept_id''' of an appropriately-sized unsigned integer type (in the foreseeable future there will never be more than 200 departments in a school)&lt;br /&gt;
#* '''abbreviation''' of type '''VARCHAR(9)''' (e.g. CSE, ChemE, etc)&lt;br /&gt;
#* '''dept_name''' of type '''VARCHAR(200)''' (e.g. Computer Science and Engineering)&lt;br /&gt;
#: The primary key should be on two fields: '''school_code''' and '''dept_id'''&lt;br /&gt;
#: '''Note:''' Why not just use the department ID for the primary key? The ID numbers are sometimes reused across schools. For instance, department 33 in The College of Arts and Sciences is Psychology while department 33 in The School of Engineering and Applied Sciences is Energy, Environmental and Chemical Engineering. Thus we must also include the school code to differentiate them  such that the record for  E33 is distinct from that of L33.&lt;br /&gt;
# Create a table named '''courses''' with the following fields:&lt;br /&gt;
#* '''school_code''' of type '''ENUM'''&lt;br /&gt;
#*: This should have the same letters in the same order as the '''school_code''' '''ENUM''' field in the '''departments''' table.&lt;br /&gt;
#* '''dept_id''' of the same size of integer as in the '''departments''' table&lt;br /&gt;
#* '''course_code''' of type '''CHAR(5)''' (this will hold course codes; e.g., '330S', '131', '2960')&lt;br /&gt;
#* '''name''' of type '''VARCHAR(150)'''&lt;br /&gt;
#: The appropriate fields in this table should make a foreign key reference to the corresponding fields in '''department'''.&lt;br /&gt;
#: In addition, it is up to you to determine the field(s) for the primary key.&lt;br /&gt;
#: '''Note:''' If you are unsure which fields to make the foreign keys and feel the need to beg your friends or the TAs to give you the answer, bang your head on your desk whilst repeating &amp;quot;I WILL EXERCISE REASON AND COMMON SENSE AND I WILL CURTAIL MY DESIRE TO BLINDLY FOLLOW DIRECTIONS&amp;quot;&lt;br /&gt;
#: ''Disclaimer: don't actually bang your head on your desk, the resulting head trauma may in fact make it harder for you to determine which fields should have associated foreign keys.''&lt;br /&gt;
# Create a table named '''grades''' with the following fields:&lt;br /&gt;
#* '''pk_grade_ID''' of an appropriately-sized unsigned integer type (should be larger than the one you chose for the '''students''' table). There will never be more than 1,000 grades per student.&lt;br /&gt;
#*: You should declare this field to be '''auto_increment''' and make it the primary key.&lt;br /&gt;
#*: This is called a ''surrogate key'' as opposed to a ''natural key'' because it doesn't arise &amp;quot;naturally&amp;quot; from the data; that is to say that it is not derived from application data. The use of surrogate keys vs. natural keys is a polemic issue amongst database designers.  For a decently unbiased take on the issue, see this page: http://www.agiledata.org/essays/keys.html#Comparison&lt;br /&gt;
#*: '''Food for thought:''' Aside from simply exposing you to the concept, can you think of any reasons why a surrogate key might be preferable for this table?  Alternatively, what attributes, if any, could you use as a natural key, and what might be the drawbacks of doing so?&lt;br /&gt;
#* '''student_id''' of the same integer (unsigned) type that you chose in the '''students''' table&lt;br /&gt;
#* '''grade''' of type '''decimal(5,2)'''&lt;br /&gt;
#* '''school_code''' of type '''ENUM'''&lt;br /&gt;
#*: Can you guess what entries to use for the enum?&lt;br /&gt;
#* '''dept_id''' of the same integer type that you've used for this field in other tables&lt;br /&gt;
#* '''course_code''' of the same type you chose for the course code in the '''courses''' table&lt;br /&gt;
#: The '''grades''' table should have foreign keys to both the '''students''' table and the '''courses''' table.&lt;br /&gt;
&lt;br /&gt;
=== Populate Tables ===&lt;br /&gt;
&lt;br /&gt;
Now, populate the tables by downloading the text files given below and loading them into the appropriate tables.&lt;br /&gt;
&lt;br /&gt;
'''Note:''' Do not insert all the values manually; instead, use the MySQL's ability to load in data from text files.&lt;br /&gt;
&lt;br /&gt;
You may find the following article to be very helpful: [[MySQL Schema and State]]&lt;br /&gt;
&lt;br /&gt;
The files containing the data are:&lt;br /&gt;
* students: http://classes.engineering.wustl.edu/cse330/content/students_data.txt&lt;br /&gt;
* courses: http://classes.engineering.wustl.edu/cse330/content/courses.txt&lt;br /&gt;
* departments: http://classes.engineering.wustl.edu/cse330/content/departments_data.txt&lt;br /&gt;
* grades: http://classes.engineering.wustl.edu/cse330/content/grades_data.txt&lt;br /&gt;
&lt;br /&gt;
=== Insert More Data ===&lt;br /&gt;
&lt;br /&gt;
Insert the following data into the tables that you have created and populated:&lt;br /&gt;
&lt;br /&gt;
# Insert entries for CSE 330S, CSE 131, and CSE 260M.&lt;br /&gt;
#: ''If you don't know CSE's department code, how can you find out using the tables in the database?''&lt;br /&gt;
# Insert the grades given for the students named below. &lt;br /&gt;
#* '''Ben Harper'''&lt;br /&gt;
#** E-mail: '''bharper@ffym.com'''&lt;br /&gt;
#** Student ID: '''88'''&lt;br /&gt;
#** Grades:&lt;br /&gt;
#*** 35.5 in CSE 330S&lt;br /&gt;
#*** 0 in CSE 131&lt;br /&gt;
#*** 95 in CSE 260M&lt;br /&gt;
#* '''Matt Freeman'''&lt;br /&gt;
#** E-mail: '''mfreeman@kickinbassist.net'''&lt;br /&gt;
#** Student ID: '''202'''&lt;br /&gt;
#** Grades:&lt;br /&gt;
#*** 100 in CSE 330S&lt;br /&gt;
#*** 90.5 in CSE 131&lt;br /&gt;
#*** 94.8 in CSE 260M&lt;br /&gt;
#* '''Marc Roberge'''&lt;br /&gt;
#** E-mail: '''mroberge@ofarevolution.us'''&lt;br /&gt;
#** Student ID: '''115'''&lt;br /&gt;
#** Grades:&lt;br /&gt;
#*** 75 in CSE 330S&lt;br /&gt;
#*** 37 in CSE 131&lt;br /&gt;
#*** 45.5 in CSE 260M&lt;br /&gt;
&lt;br /&gt;
=== Querying Your Database ===&lt;br /&gt;
&lt;br /&gt;
Now that you have a fully-functional, populated database, let's do some queries on it!&lt;br /&gt;
&lt;br /&gt;
Please Running the following &amp;lt;code&amp;gt;SELECT&amp;lt;/code&amp;gt; queries, then copy the output to a text file of the form &amp;lt;code&amp;gt;query1.txt&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;query2.txt&amp;lt;/code&amp;gt;, and so on, and commit them with the rest of your repository (be sure to include your query command and the entire response, including the number of results found). For each query, only the requested columns should be present. You will receive 0 points for any query that includes additional columns.&lt;br /&gt;
&lt;br /&gt;
# Select the entire grades table.&lt;br /&gt;
# Select all fields describing the courses offered in the College of Arts &amp;amp; Sciences (school code &amp;lt;code&amp;gt;L&amp;lt;/code&amp;gt;).&lt;br /&gt;
# The names, student IDs, and CSE330 grades of all students who are in CSE330S.&lt;br /&gt;
#: '''Note:''' This query should involve joins.  You don't need to use any aggregation functions.&lt;br /&gt;
# The names, e-mails, and average grades of any student with an average below 50 so that the dean can send them an email notification that they are now on academic probation.&lt;br /&gt;
#: ''You should be able to do this in only one query, without making any temporary tables.  You will need to use aggregation functions and the &amp;lt;code&amp;gt;HAVING&amp;lt;/code&amp;gt; keyword.''&lt;br /&gt;
# An individual report card for Jack Johnson, consisting of only his student ID, e-mail address, and average grade.&lt;br /&gt;
#: ''Again, you should be able to do this in just one query, using the correct combination of aggregation functions and joins.''&lt;br /&gt;
#: '''Note:''' Your query must look for students with the name &amp;quot;Jack Johnson&amp;quot; instead of hard-coding the student ID.&lt;br /&gt;
&lt;br /&gt;
== Group Project ==&lt;br /&gt;
&lt;br /&gt;
You will work in pairs on this project.  You may work with the same partner from Module 2, or change to someone else.&lt;br /&gt;
&lt;br /&gt;
'''Important Reminder:''' frequently commit your work to your Git repository as a backup!&lt;br /&gt;
&lt;br /&gt;
=== Simple News Web Site ===&lt;br /&gt;
&lt;br /&gt;
'''Examples:'''&lt;br /&gt;
* http://digg.com/&lt;br /&gt;
* http://slashdot.org/&lt;br /&gt;
&lt;br /&gt;
You should use '''PHP''' unless you get permission to use another web technology from the instructor.  You may also use phpMyAdmin to help set up databases.&lt;br /&gt;
&lt;br /&gt;
You may find this wiki article helpful: [[PHP and MySQL]]&lt;br /&gt;
&lt;br /&gt;
==== Requirements ====&lt;br /&gt;
&lt;br /&gt;
* Users can register for accounts and then log in to the website.&lt;br /&gt;
* Accounts should have both a username and a ''secure'' password.  '''NEVER store plaintext passwords in a database!'''&lt;br /&gt;
*: For more information on password security, refer to [[Web Application Security, Part 2#Password Security|the Web Application Security guide]].&lt;br /&gt;
* Registered users can submit story commentary.&lt;br /&gt;
*: A link can be associated with each story, and they should be stored in a separate database field from the story&lt;br /&gt;
* Registered users can comment on any story.&lt;br /&gt;
* Unregistered users can only view stories and comments.&lt;br /&gt;
* Registered users can edit and delete their stories and comments.&lt;br /&gt;
* All data must be kept in a MySQL database (user information, stories, comments, and links).&lt;br /&gt;
* Creative Portion&lt;br /&gt;
&lt;br /&gt;
=== Web Security and Validation ===&lt;br /&gt;
&lt;br /&gt;
No application is finished until much thought is put into web security and best practice.  Throughout this course, we heavily emphasize the dogma of [http://coderesponsibly.org/ responsible] coding.&lt;br /&gt;
&lt;br /&gt;
Read this week's Web Application Security guide: [[Web Application Security, Part 2]].  In particular, your project needs to:&lt;br /&gt;
&lt;br /&gt;
* '''Your application needs to be secure against SQL injection attacks'''. If you are using prepared queries, you should already be safe on this front.&lt;br /&gt;
* '''Your passwords need to be securely hashed salted''' to prevent rainbow table attacks.&lt;br /&gt;
* '''You should pass tokens in forms''' to prevent CSRF attacks.&lt;br /&gt;
* '''You should check all preconditions on the server side''' to prevent Abuse of Functionality attacks.&lt;br /&gt;
&lt;br /&gt;
You shouldn't forget the practices you learned last week:&lt;br /&gt;
&lt;br /&gt;
* '''Your page should validate''' with no errors through the W3C validator.&lt;br /&gt;
* '''Filter Input and Escape Output''', but not the other way around.&lt;br /&gt;
&lt;br /&gt;
== Grading ==&lt;br /&gt;
&lt;br /&gt;
We will be grading the following aspects of your work.  There are 100 points total.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Assignments (including code) must be committed to Bitbucket by the end of class on the due date (commit early and often). Failing to commit by the end of class on the due date will result in a 0. ''' &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''If you do not include a link to your group portion running on your instance in your group portion README.md, you will receive a 0 for the group portion.''' &lt;br /&gt;
________&lt;br /&gt;
&lt;br /&gt;
# '''MySQL Queries (25 Points):'''&lt;br /&gt;
#* A MySQL server is running on your instance (2 points)&lt;br /&gt;
#* Tables' fields, including data types and foreign keys, are correct (8 points)&lt;br /&gt;
#*: ''Note: To demonstrate the structure of your tables, you should commit a text file containing the output of the &amp;lt;code&amp;gt;SHOW CREATE TABLE&amp;lt;/code&amp;gt; command '''for each table.''' Each table's file should have a name of the form &amp;lt;code&amp;gt;tablename.sql&amp;lt;/code&amp;gt; (e.g. &amp;lt;code&amp;gt;students.sql&amp;lt;/code&amp;gt;).''&lt;br /&gt;
#* The output of each of the five queries is correct. (3 points each)&lt;br /&gt;
#*: ''Note: To demonstrate the output of your queries, text files containing the 'entire' result (including the query and number of records found) of running each query should committed to BitBucket. The file for query 1 should be named &amp;lt;code&amp;gt;query1.txt&amp;lt;/code&amp;gt;, the file for query 2 should be named &amp;lt;code&amp;gt;query2.txt&amp;lt;/code&amp;gt;, and so on.''&lt;br /&gt;
# '''News Site (60 Points):'''&lt;br /&gt;
#* '''''User Management (20 Points):'''''&lt;br /&gt;
#** A session is created when a user logs in (3 points)&lt;br /&gt;
#** New users can register (3 points)&lt;br /&gt;
#** Passwords are hashed, salted, and checked securely (3 points)&lt;br /&gt;
#**: ''Note: You will receive 0 points for this section if you use the &amp;lt;code&amp;gt;==&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;===&amp;lt;/code&amp;gt; operators to compare password hashes, or if you use the &amp;lt;code&amp;gt;crypt&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;md5&amp;lt;/code&amp;gt; functions at any point.''&lt;br /&gt;
#** Users can log out (3 points)&lt;br /&gt;
#** A user can edit and delete his/her own stories and comments but cannot edit or delete the stories or comments of another user (8 points)&lt;br /&gt;
#* '''''Story and Comment Management (20 Points):'''''&lt;br /&gt;
#** Relational database is configured with correct data types and foreign keys (4 points)&lt;br /&gt;
#*: ''Note: To demonstrate the structure of your database, you should commit a 'single' text file containing the output of the &amp;lt;code&amp;gt;SHOW CREATE TABLE&amp;lt;/code&amp;gt; command '''for all tables in your database,''' called &amp;lt;code&amp;gt;tables.sql&amp;lt;/code&amp;gt;. This one file should contain the output for all of your tables.&lt;br /&gt;
#** Stories can be posted (3 points)&lt;br /&gt;
#** A link can be associated with each story, and is stored in a separate database field from the story (3 points)&lt;br /&gt;
#** Comments can be posted in association with a story (4 points)&lt;br /&gt;
#** Stories can be edited and deleted (3 points)&lt;br /&gt;
#** Comments can be edited and deleted (3 points)&lt;br /&gt;
#**: ''Note: Although there are only 6 points allocated for editing/deleting in this section, there are 8 more points at stake in the User Management section that cannot be earned unless editing/deleting is implemented.  Implementing editing but not deleting, or vice-versa, will result in earning half the points.''&lt;br /&gt;
#* '''''Best Practices (15 Points):'''''&lt;br /&gt;
#** Code is well formatted and easy to read, with proper commenting (3 points)&lt;br /&gt;
#** Safe from SQL Injection attacks (2 points)&lt;br /&gt;
#** Site follows the FIEO philosophy (3 points)&lt;br /&gt;
#** All pages pass the W3C HTML and CSS validators (2 points)&lt;br /&gt;
#** CSRF tokens are passed when creating, editing, and deleting comments and stories (5 points)&lt;br /&gt;
#* '''''Usability (5 Points):'''''&lt;br /&gt;
#** Site is intuitive to use and navigate (4 points)&lt;br /&gt;
#** Site is visually appealing (1 point)&lt;br /&gt;
# '''Creative Portion (15 Points)''' (see below)&lt;br /&gt;
#* '''''Make sure you have a README.md file in your group repo with the following:'''''&lt;br /&gt;
#** Names and Student IDs of all the group members&lt;br /&gt;
#** A link to your homepage of the site&lt;br /&gt;
#** A brief description of what you did for your creative portion&lt;br /&gt;
#** Any additional login details needed for the TA&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 3]]&lt;br /&gt;
[[Category:Modules]]&lt;/div&gt;</summary>
		<author><name>Alex</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Module_3&amp;diff=2509</id>
		<title>Module 3</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Module_3&amp;diff=2509"/>
		<updated>2018-02-15T00:02:09Z</updated>

		<summary type="html">&lt;p&gt;Alex: /* Grading */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;__NOTOC__&lt;br /&gt;
In Module 3, you will learn about MySQL, a web application database.&lt;br /&gt;
&lt;br /&gt;
This article contains your assignments for Module 3.&lt;br /&gt;
&lt;br /&gt;
== Reading ==&lt;br /&gt;
&lt;br /&gt;
The following articles on the online class wiki textbook contain information that will help you complete the assignments.&lt;br /&gt;
&lt;br /&gt;
* [[Introduction to MySQL]]&lt;br /&gt;
* [[MySQL Schema and State]]&lt;br /&gt;
* [[PHP and MySQL]]&lt;br /&gt;
* [[Web Application Security, Part 2]]&lt;br /&gt;
&lt;br /&gt;
== Individual Assignments ==&lt;br /&gt;
&lt;br /&gt;
You will create a simple grades database containing four tables.&lt;br /&gt;
&lt;br /&gt;
'''IMPORTANT:''' The individual assignment is to be done by writing queries by hand.  (You can use phpMyAdmin to run the queries, but '''do not let phpMyAdmin write your queries for you!''')  Writing your own queries gives you a greater understanding of the underlying mechanisms and databases in general.  Additionally, having SQL knowledge and experience is a very marketable trait.&lt;br /&gt;
&lt;br /&gt;
=== Install MySQL and phpMyAdmin ===&lt;br /&gt;
&lt;br /&gt;
Before you start, '''you need to install MySQL''' on your EC2 instance.  You may also install phpMyAdmin, a web frontend to MySQL, if you choose to do so.&lt;br /&gt;
&lt;br /&gt;
=== Set Up a Database ===&lt;br /&gt;
&lt;br /&gt;
You may find the following article to be very helpful: [[Introduction to MySQL]]&lt;br /&gt;
&lt;br /&gt;
# Create a database named '''wustl''' &lt;br /&gt;
# Create a user named '''wustl_inst''' and give them the password '''wustl_pass'''&lt;br /&gt;
&lt;br /&gt;
=== Create Tables ===&lt;br /&gt;
&lt;br /&gt;
You may find the following article to be very helpful: [[MySQL Schema and State]]&lt;br /&gt;
&lt;br /&gt;
When creating tables, keep the following items in mind:&lt;br /&gt;
&lt;br /&gt;
* You should create all tables such that they use the InnoDB storage engine, since we wish to make use of its support of foreign keys. In other database engines, foreign key constraints are not enforced.  (If you mess up, you can use ALTER TABLE to change the storage engine.)&lt;br /&gt;
* Where it is appropriate, you should take advantage of the ability to define fields NOT NULL so that you do not inadvertently insert incomplete data for a row.&lt;br /&gt;
&lt;br /&gt;
Create the following tables:&lt;br /&gt;
&lt;br /&gt;
# Create a table named '''students''' with the following fields:&lt;br /&gt;
#* '''id''' of an appropriately-sized unsigned integer type (we will never need to process more than a million students)&lt;br /&gt;
#* '''first_name''' of type '''VARCHAR(50)'''&lt;br /&gt;
#* '''last_name''' of type '''VARCHAR(50)'''&lt;br /&gt;
#* '''email_address''' of type '''VARCHAR(50)'''&lt;br /&gt;
#: The primary key should be on the '''id''' field.&lt;br /&gt;
# Create a table named '''departments''' with the following fields:&lt;br /&gt;
#* '''school_code''' of type '''ENUM''' (e.g. &amp;quot;L&amp;quot; for ArtSci and &amp;quot;E&amp;quot; for Engineering).  The options are as follows:&lt;br /&gt;
#*: 'L', 'B', 'A', 'F', 'E', 'T', 'I', 'W', 'S', 'U', 'M'&lt;br /&gt;
#* '''dept_id''' of an appropriately-sized unsigned integer type (in the foreseeable future there will never be more than 200 departments in a school)&lt;br /&gt;
#* '''abbreviation''' of type '''VARCHAR(9)''' (e.g. CSE, ChemE, etc)&lt;br /&gt;
#* '''dept_name''' of type '''VARCHAR(200)''' (e.g. Computer Science and Engineering)&lt;br /&gt;
#: The primary key should be on two fields: '''school_code''' and '''dept_id'''&lt;br /&gt;
#: '''Note:''' Why not just use the department ID for the primary key? The ID numbers are sometimes reused across schools. For instance, department 33 in The College of Arts and Sciences is Psychology while department 33 in The School of Engineering and Applied Sciences is Energy, Environmental and Chemical Engineering. Thus we must also include the school code to differentiate them  such that the record for  E33 is distinct from that of L33.&lt;br /&gt;
# Create a table named '''courses''' with the following fields:&lt;br /&gt;
#* '''school_code''' of type '''ENUM'''&lt;br /&gt;
#*: This should have the same letters in the same order as the '''school_code''' '''ENUM''' field in the '''departments''' table.&lt;br /&gt;
#* '''dept_id''' of the same size of integer as in the '''departments''' table&lt;br /&gt;
#* '''course_code''' of type '''CHAR(5)''' (this will hold course codes; e.g., '330S', '131', '2960')&lt;br /&gt;
#* '''name''' of type '''VARCHAR(150)'''&lt;br /&gt;
#: The appropriate fields in this table should make a foreign key reference to the corresponding fields in '''department'''.&lt;br /&gt;
#: In addition, it is up to you to determine the field(s) for the primary key.&lt;br /&gt;
#: '''Note:''' If you are unsure which fields to make the foreign keys and feel the need to beg your friends or the TAs to give you the answer, bang your head on your desk whilst repeating &amp;quot;I WILL EXERCISE REASON AND COMMON SENSE AND I WILL CURTAIL MY DESIRE TO BLINDLY FOLLOW DIRECTIONS&amp;quot;&lt;br /&gt;
#: ''Disclaimer: don't actually bang your head on your desk, the resulting head trauma may in fact make it harder for you to determine which fields should have associated foreign keys.''&lt;br /&gt;
# Create a table named '''grades''' with the following fields:&lt;br /&gt;
#* '''pk_grade_ID''' of an appropriately-sized unsigned integer type (should be larger than the one you chose for the '''students''' table). There will never be more than 1,000 grades per student.&lt;br /&gt;
#*: You should declare this field to be '''auto_increment''' and make it the primary key.&lt;br /&gt;
#*: This is called a ''surrogate key'' as opposed to a ''natural key'' because it doesn't arise &amp;quot;naturally&amp;quot; from the data; that is to say that it is not derived from application data. The use of surrogate keys vs. natural keys is a polemic issue amongst database designers.  For a decently unbiased take on the issue, see this page: http://www.agiledata.org/essays/keys.html#Comparison&lt;br /&gt;
#*: '''Food for thought:''' Aside from simply exposing you to the concept, can you think of any reasons why a surrogate key might be preferable for this table?  Alternatively, what attributes, if any, could you use as a natural key, and what might be the drawbacks of doing so?&lt;br /&gt;
#* '''student_id''' of the same integer (unsigned) type that you chose in the '''students''' table&lt;br /&gt;
#* '''grade''' of type '''decimal(5,2)'''&lt;br /&gt;
#* '''school_code''' of type '''ENUM'''&lt;br /&gt;
#*: Can you guess what entries to use for the enum?&lt;br /&gt;
#* '''dept_id''' of the same integer type that you've used for this field in other tables&lt;br /&gt;
#* '''course_code''' of the same type you chose for the course code in the '''courses''' table&lt;br /&gt;
#: The '''grades''' table should have foreign keys to both the '''students''' table and the '''courses''' table.&lt;br /&gt;
&lt;br /&gt;
=== Populate Tables ===&lt;br /&gt;
&lt;br /&gt;
Now, populate the tables by downloading the text files given below and loading them into the appropriate tables.&lt;br /&gt;
&lt;br /&gt;
'''Note:''' Do not insert all the values manually; instead, use the MySQL's ability to load in data from text files.&lt;br /&gt;
&lt;br /&gt;
You may find the following article to be very helpful: [[MySQL Schema and State]]&lt;br /&gt;
&lt;br /&gt;
The files containing the data are:&lt;br /&gt;
* students: http://classes.engineering.wustl.edu/cse330/content/students_data.txt&lt;br /&gt;
* courses: http://classes.engineering.wustl.edu/cse330/content/courses.txt&lt;br /&gt;
* departments: http://classes.engineering.wustl.edu/cse330/content/departments_data.txt&lt;br /&gt;
* grades: http://classes.engineering.wustl.edu/cse330/content/grades_data.txt&lt;br /&gt;
&lt;br /&gt;
=== Insert More Data ===&lt;br /&gt;
&lt;br /&gt;
Insert the following data into the tables that you have created and populated:&lt;br /&gt;
&lt;br /&gt;
# Insert entries for CSE 330S, CSE 131, and CSE 260M.&lt;br /&gt;
#: ''If you don't know CSE's department code, how can you find out using the tables in the database?''&lt;br /&gt;
# Insert the grades given for the students named below. &lt;br /&gt;
#* '''Ben Harper'''&lt;br /&gt;
#** E-mail: '''bharper@ffym.com'''&lt;br /&gt;
#** Student ID: '''88'''&lt;br /&gt;
#** Grades:&lt;br /&gt;
#*** 35.5 in CSE 330S&lt;br /&gt;
#*** 0 in CSE 131&lt;br /&gt;
#*** 95 in CSE 260M&lt;br /&gt;
#* '''Matt Freeman'''&lt;br /&gt;
#** E-mail: '''mfreeman@kickinbassist.net'''&lt;br /&gt;
#** Student ID: '''202'''&lt;br /&gt;
#** Grades:&lt;br /&gt;
#*** 100 in CSE 330S&lt;br /&gt;
#*** 90.5 in CSE 131&lt;br /&gt;
#*** 94.8 in CSE 260M&lt;br /&gt;
#* '''Marc Roberge'''&lt;br /&gt;
#** E-mail: '''mroberge@ofarevolution.us'''&lt;br /&gt;
#** Student ID: '''115'''&lt;br /&gt;
#** Grades:&lt;br /&gt;
#*** 75 in CSE 330S&lt;br /&gt;
#*** 37 in CSE 131&lt;br /&gt;
#*** 45.5 in CSE 260M&lt;br /&gt;
&lt;br /&gt;
=== Querying Your Database ===&lt;br /&gt;
&lt;br /&gt;
Now that you have a fully-functional, populated database, let's do some queries on it!&lt;br /&gt;
&lt;br /&gt;
Please Running the following &amp;lt;code&amp;gt;SELECT&amp;lt;/code&amp;gt; queries, then copy the output to a text file of the form &amp;lt;code&amp;gt;query1.txt&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;query2.txt&amp;lt;/code&amp;gt;, and so on, and commit them with the rest of your repository (be sure to include your query command and the entire response, including the number of results found). For each query, only the requested columns should be present. You will receive 0 points for any query that includes additional columns.&lt;br /&gt;
&lt;br /&gt;
# Select the entire grades table.&lt;br /&gt;
# Select all fields describing the courses offered in the College of Arts &amp;amp; Sciences (school code &amp;lt;code&amp;gt;L&amp;lt;/code&amp;gt;).&lt;br /&gt;
# The names, student IDs, and CSE330 grades of all students who are in CSE330S.&lt;br /&gt;
#: '''Note:''' This query should involve joins.  You don't need to use any aggregation functions.&lt;br /&gt;
# The names, e-mails, and average grades of any student with an average below 50 so that the dean can send them an email notification that they are now on academic probation.&lt;br /&gt;
#: ''You should be able to do this in only one query, without making any temporary tables.  You will need to use aggregation functions and the &amp;lt;code&amp;gt;HAVING&amp;lt;/code&amp;gt; keyword.''&lt;br /&gt;
# An individual report card for Jack Johnson, consisting of only his student ID, e-mail address, and average grade.&lt;br /&gt;
#: ''Again, you should be able to do this in just one query, using the correct combination of aggregation functions and joins.''&lt;br /&gt;
#: '''Note:''' Your query must look for students with the name &amp;quot;Jack Johnson&amp;quot; instead of hard-coding the student ID.&lt;br /&gt;
&lt;br /&gt;
== Group Project ==&lt;br /&gt;
&lt;br /&gt;
You will work in pairs on this project.  You may work with the same partner from Module 2, or change to someone else.&lt;br /&gt;
&lt;br /&gt;
'''Important Reminder:''' frequently commit your work to your Git repository as a backup!&lt;br /&gt;
&lt;br /&gt;
=== Simple News Web Site ===&lt;br /&gt;
&lt;br /&gt;
'''Examples:'''&lt;br /&gt;
* http://digg.com/&lt;br /&gt;
* http://slashdot.org/&lt;br /&gt;
&lt;br /&gt;
You should use '''PHP''' unless you get permission to use another web technology from the instructor.  You may also use phpMyAdmin to help set up databases.&lt;br /&gt;
&lt;br /&gt;
You may find this wiki article helpful: [[PHP and MySQL]]&lt;br /&gt;
&lt;br /&gt;
==== Requirements ====&lt;br /&gt;
&lt;br /&gt;
* Users can register for accounts and then log in to the website.&lt;br /&gt;
* Accounts should have both a username and a ''secure'' password.  '''NEVER store plaintext passwords in a database!'''&lt;br /&gt;
*: For more information on password security, refer to [[Web Application Security, Part 2#Password Security|the Web Application Security guide]].&lt;br /&gt;
* Registered users can submit story commentary.&lt;br /&gt;
*: A link can be associated with each story, and they should be stored in a separate database field from the story&lt;br /&gt;
* Registered users can comment on any story.&lt;br /&gt;
* Unregistered users can only view stories and comments.&lt;br /&gt;
* Registered users can edit and delete their stories and comments.&lt;br /&gt;
* All data must be kept in a MySQL database (user information, stories, comments, and links).&lt;br /&gt;
* Creative Portion&lt;br /&gt;
&lt;br /&gt;
=== Web Security and Validation ===&lt;br /&gt;
&lt;br /&gt;
No application is finished until much thought is put into web security and best practice.  Throughout this course, we heavily emphasize the dogma of [http://coderesponsibly.org/ responsible] coding.&lt;br /&gt;
&lt;br /&gt;
Read this week's Web Application Security guide: [[Web Application Security, Part 2]].  In particular, your project needs to:&lt;br /&gt;
&lt;br /&gt;
* '''Your application needs to be secure against SQL injection attacks'''. If you are using prepared queries, you should already be safe on this front.&lt;br /&gt;
* '''Your passwords need to be securely hashed salted''' to prevent rainbow table attacks.&lt;br /&gt;
* '''You should pass tokens in forms''' to prevent CSRF attacks.&lt;br /&gt;
* '''You should check all preconditions on the server side''' to prevent Abuse of Functionality attacks.&lt;br /&gt;
&lt;br /&gt;
You shouldn't forget the practices you learned last week:&lt;br /&gt;
&lt;br /&gt;
* '''Your page should validate''' with no errors through the W3C validator.&lt;br /&gt;
* '''Filter Input and Escape Output''', but not the other way around.&lt;br /&gt;
&lt;br /&gt;
== Grading ==&lt;br /&gt;
&lt;br /&gt;
We will be grading the following aspects of your work.  There are 100 points total.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Assignments (including code) must be committed to Bitbucket by the end of class on the due date (commit early and often). Failing to commit by the end of class on the due date will result in a 0. ''' &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''If you do not include a link to your group portion running on your instance in your group portion README.md, you will receive a 0 for the group portion.''' &lt;br /&gt;
________&lt;br /&gt;
&lt;br /&gt;
# '''MySQL Queries (25 Points):'''&lt;br /&gt;
#* A MySQL server is running on your instance (2 points)&lt;br /&gt;
#* Tables' fields, including data types and foreign keys, are correct (8 points)&lt;br /&gt;
#*: ''Note: To demonstrate the structure of your tables, you should commit a file containing the output of the &amp;lt;code&amp;gt;SHOW CREATE TABLE&amp;lt;/code&amp;gt; command '''for each table.''' Each table's file should have a name of the form &amp;lt;code&amp;gt;tablename.sql&amp;lt;/code&amp;gt; (e.g. &amp;lt;code&amp;gt;students.sql&amp;lt;/code&amp;gt;).''&lt;br /&gt;
#* The output of each of the five queries is correct. (3 points each)&lt;br /&gt;
#*: ''Note: To demonstrate the output of your queries, text files containing the 'entire' result (including the query and number of records found) of running each query should committed to BitBucket. The file for query 1 should be named &amp;lt;code&amp;gt;query1.txt&amp;lt;/code&amp;gt;, the file for query 2 should be named &amp;lt;code&amp;gt;query2.txt&amp;lt;/code&amp;gt;, and so on.''&lt;br /&gt;
# '''News Site (60 Points):'''&lt;br /&gt;
#* '''''User Management (20 Points):'''''&lt;br /&gt;
#** A session is created when a user logs in (3 points)&lt;br /&gt;
#** New users can register (3 points)&lt;br /&gt;
#** Passwords are hashed, salted, and checked securely (3 points)&lt;br /&gt;
#**: ''Note: You will receive 0 points for this section if you use the &amp;lt;code&amp;gt;==&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;===&amp;lt;/code&amp;gt; operators to compare password hashes, or if you use the &amp;lt;code&amp;gt;crypt&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;md5&amp;lt;/code&amp;gt; functions at any point.''&lt;br /&gt;
#** Users can log out (3 points)&lt;br /&gt;
#** A user can edit and delete his/her own stories and comments but cannot edit or delete the stories or comments of another user (8 points)&lt;br /&gt;
#* '''''Story and Comment Management (20 Points):'''''&lt;br /&gt;
#** Relational database is configured with correct data types and foreign keys (4 points)&lt;br /&gt;
#*: ''Note: To demonstrate the structure of your database, you should commit a 'single' text file containing the output of the &amp;lt;code&amp;gt;SHOW CREATE TABLE&amp;lt;/code&amp;gt; command '''for all tables in your database,''' called &amp;lt;code&amp;gt;tables.sql&amp;lt;/code&amp;gt;. This one file should contain the output for all of your tables.&lt;br /&gt;
#** Stories can be posted (3 points)&lt;br /&gt;
#** A link can be associated with each story, and is stored in a separate database field from the story (3 points)&lt;br /&gt;
#** Comments can be posted in association with a story (4 points)&lt;br /&gt;
#** Stories can be edited and deleted (3 points)&lt;br /&gt;
#** Comments can be edited and deleted (3 points)&lt;br /&gt;
#**: ''Note: Although there are only 6 points allocated for editing/deleting in this section, there are 8 more points at stake in the User Management section that cannot be earned unless editing/deleting is implemented.  Implementing editing but not deleting, or vice-versa, will result in earning half the points.''&lt;br /&gt;
#* '''''Best Practices (15 Points):'''''&lt;br /&gt;
#** Code is well formatted and easy to read, with proper commenting (3 points)&lt;br /&gt;
#** Safe from SQL Injection attacks (2 points)&lt;br /&gt;
#** Site follows the FIEO philosophy (3 points)&lt;br /&gt;
#** All pages pass the W3C HTML and CSS validators (2 points)&lt;br /&gt;
#** CSRF tokens are passed when creating, editing, and deleting comments and stories (5 points)&lt;br /&gt;
#* '''''Usability (5 Points):'''''&lt;br /&gt;
#** Site is intuitive to use and navigate (4 points)&lt;br /&gt;
#** Site is visually appealing (1 point)&lt;br /&gt;
# '''Creative Portion (15 Points)''' (see below)&lt;br /&gt;
#* '''''Make sure you have a README.md file in your group repo with the following:'''''&lt;br /&gt;
#** Names and Student IDs of all the group members&lt;br /&gt;
#** A link to your homepage of the site&lt;br /&gt;
#** A brief description of what you did for your creative portion&lt;br /&gt;
#** Any additional login details needed for the TA&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 3]]&lt;br /&gt;
[[Category:Modules]]&lt;/div&gt;</summary>
		<author><name>Alex</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Module_6&amp;diff=2508</id>
		<title>Module 6</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Module_6&amp;diff=2508"/>
		<updated>2018-02-12T17:45:08Z</updated>

		<summary type="html">&lt;p&gt;Alex: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;__NOTOC__ &lt;br /&gt;
Module 6 builds upon the JavaScript skills you learned in Module 5.&lt;br /&gt;
&lt;br /&gt;
== Reading ==&lt;br /&gt;
&lt;br /&gt;
The following articles on the online class wiki textbook contain information that will help you complete the assignments.&lt;br /&gt;
&lt;br /&gt;
* [[Node.JS]]&lt;br /&gt;
* [[Socket.IO]]&lt;br /&gt;
&lt;br /&gt;
== Individual Assignments ==&lt;br /&gt;
&lt;br /&gt;
=== Install Node.JS ===&lt;br /&gt;
&lt;br /&gt;
Install Node.JS from Apt or Yum according to the instructions in the [[Node.JS]] guide.&lt;br /&gt;
&lt;br /&gt;
=== Static File Server in Node.JS ===&lt;br /&gt;
&lt;br /&gt;
The individual portion of Module 6 is short in order to give you enough time to complete the group portion.&lt;br /&gt;
&lt;br /&gt;
# Copy the example code from the Node.JS guide into a file called ''static_server.js'' or something of that nature.  Save it on your EC2 instance (but not in a place that Apache can serve!).&lt;br /&gt;
#: Ensure that you understand what the static file server script is doing…&lt;br /&gt;
# Make a directory parallel to ''static_server.js'' named ''static''.&lt;br /&gt;
# Change &amp;quot;&amp;lt;STATIC DIRECTORY NAME&amp;gt;&amp;quot; on line 11 of the static fileserver example code to reflect the name of the directory you just made.&lt;br /&gt;
# Save the following files in your ''static'' directory:&lt;br /&gt;
#* ''hello.txt'', a text file containing &amp;quot;Hello World&amp;quot;&lt;br /&gt;
#* ''brookings.jpg'', an image file you can download from here: http://classes.engineering.wustl.edu/cse330/content/brookings.jpg&lt;br /&gt;
#* ''college.html'', an HTML document based on the [[HTML and CSS#Quick and Easy Page Layout|Quick and Easy HTML Layout]] containing an image tag pointing to ''brookings.jpg''&lt;br /&gt;
#* ''phpinfo.php'', a PHP file containing the phpinfo command that generates a diagnostic page of the server:&lt;br /&gt;
#: &amp;lt;source lang=&amp;quot;php&amp;quot;&amp;gt;&amp;lt;?php   phpinfo();   ?&amp;gt;&amp;lt;/source&amp;gt;&lt;br /&gt;
# Boot up your Node.JS static fileserver, and from your browser, load all four of the files you created in step 4.&lt;br /&gt;
#: Which ones work and which ones don't?  Why might this be the case?&lt;br /&gt;
&lt;br /&gt;
== Group Project ==&lt;br /&gt;
&lt;br /&gt;
In the group portion of Module 6 you will create a multi-room chat server using Node.JS and Socket.IO. You may not use Apache as your web server for the group project, it must be completed using Node.JS.&lt;br /&gt;
&lt;br /&gt;
This chat service will contain a main lobby where users sign on with a nickname and can communicate with each other.  Users may also create chat rooms for other to join.  The entire app should be displayed on a single webpage, listing the room you are in, all available rooms, and the users in the current room.&lt;br /&gt;
&lt;br /&gt;
The single room chat server and client are provided here: [[Socket.IO]]&lt;br /&gt;
&lt;br /&gt;
== Grading ==&lt;br /&gt;
&lt;br /&gt;
We will be grading the following aspects of your work.  There are 75 points total.&lt;br /&gt;
&lt;br /&gt;
'''Assignments (including code) must be committed to Bitbucket by the end of class on the due date (commit early and often). Failing to commit by the end of class on the due date will result in a 0. ''' &lt;br /&gt;
&lt;br /&gt;
_________&lt;br /&gt;
&lt;br /&gt;
# '''Individual Portion (25 Points):'''&lt;br /&gt;
#* Node.JS is installed on your EC2 instance (5 points)&lt;br /&gt;
#*: ''Take a screenshot of your browser visiting your EC2 instance serving up the college.html web page on port 3456, make sure the URL is visible in the screenshot.''&lt;br /&gt;
#* The ''hello.txt'', ''brookings.jpg'', and ''college.html'' files all load successfully (4 points each)&lt;br /&gt;
#* Visiting a file that does not exist inside the ''static'' directory results in a 404 (4 points)&lt;br /&gt;
#* Discuss in the README.md why ''phpinfo.php'' behaves the way it does when loaded through Node.JS (4 points)&lt;br /&gt;
#* Make sure all of your individual portion files are pushed to Bitbucket (include your node.js file, hello.txt, brookings.jpg, college.html, and phpinfo.php)&lt;br /&gt;
#*: ''The TA should be able to simply download your repo and start up your file server, without having to copy files or create additional subdirectories''&lt;br /&gt;
# '''Multi-room Chat Server (50 Points):'''&lt;br /&gt;
#* '''''Administration of user created chat rooms (25 Points):'''''&lt;br /&gt;
#** Users can create chat rooms with an arbitrary room name(5 points)&lt;br /&gt;
#** Users can join an arbitrary chat room (5 points)&lt;br /&gt;
#** The chat room displays all users currently in the room (5 points)&lt;br /&gt;
#** A private room can be created that is password protected (5 points)&lt;br /&gt;
#** Creators of chat rooms can temporarily kick others out of the room (3 points)&lt;br /&gt;
#** Creators of chat rooms can permanently ban users from joining that particular room (2 points)&lt;br /&gt;
#* '''''Messaging (5 Points):'''''&lt;br /&gt;
#** A user's message shows their username and is sent to everyone in the room (1 point)&lt;br /&gt;
#** Users can send private messages to another user in the same room (4 points)&lt;br /&gt;
#* '''''Best Practices (5 Points):'''''&lt;br /&gt;
#** Code is well formatted and easy to read, with proper commenting (2 points)&lt;br /&gt;
#** Code passes HTML validation (2 points)&lt;br /&gt;
#** node_modules folder is ignored by version control (1 points)&lt;br /&gt;
#* '''''Usability (5 Points):'''''&lt;br /&gt;
#** Communicating with others and joining rooms is easy and intuitive (4 points)&lt;br /&gt;
#** Site is visually appealing (1 point)&lt;br /&gt;
#* '''Creative Portion (10 Points)'''&lt;br /&gt;
#** Make sure to create a README.md file pointing to your server&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 6]]&lt;br /&gt;
[[Category:Modules]]&lt;/div&gt;</summary>
		<author><name>Alex</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Module_5&amp;diff=2507</id>
		<title>Module 5</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Module_5&amp;diff=2507"/>
		<updated>2018-02-12T17:45:01Z</updated>

		<summary type="html">&lt;p&gt;Alex: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;__NOTOC__&lt;br /&gt;
In Module 5, you will learn JavaScript, the dominant client-side web language.  JavaScript is the third and final programming language you will learn in CSE 330.&lt;br /&gt;
&lt;br /&gt;
This article contains your assignments for Module 5.&lt;br /&gt;
&lt;br /&gt;
'''Warning:'''&lt;br /&gt;
&lt;br /&gt;
''This module takes students a while. It is strongly recommended that you start early and ask questions as they come up.''&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Reading ==&lt;br /&gt;
&lt;br /&gt;
The following articles on the online class wiki textbook contain information that will help you complete the assignments.&lt;br /&gt;
&lt;br /&gt;
* [[JavaScript]]&lt;br /&gt;
* [[AJAX and JSON]]&lt;br /&gt;
* [[jQuery]]&lt;br /&gt;
* [[Web Application Security, Part 3]]&lt;br /&gt;
&lt;br /&gt;
== Individual Assignments ==&lt;br /&gt;
&lt;br /&gt;
'''''IMPORTANT:'' Both of the individual assignments must be completed ''without'' using a JavaScript library like jQuery.'''  However, you may (and should) use jQuery for the group portion.&lt;br /&gt;
&lt;br /&gt;
=== JavaScript Calculator ===&lt;br /&gt;
&lt;br /&gt;
In Module 2, you made a calculator using PHP.  Now you will be making one using JavaScript.&lt;br /&gt;
&lt;br /&gt;
* The web page should have two input fields and a radio button group for the operation, with the 4 basic math operations represented (add, subtract, multiply, divide).&lt;br /&gt;
* JavaScript should monitor all three fields and display the current result whenever the user changes any value in any field, without refreshing the page.&lt;br /&gt;
*: '''Tip 1:''' Consider using either the ''change'' or the ''keyup'' event on the text fields, and either the ''change'' or the ''click'' event on the radio buttons.&lt;br /&gt;
*: '''Tip 2:''' Re-read [[JavaScript|the JavaScript guide]] if you need help figuring our how to bind callback functions to events, or how to determine which radio button is currently selected.  (There are examples for both of these!)&lt;br /&gt;
* The calculator should be completely self-contained; i.e., you should not be making any requests to any other server-side or client-side scripts or web pages after the initial page load.&lt;br /&gt;
&lt;br /&gt;
'''Tip:''' You can embed JavaScript code into an HTML document like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;script type=&amp;quot;text/javascript&amp;quot;&amp;gt;&lt;br /&gt;
// your code here&lt;br /&gt;
&amp;lt;/script&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Tip:''' If your code isn't working the way you expect, use a JavaScript error console.  In Chrome, for example, press Ctrl-Shift-I (or Cmd-Option-I) to open the WebKit inspector.&lt;br /&gt;
&lt;br /&gt;
'''Important:''' It is best practice to fully separate the content, appearance, and behavior.  In previous modules, you may have lost points for using HTML tags that change the appearance of things &amp;lt;nowiki&amp;gt;(like &amp;lt;center&amp;gt; and &amp;lt;font&amp;gt;).&amp;lt;/nowiki&amp;gt;  In this module, make sure that you define your event listeners in JavaScript as in &amp;lt;code&amp;gt;document.getElementById(&amp;quot;xyz&amp;quot;).addEventListener(...)&amp;lt;/code&amp;gt; and '''''not''''' in the HTML like &amp;lt;code&amp;gt;&amp;lt;button onclick=&amp;quot;badExample();&amp;quot;&amp;gt;Bad Example&amp;lt;/button&amp;gt;&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== Weather Widget ===&lt;br /&gt;
&lt;br /&gt;
In this section, you will make a web page that displays the weather forecast using AJAX requests to a weather server.&lt;br /&gt;
&lt;br /&gt;
# Make an empty HTML document; name it '''weather.html'''&lt;br /&gt;
#: Refer to the [[HTML and CSS]] guide for the skeleton of an HTML document&lt;br /&gt;
# Define a function in JavaScript; call it '''fetchWeather()'''.  You may write your JavaScript in an embedded script in your HTML document.&lt;br /&gt;
# Inside your '''fetchWeather()''' function, make an AJAX request to the weather server.&lt;br /&gt;
#: We have a server that outputs the current weather in JSON format.  The format is documented in the [[#JSON Structure]] section below.&lt;br /&gt;
#: '''URL:''' https://classes.engineering.wustl.edu/cse330/content/weather_json.php&lt;br /&gt;
#: We kindly thank Yahoo Weather for providing us with up-to-date weather information.&lt;br /&gt;
#* '''IMPORTANT:''' Under normal circumstances, AJAX requests ''cannot'' be performed cross-domain for security reasons.  We have set the &amp;lt;code&amp;gt;Access-Control-Allow-Origin&amp;lt;/code&amp;gt; header on our server to allow requests from your EC2 instances, or from localhost.  '''You will therefore need to upload your code to your EC2, or access it via localhost, in order for the AJAX requests to work.'''  This means that you cannot, for example, complete this part of the individual portion in JSFiddle.&lt;br /&gt;
# In your callback, process the JSON and use JavaScript to manipulate the HTML DOM to display the following information on your page:&lt;br /&gt;
#* Location&lt;br /&gt;
#** City, in a &amp;lt;nowiki&amp;gt;&amp;lt;strong&amp;gt;&amp;lt;/nowiki&amp;gt; tag&lt;br /&gt;
#** State, not in any tag&lt;br /&gt;
#* Humidity&lt;br /&gt;
#* Current Temperature&lt;br /&gt;
#* Image for Tomorrow's Forecast (see [[#Weather Condition Images]] below for more information)&lt;br /&gt;
#* Image for the Day After Tomorrow's Forecast&lt;br /&gt;
# Finally, bind '''fetchWeather()''' to the DOMContentLoaded event so that your weather widget is automatically initialized when the page is loaded:&lt;br /&gt;
#: &amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;document.addEventListener(&amp;quot;DOMContentLoaded&amp;quot;, fetchWeather, false);&amp;lt;/source&amp;gt;&lt;br /&gt;
# In addition, add a button that runs your ''fetchWeather'' function when clicked.  This should update your widget with the current weather conditions.&lt;br /&gt;
&lt;br /&gt;
Use the following HTML:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;div class=&amp;quot;weather&amp;quot; id=&amp;quot;weatherWidget&amp;quot;&amp;gt;&lt;br /&gt;
	&amp;lt;div class=&amp;quot;weather-loc&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
	&amp;lt;div class=&amp;quot;weather-humidity&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
	&amp;lt;div class=&amp;quot;weather-temp&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
	&amp;lt;img class=&amp;quot;weather-tomorrow&amp;quot; /&amp;gt;&lt;br /&gt;
	&amp;lt;img class=&amp;quot;weather-dayaftertomorrow&amp;quot; /&amp;gt;&lt;br /&gt;
&amp;lt;/div&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Include the CSS file from here: http://classes.engineering.wustl.edu/cse330/content/weather.css&lt;br /&gt;
&lt;br /&gt;
When everything is working, the weather widget should look something like this:&lt;br /&gt;
&lt;br /&gt;
[[File:WeatherWidget.png]]&lt;br /&gt;
&lt;br /&gt;
'''Important:''' The widget in this section needs to work in only Firefox and Chrome.  It does '''''not''''' need to work Internet Explorer.&lt;br /&gt;
&lt;br /&gt;
==== Tips ====&lt;br /&gt;
&lt;br /&gt;
===== JSON Structure =====&lt;br /&gt;
&lt;br /&gt;
The JSON from our server looks like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
{&lt;br /&gt;
   &amp;quot;updated&amp;quot;: &amp;quot;Thu, 11 Oct 2012 5:54 pm CDT&amp;quot;,&lt;br /&gt;
   &amp;quot;location&amp;quot;: {&lt;br /&gt;
      &amp;quot;city&amp;quot;: &amp;quot;St. Louis&amp;quot;,&lt;br /&gt;
      &amp;quot;state&amp;quot;: &amp;quot;MO&amp;quot;&lt;br /&gt;
   },&lt;br /&gt;
   &amp;quot;wind&amp;quot;: {&lt;br /&gt;
      &amp;quot;chill&amp;quot;: &amp;quot;62&amp;quot;,&lt;br /&gt;
      &amp;quot;direction&amp;quot;: &amp;quot;150&amp;quot;,&lt;br /&gt;
      &amp;quot;speed&amp;quot;: &amp;quot;3 mph&amp;quot;&lt;br /&gt;
   },&lt;br /&gt;
   &amp;quot;atmosphere&amp;quot;: {&lt;br /&gt;
      &amp;quot;humidity&amp;quot;: &amp;quot;50&amp;quot;,&lt;br /&gt;
      &amp;quot;visibility&amp;quot;: &amp;quot;10&amp;quot;,&lt;br /&gt;
      &amp;quot;pressure&amp;quot;: &amp;quot;30.12 in&amp;quot;&lt;br /&gt;
   },&lt;br /&gt;
   &amp;quot;current&amp;quot;: {&lt;br /&gt;
      &amp;quot;code&amp;quot;: &amp;quot;28&amp;quot;,&lt;br /&gt;
      &amp;quot;text&amp;quot;: &amp;quot;Mostly Cloudy&amp;quot;,&lt;br /&gt;
      &amp;quot;temp&amp;quot;: &amp;quot;62°F&amp;quot;,&lt;br /&gt;
      &amp;quot;date&amp;quot;: &amp;quot;Thu, 11 Oct 2012 5:54 pm CDT&amp;quot;&lt;br /&gt;
   },&lt;br /&gt;
   &amp;quot;tomorrow&amp;quot;: {&lt;br /&gt;
      &amp;quot;code&amp;quot;: &amp;quot;29&amp;quot;,&lt;br /&gt;
      &amp;quot;text&amp;quot;: &amp;quot;Clouds Early/Clearing Late&amp;quot;,&lt;br /&gt;
      &amp;quot;low&amp;quot;: &amp;quot;45°F&amp;quot;,&lt;br /&gt;
      &amp;quot;high&amp;quot;: &amp;quot;61°F&amp;quot;&lt;br /&gt;
   },&lt;br /&gt;
   &amp;quot;dayafter&amp;quot;: {&lt;br /&gt;
      &amp;quot;code&amp;quot;: &amp;quot;30&amp;quot;,&lt;br /&gt;
      &amp;quot;text&amp;quot;: &amp;quot;Partly Cloudy&amp;quot;,&lt;br /&gt;
      &amp;quot;low&amp;quot;: &amp;quot;53°F&amp;quot;,&lt;br /&gt;
      &amp;quot;high&amp;quot;: &amp;quot;65°F&amp;quot;&lt;br /&gt;
   },&lt;br /&gt;
   &amp;quot;credit&amp;quot;: &amp;quot;http://us.rd.yahoo.com/dailynews/rss/weather/St._Louis__MO/*http://weather.yahoo.com/forecast/USMO0170_f.html&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===== Weather Condition Images =====&lt;br /&gt;
&lt;br /&gt;
Each day's forecast has a code.  There are images associated with these codes.&lt;br /&gt;
&lt;br /&gt;
One place to get the images is from here: &amp;lt;nowiki&amp;gt;http://us.yimg.com/i/us/nws/weather/gr/&amp;lt;/nowiki&amp;gt;'''##'''&amp;lt;nowiki&amp;gt;ds.png&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Replace the '''##''' with the forecast code.  For example, for code 32, the URL would be: http://us.yimg.com/i/us/nws/weather/gr/32ds.png&lt;br /&gt;
&lt;br /&gt;
== Group Project ==&lt;br /&gt;
&lt;br /&gt;
I forgot if I already mentioned this, but '''start early on this project!''' It will take longer than you think, I promise!&lt;br /&gt;
&lt;br /&gt;
You are encouraged to use the advanced version control practices you learned in Module 5 when completing this assignment.&lt;br /&gt;
&lt;br /&gt;
=== Calendar ===&lt;br /&gt;
&lt;br /&gt;
Build a simple calendar that allows users to add and remove events dynamically.&lt;br /&gt;
&lt;br /&gt;
You will use JavaScript to process user interactions at the web browser, without ever refreshing the browser after the initial web page load.  You may use a JavaScript library of your choice, including Ext JS.&lt;br /&gt;
&lt;br /&gt;
Your application should utilize AJAX to run server-side scripts that query your database to save and retrieve information, including user accounts and events.&lt;br /&gt;
&lt;br /&gt;
We have also written some functions to help you get started: [[JavaScript Calendar Library]]&lt;br /&gt;
&lt;br /&gt;
==== Examples ====&lt;br /&gt;
&lt;br /&gt;
* https://calendar.google.com/&lt;br /&gt;
* http://www.zoho.com/calendar/&lt;br /&gt;
&lt;br /&gt;
==== Server Side Language ====&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Additionally, you may use a database of your choice.  MySQL is probably the logical choice since you have been using it since Module 2, but you are free to explore other databases if you like.&lt;br /&gt;
&lt;br /&gt;
==== Requirements ====&lt;br /&gt;
&lt;br /&gt;
* Support a month-by-month view of the calendar.&lt;br /&gt;
*: Show one month at a time, with buttons to move forward or backward.&lt;br /&gt;
*: There should be no limit to how far forward or backward the user can go.&lt;br /&gt;
* Users can register and log in to the website.&lt;br /&gt;
*: You may leverage your MySQL project code and database from module 3 to get started.&lt;br /&gt;
* Unregistered users should see no events on the calendar.&lt;br /&gt;
* Registered users can add events.&lt;br /&gt;
*: All events should have a date and time, but do not need to have a duration.&lt;br /&gt;
*: You do ''not'' need to support recurring events (where you add an event that repeats, for example, every monday).&lt;br /&gt;
* Registered users see only events that they have added.&lt;br /&gt;
*: Your AJAX should not ask the server for events from a certain username.  Instead, your AJAX should ask the server for events, and the server should respond with the events for only the currently-logged-in user (from the session).  Can you think of why?&lt;br /&gt;
* Registered users can delete their events, but not the events of others.&lt;br /&gt;
*: Again, the server should delete events based on the username present in the session.  (If it deletes only based on an Event ID, an attacker could feed any arbitrary Event ID to your server, even if he/she didn't own that event.)&lt;br /&gt;
* All user and event data should be kept in a database.&lt;br /&gt;
* At no time should the main page need to be reloaded.&lt;br /&gt;
*: User registration, user authentication, event addition, and event deletion should all be handled by JavaScript and AJAX requests to your server.&lt;br /&gt;
* Your page needs to work in the versions of Firefox and Chrome installed on the lab computers.&lt;br /&gt;
&lt;br /&gt;
'''Tip:''' Run your database schema by a TA before implementing it.&lt;br /&gt;
&lt;br /&gt;
=== Web Security and Validation ===&lt;br /&gt;
&lt;br /&gt;
Your project needs to demonstrate that thought was put into web security and best practice.  For more information, see this week's Web Application Security guide: [[Web Application Security, Part 3]]&lt;br /&gt;
&lt;br /&gt;
In particular:&lt;br /&gt;
&lt;br /&gt;
* '''Your application needs to prevent XSS attacks.'''  Be careful when transmitting data over JSON that will be reflected in an event title!  (Note: JSON data should be sanitized on the client side, not the server side.)&lt;br /&gt;
* '''Perform precautionary measures to prevent session hijacking attacks.'''&lt;br /&gt;
*: You should specify your session cookie to be HTTP-Only.  However, for the means of this module, you need not test for user agent consistency.&lt;br /&gt;
* '''Optional:''' Validate your JavaScript code using [http://www.jshint.com/ JSHint] '''''or''''' [http://jslint.com/ JSLint] for up to 3 points of extra credit.&lt;br /&gt;
&lt;br /&gt;
You should continue the practices that you have learned in past weeks:&lt;br /&gt;
&lt;br /&gt;
* Pass tokens in forms to prevent CSRF attacks.&lt;br /&gt;
*: '''Hint:''' You will need to send your CSRF tokens in your AJAX requests.  Remember that AJAX still submits forms and runs server-side scripts, just like the vanilla forms you've been using in Modules 2 and 3.&lt;br /&gt;
* Use prepared queries to prevent SQL Injection attacks.&lt;br /&gt;
* If storing passwords in a database, always store them salted and encrypted.&lt;br /&gt;
* Your page should validate with no errors through the W3C validator.&lt;br /&gt;
&lt;br /&gt;
== Grading ==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
We will be grading the following aspects of your work.  There are 100 points total.&lt;br /&gt;
&lt;br /&gt;
'''Assignments (including code) must be committed to Bitbucket by the end of class on the due date (commit early and often). Failing to commit by the end of class on the due date will result in a 0. ''' &lt;br /&gt;
&lt;br /&gt;
_________&lt;br /&gt;
&lt;br /&gt;
# '''JavaScript Calculator (10 Points):'''&lt;br /&gt;
#* Calculator successfully adds, subtracts, multiplies, and divides numbers (3 points)&lt;br /&gt;
#* The result is automatically computed when a value in either field is changed (3 points)&lt;br /&gt;
#* Calculator is written entirely in pure, conventional JavaScript with no external libraries (4 points)*&lt;br /&gt;
#*: ''Note: be sure to fully separate content, appearance, and behavior.  This means that you should '''not''' use the event attributes on the HTML elements like onclick, onchange, and onkeyup.''&lt;br /&gt;
# '''Weather Widget (15 Points):'''&lt;br /&gt;
#* Widget performs an AJAX request to fetch the current weather (4 points)&lt;br /&gt;
#* The HTML template is filled with the correct information, including an image (4 points)&lt;br /&gt;
#* Button to reload the weather widget (2 points)&lt;br /&gt;
#* Widget is written entirely in pure, conventional JavaScript with no external libraries (5 points)*&lt;br /&gt;
# '''AJAX Calendar (60 Points):'''&lt;br /&gt;
#* '''''Calendar View (10 Points):'''''&lt;br /&gt;
#** The calendar is displayed as a table grid with days as the columns and weeks as the rows, one month at a time (5 points)&lt;br /&gt;
#** The user can view different months as far in the past or future as desired (5 points)&lt;br /&gt;
#* '''''User and Event Management (25 Points):'''''&lt;br /&gt;
#** Events can be added, modified, and deleted (5 points)&lt;br /&gt;
#** Events have a title, date, and time (2 points)&lt;br /&gt;
#** Users can log into the site, and they cannot view or manipulate events associated with other users (8 points)&lt;br /&gt;
#**: ''Don't fall into the Abuse of Functionality trap!  Check user credentials on the server side as well as on the client side.''&lt;br /&gt;
#** All actions are performed over AJAX, without ever needing to reload the page (10 points)&lt;br /&gt;
#* '''''Best Practices (20 Points):'''''&lt;br /&gt;
#** Code is well formatted and easy to read, with proper commenting (2 points)&lt;br /&gt;
#** If storing passwords, they are stored salted and encrypted (2 points)&lt;br /&gt;
#** All AJAX requests that either contain sensitive information or modify something on the server are performed via POST, not GET (3 points)&lt;br /&gt;
#** Safe from XSS attacks; that is, all content is escaped on output (3 points)&lt;br /&gt;
#** Safe from SQL Injection attacks (2 points)&lt;br /&gt;
#** CSRF tokens are passed when editing or removing events (3 points)&lt;br /&gt;
#** Session cookie is HTTP-Only (3 points)&lt;br /&gt;
#** Page passes the W3C validator (2 points)&lt;br /&gt;
#** ''Extra Credit:'' Your code passes ''JSHint'' or ''JSLint'' (+3 bonus points)&lt;br /&gt;
#* '''''Usability (5 Points):'''''&lt;br /&gt;
#** Site is intuitive to use and navigate (4 points)&lt;br /&gt;
#** Site is visually appealing (1 point)&lt;br /&gt;
# '''Creative Portion (15 Points)'''&lt;br /&gt;
#* '''Additional Calendars Features (worth 15 points):''' Develop some additional features for the calendar, a few examples are provided below.&lt;br /&gt;
#**  Users can tag an event with a particular category and enable/disable those tags in the calendar view. (5 points)&lt;br /&gt;
#**  Users can share their calendar with additional users. (5 points)&lt;br /&gt;
#**  Users can create group events that display on multiple users calendars (5 points)&lt;br /&gt;
#*  '''Make sure to save a description of your creative portion, and a link to your server in your README.md file.'''&lt;br /&gt;
''* These points can be earned only if at least 3 other points have been earned in that category.  This is to prevent these points from being &amp;quot;free.&amp;quot;''&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 5]]&lt;br /&gt;
[[Category:Modules]]&lt;/div&gt;</summary>
		<author><name>Alex</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Module_4&amp;diff=2506</id>
		<title>Module 4</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Module_4&amp;diff=2506"/>
		<updated>2018-02-12T17:44:53Z</updated>

		<summary type="html">&lt;p&gt;Alex: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;__NOTOC__&lt;br /&gt;
In Module 4, you will learn the fundamentals of Python, a popular scripting language, and Regular Expressions, which give you power in text processing.&lt;br /&gt;
&lt;br /&gt;
This article contains your assignments for Module 4.&lt;br /&gt;
&lt;br /&gt;
== Reading ==&lt;br /&gt;
&lt;br /&gt;
The following articles on the online class wiki textbook contain information that will help you complete the assignments.&lt;br /&gt;
&lt;br /&gt;
* [[Python]]&lt;br /&gt;
* [[Regular Expressions]]&lt;br /&gt;
&lt;br /&gt;
== Individual Assignments ==&lt;br /&gt;
&lt;br /&gt;
=== Learn Python and Regular Expressions ===&lt;br /&gt;
&lt;br /&gt;
Up to this point in CSE 330, you have used only one programming language: PHP.  In Module 4, you will learn a new language: Python.  Before starting this assignment, you should look over the [[Python|online textbook article about Python]].  You should be using version 3 (or greater) of Python. Additionally, you may find it helpful to look over the [[Regular Expressions|online textbook article about Regular Expressions]].&lt;br /&gt;
&lt;br /&gt;
=== Write some Regular Expressions ===&lt;br /&gt;
&lt;br /&gt;
Please write regular expressions that do each the following:&lt;br /&gt;
&lt;br /&gt;
# Match the string &amp;quot;hello world&amp;quot; in a sentence&lt;br /&gt;
# Find all words in an input string that contains three consecutive vowels, regardless of case.&lt;br /&gt;
# Match an input string that is '''entirely''' a flight code, of the format AA####, where '''AA''' is a two-letter uppercase airline code, and '''####''' is a three- or four-digit flight number&lt;br /&gt;
Examples:&lt;br /&gt;
   Note: text in ''[[red]]'' is matched by the regular expression. Each line is a separate test input string.&lt;br /&gt;
   Regex 1:  Programmers will often write ''[[hello world]]'' as their first project with a programming language.&lt;br /&gt;
   Regex 2:  The ''[[gooey]]'' peanut butter and jelly sandwich was a ''[[beauty]]''.&lt;br /&gt;
   Regex 3:  ''[[AA312]]''&lt;br /&gt;
             ''[[AA1298]]''&lt;br /&gt;
             ''[[NW1234]]''&lt;br /&gt;
             ''[[US443]]''&lt;br /&gt;
             US31344&lt;br /&gt;
             AA123 extratext&lt;br /&gt;
&lt;br /&gt;
            &lt;br /&gt;
&lt;br /&gt;
Save your regexes to a text file.  The TA will test them in regexpal on Demo Day.&lt;br /&gt;
&lt;br /&gt;
=== Baseball Stats Counter ===&lt;br /&gt;
&lt;br /&gt;
The St. Louis Cardinals are the most legendary baseball team in the national league.  In this exercise, you will be creating a Python script that reads box scores from a file and computes the Cardinals' players' batting averages in a particular season.&lt;br /&gt;
&lt;br /&gt;
==== Tips and Instructions ====&lt;br /&gt;
&lt;br /&gt;
* You should write a Python script file to solve this problem.&lt;br /&gt;
* You should use a regular expression to parse players' names, at-bats, hits, and runs from the input file.&lt;br /&gt;
* You may want to create a class to hold and compute information about each player.&lt;br /&gt;
* Your file should take one command-line argument: the path to an input file.  If no path is given, your program should print a usage message.&lt;br /&gt;
&lt;br /&gt;
==== Input ====&lt;br /&gt;
&lt;br /&gt;
Sample input files may be found here: http://classes.engineering.wustl.edu/cse330/content/cardinals/&lt;br /&gt;
&lt;br /&gt;
The top of the file contains a citation, and what follows is an entire season of Cardinals Baseball box scores.  Each game starts with a title; for example:&lt;br /&gt;
&lt;br /&gt;
 === St.Louis Cardinals vs. Chicago Cubs, 1940-04-19 ===&lt;br /&gt;
&lt;br /&gt;
What follows are the performance of each player in that game.  The format of each line is as follows:&lt;br /&gt;
&lt;br /&gt;
 XXX batted # times with # hits and # runs&lt;br /&gt;
&lt;br /&gt;
where '''XXX''' is the player's name (you may assume that the name is unique), and each '''#''' are integers representing the number of &amp;quot;at bats&amp;quot;, the number of &amp;quot;hits&amp;quot;, and the number of &amp;quot;runs&amp;quot;, respectively.&lt;br /&gt;
&lt;br /&gt;
==== Output ====&lt;br /&gt;
&lt;br /&gt;
Your script needs to output all players' batting average across the season.  A player's batting average is that player's total hits divided by that player's total at-bats throughout the entire season.  For example, Johnny Hopp was at bat 149 times in 1940, and he had 41 hits, so his batting average was 0.275.&lt;br /&gt;
&lt;br /&gt;
Each line in the output should have the format:&lt;br /&gt;
&lt;br /&gt;
 XXX: #.###&lt;br /&gt;
&lt;br /&gt;
where '''XXX''' is the player's name, and '''#.###''' is the player's batting average, '''rounded''' (not truncated) to three decimal places.&lt;br /&gt;
&lt;br /&gt;
The players should be sorted by batting average, with the highest batting average on top.  If two players have the exact same batting average (before rounding occurs), the order between those two players is unimportant.&lt;br /&gt;
&lt;br /&gt;
For example, the correct output for the 1940 season is:&lt;br /&gt;
&amp;lt;!-- Jimmy Brown was 0.280 and Ira Hutchinson was 0.125 --&amp;gt;&lt;br /&gt;
&amp;lt;source lang=&amp;quot;text&amp;quot;&amp;gt;&lt;br /&gt;
Pepper Martin: 0.316&lt;br /&gt;
Walker Cooper: 0.316&lt;br /&gt;
Johnny Mize: 0.314&lt;br /&gt;
Ernie Koy: 0.310&lt;br /&gt;
Enos Slaughter: 0.306&lt;br /&gt;
Joe Medwick: 0.304&lt;br /&gt;
Terry Moore: 0.304&lt;br /&gt;
Joe Orengo: 0.286&lt;br /&gt;
Jimmy Brown: 0.280&lt;br /&gt;
Marty Marion: 0.279&lt;br /&gt;
Don Gutteridge: 0.276&lt;br /&gt;
Johnny Hopp: 0.275&lt;br /&gt;
Creepy Crespi: 0.273&lt;br /&gt;
Mickey Owen: 0.265&lt;br /&gt;
Bill DeLancey: 0.250&lt;br /&gt;
Don Padgett: 0.242&lt;br /&gt;
Stu Martin: 0.238&lt;br /&gt;
Eddie Lake: 0.222&lt;br /&gt;
Hal Epps: 0.214&lt;br /&gt;
Lon Warneke: 0.209&lt;br /&gt;
Harry Walker: 0.185&lt;br /&gt;
Max Lanier: 0.179&lt;br /&gt;
Bill McGee: 0.178&lt;br /&gt;
Carl Doyle: 0.174&lt;br /&gt;
Mort Cooper: 0.157&lt;br /&gt;
Clyde Shoun: 0.145&lt;br /&gt;
Carden Gillenwater: 0.130&lt;br /&gt;
Bob Bowman: 0.067&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Grading ==&lt;br /&gt;
&lt;br /&gt;
We will be grading the following aspects of your work.  There are 50 points total.&lt;br /&gt;
&lt;br /&gt;
'''Assignments (including code) must be committed to Bitbucket by the end of class on the due date (commit early and often). Failing to commit by the end of class on the due date will result in a 0. ''' &lt;br /&gt;
&lt;br /&gt;
Upload your baseball code, a file with your Regular expressions, and a screenshot of your python output onto Bitbucket.&lt;br /&gt;
&lt;br /&gt;
# '''Regular Expressions (15 Points):'''&lt;br /&gt;
#* Regular Expression 1 Correct and saved in a file named &amp;lt;code&amp;gt;regex1.txt&amp;lt;/code&amp;gt; (5 points)&lt;br /&gt;
#* Regular Expression 2 Correct and saved in a file named &amp;lt;code&amp;gt;regex2.txt&amp;lt;/code&amp;gt;(5 points)&lt;br /&gt;
#* Regular Expression 3 Correct and saved in a file named &amp;lt;code&amp;gt;regex3.txt&amp;lt;/code&amp;gt;(5 points)&lt;br /&gt;
# '''Baseball Stats Counter (35 Points):'''&lt;br /&gt;
#* Solution is written entirely in Python and saved in a file named &amp;lt;code&amp;gt;baseball.py&amp;lt;/code&amp;gt; (8 points)&lt;br /&gt;
#* Correct usage of one or more regular expressions to parse and extract data from each line of the input file (8 points)&lt;br /&gt;
#* Script prints a usage message if a command line argument is not present (4 points)&lt;br /&gt;
#* Output is correct for all test cases (15 points)&lt;br /&gt;
#*: ''This includes sorting and rounding.''&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 4]]&lt;br /&gt;
[[Category:Modules]]&lt;/div&gt;</summary>
		<author><name>Alex</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Module_1&amp;diff=2505</id>
		<title>Module 1</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Module_1&amp;diff=2505"/>
		<updated>2018-02-12T17:44:39Z</updated>

		<summary type="html">&lt;p&gt;Alex: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;__NOTOC__ &lt;br /&gt;
Module 1 introduces the fundamentals of HTML and CSS.  You will first make a static document using HTML and CSS, and then you will make a portal to a DuckDuckGo search.  This module is worth 50 points.&lt;br /&gt;
&lt;br /&gt;
== Reading ==&lt;br /&gt;
&lt;br /&gt;
The following articles on the online class wiki textbook contain information that will help you complete the assignment.&lt;br /&gt;
&lt;br /&gt;
* [[Git]]&lt;br /&gt;
* [[HTML and CSS]]&lt;br /&gt;
* [[HTML Forms]]&lt;br /&gt;
&lt;br /&gt;
== Assignments ==&lt;br /&gt;
&lt;br /&gt;
=== Write a Birthday Card ===&lt;br /&gt;
&lt;br /&gt;
'''Write a birthday card to a friend or family member using HTML and CSS.'''  Use HTML to define the content of the card (like the headings and the paragraphs), and use CSS to define the appearance.  Some ideas:&lt;br /&gt;
&lt;br /&gt;
* Make the background-color of the page baby blue and use purple ink to write a card to a little boy&lt;br /&gt;
* Make the text big and include pictures of hearts&lt;br /&gt;
* Use a font with text shadows (more advanced)&lt;br /&gt;
&lt;br /&gt;
Use this opportunity to experiment with the plethora of CSS properties.  Remember that you're in a computer science class (not an art class), so we don't care if your card looks ugly.  The main thing is that you learn HTML and CSS and use them appropriately.&lt;br /&gt;
&lt;br /&gt;
==== How to Edit Your File ====&lt;br /&gt;
&lt;br /&gt;
Starting in Module 2, we will be using Komodo Edit as our primary development tool.  However, for the purposes of this exercise, we want you to edit your HTML file using a more basic text editor. '''If you already have a text editor that works for you, like [https://www.sublimetext.com/ Sublime Text], [https://atom.io/ Atom], Vim, or Emacs, feel free to use it for the entirety of this course. The same is true if you're already a fan of an IDE - you don't ''have'' to use any of the suggestions below.'''&lt;br /&gt;
&lt;br /&gt;
* On Windows, consider Notepad++.  This is already installed for you in the CEC labs.  If you prefer to use your personal computer, you can download it from [https://notepad-plus-plus.org/ here].&lt;br /&gt;
&amp;lt;!-- As of February 11th, 2017, TextWrangler's website has an improperly configured SSL certificate, so we can't link to HTTPS yet. --&amp;gt;&lt;br /&gt;
* On Mac OS X, consider TextWrangler.  You can download it from [http://www.barebones.com/products/textwrangler/ here] or from the Mac App Store.&lt;br /&gt;
* Most Linux distributions come with gedit pre-installed, which you can use for this lab.&lt;br /&gt;
&lt;br /&gt;
Please save your file as ''birthday.html'' from the plain text editor of your choice.&lt;br /&gt;
&lt;br /&gt;
'''Important Note:''' Writing your web page in a word processor like Microsoft Word or even WordPad or TextEdit will ''not'' work.  You need a plain text editor.&lt;br /&gt;
&lt;br /&gt;
==== How to View Your HTML Document ====&lt;br /&gt;
&lt;br /&gt;
Once you have ''birthday.html'', you can open it using your favorite web browser (like Firefox).  For the purposes of this exercise, it suffices to right-click the file and tell it to &amp;quot;open with&amp;quot; Firefox.  When the file opens, it should be under the file:/// protocol.&lt;br /&gt;
&lt;br /&gt;
In Module 2, we will install a web server that serves up pages on the http:// and https:// protocols.&lt;br /&gt;
&lt;br /&gt;
==== Validation ====&lt;br /&gt;
&lt;br /&gt;
'''Your birthday card must pass the W3C Validators for both HTML and CSS with no errors.'''  You can upload your HTML to [https://validator.w3.org/ the HTML validator] and your CSS to [https://jigsaw.w3.org/css-validator/ the CSS validator].&lt;br /&gt;
&lt;br /&gt;
For more information on validation, see the HTML and CSS guide: [[HTML and CSS#Validation]]&lt;br /&gt;
&lt;br /&gt;
=== Make a Portal to a DuckDuckGo Search ===&lt;br /&gt;
&lt;br /&gt;
'''Write an HTML document containing a form that searches DuckDuckGo's web site.'''  You should be able to type in a search term and have your form load the DuckDuckGo search page.&lt;br /&gt;
&lt;br /&gt;
# Visit [https://www.duckduckgo.com/ www.duckduckgo.com].  Search for something easy to spot in the URL, like &amp;quot;QUERY&amp;quot;.&lt;br /&gt;
# Look at the URL of the search page.  What is the script URL?  What is the query variable?&lt;br /&gt;
# Make an HTML document containing a text field and a submit button.  Typing a search query into the text field and pressing the submit button should load the DuckDuckGo search page.&lt;br /&gt;
&lt;br /&gt;
== Grading ==&lt;br /&gt;
&lt;br /&gt;
We will be grading the following aspects of your work.  There are 50 points total.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Assignments (including code) must be committed to Bitbucket by the end of class on the due date. Commit early and often. Failing to commit by the end of class on the due date will result in a 0. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# '''Birthday Card (30 Points):'''&lt;br /&gt;
#* Correct usage of HTML and CSS in your birthday card (10 points).&lt;br /&gt;
#*: ''Make sure that you use HTML for &amp;quot;content&amp;quot; and CSS for &amp;quot;appearance.&amp;quot;  Don't write inline styles: use a separate stylesheet and link your HTML file to it.''&lt;br /&gt;
#* Experimenting with at least 5 different CSS properties in your birthday card (10 points).&lt;br /&gt;
#* Birthday card passes the W3C validation for HTML 5 and CSS. (10 points).&lt;br /&gt;
# '''Search Portal (10 Points):'''&lt;br /&gt;
#* DuckDuckGo search portal is functional (10 points).&lt;br /&gt;
# '''Account Creation and Version Control (10 Points):'''&lt;br /&gt;
#* Bitbucket account created (2 Points)&lt;br /&gt;
#* Module 1 repo created using the link provided on Piazza (2 Points)&lt;br /&gt;
#* Account created on Amazon Web Services and an image file containing a screenshot of your account page pushed to Bitbucket. (4 Points)&lt;br /&gt;
#* Files pushed to repo on Bitbucket using Git (2 Points)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 1]]&lt;br /&gt;
[[Category:Modules]]&lt;/div&gt;</summary>
		<author><name>Alex</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Module_2&amp;diff=2504</id>
		<title>Module 2</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Module_2&amp;diff=2504"/>
		<updated>2018-02-12T17:44:27Z</updated>

		<summary type="html">&lt;p&gt;Alex: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;__NOTOC__ &lt;br /&gt;
Module 2 introduces you to Linux, a command-line environment, the Apache web server, and PHP.  You will create and configure your own cloud instance, install Apache and related software, and then form groups to make a simple file sharing site.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;span style=&amp;quot;font-size:1.3em; line-height:1.2em; color:blue;&amp;quot;&amp;gt;'''DO NOT WAIT UNTIL THE LAST MINUTE TO START ON THIS (or any) MODULE!'''  The most common reason students perform poorly in this class is procrastination.  You have been warned.&amp;lt;/span&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Reading ==&lt;br /&gt;
&lt;br /&gt;
The following articles on the online class wiki textbook contain information that will help you complete the assignments.&lt;br /&gt;
&lt;br /&gt;
* [[Linux]]&lt;br /&gt;
* [[Bash]]&lt;br /&gt;
* [[Amazon Web Services]]&lt;br /&gt;
* [[SSH]]&lt;br /&gt;
* [[Apache]]&lt;br /&gt;
* [[PHP]]&lt;br /&gt;
* [[Workflow]]&lt;br /&gt;
* [[Web Application Security, Part 1]]&lt;br /&gt;
&lt;br /&gt;
== Individual Assignments ==&lt;br /&gt;
&lt;br /&gt;
{{RequiredInstructions|content=&lt;br /&gt;
&lt;br /&gt;
&amp;lt;span style=&amp;quot;color:red&amp;quot;&amp;gt;There are a lot of wiki pages that you need to read in order to complete the individual portion of Module 2.  The wiki pages contain an assortment of required steps, optional steps, and information.  To make things easier, we have highlighted the ''required steps'' with a red bar, like you see on the left of this message.  Do not skip anything marked with a red bar, or else you will not have a perfectly configured instance.&amp;lt;/span&amp;gt;&lt;br /&gt;
&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
=== Learn About Linux ===&lt;br /&gt;
&lt;br /&gt;
Linux is an open-source operating system based on UNIX. Linux is highly versatile and is used in a wide range of applications.&lt;br /&gt;
&lt;br /&gt;
If you are not a Linux guru, read the Linux guide to get started: [[Linux]]&lt;br /&gt;
&lt;br /&gt;
=== Windows Users Only: Enable Windows Subsystem for Linux (WSL) or Install Cygwin ===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
You will need WSL or Cygwin in order to log into and configure your EC2 instance. Cygwin is already installed on the CEC machines. If you're using Windows 10, you can use WSL, which is an officially-supported way of accessing a Linux terminal on Windows. If not, you'll have to use Cygwin. Instructions for installing either on your personal machine are located in [[Workflow#Cygwin|the Workflow guide]].&lt;br /&gt;
&lt;br /&gt;
Mac OS X users should located the &amp;quot;Terminal&amp;quot; application, which is installed by default; you will need this in the coming steps.&lt;br /&gt;
&lt;br /&gt;
=== Create an AWS EC2 Instance ===&lt;br /&gt;
&lt;br /&gt;
Once you understand [[Linux]], you need to set up your Amazon EC2 Instance.  Use the AWS article to guide you through the process: [[Amazon Web Services]]&lt;br /&gt;
&lt;br /&gt;
=== Configure SSH ===&lt;br /&gt;
&lt;br /&gt;
Follow the instructions in [[SSH#SSH Configuration|the SSH guide]] to do the following:&lt;br /&gt;
&lt;br /&gt;
# Create your own SSH key pair&lt;br /&gt;
# Log in as the default user to your EC2 instance&lt;br /&gt;
# Create a new user&lt;br /&gt;
# Give the new user your SSH public key&lt;br /&gt;
&lt;br /&gt;
From now on, when you need to log into your EC2 instance as an administrator, just pop up a terminal and run:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ ssh your-username@ec2-xx-xx-xx-xx.compute-1.amazonaws.com&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Install Essential Packages ===&lt;br /&gt;
&lt;br /&gt;
Recall that software installation in Linux instances is usually handled through a package manager, like '''yum'''.  For more information, refer to [[Linux#Repository-Based Package Managers|the Linux guide]].&lt;br /&gt;
&lt;br /&gt;
To make sure everything is working properly, '''install your first package(s) according to the ''Essential Packages'' subsection in the Linux guide.'''&lt;br /&gt;
&lt;br /&gt;
=== Set the Timezone ===&lt;br /&gt;
&lt;br /&gt;
'''Set your server to use US Central time (America/Chicago).'''  Instructions are in the Linux guide: [[Linux#Synchronizing Date and Time]]&lt;br /&gt;
&lt;br /&gt;
=== Set Up the Apache Web Server ===&lt;br /&gt;
&lt;br /&gt;
You need to '''install the Apache web server on your EC2 instance'''.  Refer to [[Apache|the Apache guide]].&lt;br /&gt;
&lt;br /&gt;
In order for your web server to be accessible, you need to '''open up Port 80 on your EC2 instance'''.  Instructions are in the AWS guide: [[Amazon Web Services#Enabling Web Access to your EC2 Instance]]&lt;br /&gt;
&lt;br /&gt;
'''Enable the UserDir module in Apache.'''  Instructions are in the Apache guide: [[Apache#The UserDir Module]]&lt;br /&gt;
&lt;br /&gt;
=== Install PHP ===&lt;br /&gt;
&lt;br /&gt;
You need to '''install PHP on your EC2 server'''.  Instructions are at the top of the PHP guide: [[PHP]]&lt;br /&gt;
&lt;br /&gt;
You need to '''configure PHP to show errors'''.  Instructions are immediately below installation in the PHP guide.&lt;br /&gt;
&lt;br /&gt;
=== Learn about the PHP Language ===&lt;br /&gt;
&lt;br /&gt;
Before you can continue, you will need to make yourself acquainted with PHP language components.  Read the PHP guide for an overview: [[PHP#PHP Language Components]]&lt;br /&gt;
&lt;br /&gt;
=== Set Up your Workspace ===&lt;br /&gt;
&lt;br /&gt;
You are now ready to set up the workspace that you will be using for the rest of the semester.  Follow the instructions in [[Workflow]] to:&lt;br /&gt;
&lt;br /&gt;
# Make an account on Bitbucket&lt;br /&gt;
# Setup a repo using the CSE 330 Repo Creation Tool&lt;br /&gt;
# Install SourceTree&lt;br /&gt;
# '''Windows only:''' Set up Pageant so that SourceTree can conect to Bitbucket&lt;br /&gt;
# Clone your CSE 330 repo from Bitbucket&lt;br /&gt;
# Install Komodo Edit&lt;br /&gt;
# Create a Komodo Edit Project inside of your Git repository&lt;br /&gt;
# Add the ''*.komodoproject'' file to ''.gitignore''&lt;br /&gt;
# Install FileZilla&lt;br /&gt;
# Connect FileZilla to your remote instance&lt;br /&gt;
&lt;br /&gt;
=== Calculator ===&lt;br /&gt;
&lt;br /&gt;
'''Make a calculator using PHP and an HTML form.'''  The form should have two inputs.  The form should submit a GET request either back to the same page or to a different results page.  The calculator should support addition, subtraction, multiplication, and division by means of a radio button group on the page.  (Consider edge cases!)&lt;br /&gt;
&lt;br /&gt;
== Group Project ==&lt;br /&gt;
&lt;br /&gt;
You will work in pairs (that means you and one other person) on this project.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;span style=&amp;quot;font-size:1.3em; line-height:1.2em; color:blue;&amp;quot;&amp;gt;In this module, and all future modules, the group portion builds off of material you learn in the individual portion.  You should therefore complete the individual portions prior to working on the group portions.  (Trust us: it will make your life easier!)&amp;lt;/span&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Important Reminder:''' frequently commit your work to your repository as a backup!&lt;br /&gt;
&lt;br /&gt;
=== Simple File Sharing Site ===&lt;br /&gt;
&lt;br /&gt;
You will be making a simple file sharing site that supports uploading, viewing, and deleting files associated with various users.  Details:&lt;br /&gt;
&lt;br /&gt;
* You should have a file named '''users.txt''' stored in a secure place on your filesystem.  It should have at least three usernames, with one username per line.&lt;br /&gt;
*: Passwords add an extra layer of complexity (encryption) that we will cover in Module 3.  You will not earn credit for implementing passwords as your creative portion for this module.&lt;br /&gt;
* Users of the file sharing site should be able to enter their username and then log in.&lt;br /&gt;
*: You may implement logins using session variables, or you may implement them using a GET parameter that is passed between pages.  You will need to always use sessions starting in Module 3.&lt;br /&gt;
* Users should see a list of all files associated with their username after the log in.&lt;br /&gt;
* Users should be able to view, upload, and delete files associated with their username.&lt;br /&gt;
* The URI should NOT reveal the internal file structure of your web site.&lt;br /&gt;
** Example of what not to do:  http://www.example.com/download.php?file=/home/paul/file.txt&lt;br /&gt;
** Another bad example:  http://www.example.com/~user/file.txt&lt;br /&gt;
** Good example: http://www.example.com/view.php?user=music&amp;amp;name=file.txt&lt;br /&gt;
*: In general, don't reveal any internal information about the site.&lt;br /&gt;
*: '''Food for thought:''' Given that Apache processes (with the exception of the main process) do not run as root, but rather as the user apache, how can you allow both your user account and the php scripts to read and write the &lt;br /&gt;
*:necessary files?&lt;br /&gt;
*:: ''Hint:'' You shouldn't be storing the user-uploaded files in public_html (that is only the place for your own web-page files), &lt;br /&gt;
*::''Hint number 2:''  you will need to use chown to change permissions to let user apache have permissions on the user-files (that '''are not''' in the public_html folder). If you don't know what this does or how to do this, look at the [[Apache]] page&lt;br /&gt;
* You should customize your file sharing site by implementing an additional feature or two as part of the '''creative portion'''.&lt;br /&gt;
&lt;br /&gt;
You will probably find the PHP guide on this wiki to be helpful: [[PHP#Other PHP Tips]]&lt;br /&gt;
&lt;br /&gt;
=== Web Security and Validation ===&lt;br /&gt;
&lt;br /&gt;
Your project needs to demonstrate that thought was put into web security and best practice.  For more information, see this week's Web Application Security guide: [[Web Application Security, Part 1]]&lt;br /&gt;
&lt;br /&gt;
In particular:&lt;br /&gt;
&lt;br /&gt;
* '''Your application needs to follow the conventions of FIEO (Filter Input and Escape Output)'''.  Things you should filter include file names, usernames, and so on.&lt;br /&gt;
* '''Your project must pass the W3C Validator with no errors'''.  For more information, see the HTML and CSS guide: [[HTML and CSS#Validation]]&lt;br /&gt;
&lt;br /&gt;
== Grading ==&lt;br /&gt;
&lt;br /&gt;
We will be grading the following aspects of your work.  There are 100 points total. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Assignments (including code) must be committed to BitBucket by the end of class on the due date. Commit early and often. Failing to commit by the end of class on the due date will result in a 0. &lt;br /&gt;
&lt;br /&gt;
_____________&lt;br /&gt;
&lt;br /&gt;
# '''Cloud Instance and Web Server (30 Points):'''&lt;br /&gt;
#* You can SSH into your instance using your own custom username and SSH key. Put a screenshot in your repository of your terminal SSH-ing into your instance (15 points)&lt;br /&gt;
#* Your custom username is able to perform SUDO commands. Put a screenshot in your repository of you successfully executing a command with sudo (5 points)&lt;br /&gt;
#* The time zone is correct on your instance. Put a screenshot in your repository of the results of the `date` command (5 points)&lt;br /&gt;
#* The UserDir Apache module is working. Place a file in /home/&amp;lt;username&amp;gt;/public_html and link to the file in your README.md (5 points)&lt;br /&gt;
# '''PHP Calculator (15 Points):'''&lt;br /&gt;
#* The calculator is able to perform all four functions with floating point numbers (2 points each, 8 points in total)&lt;br /&gt;
#* Each function is given as a radio button choice (4 points)&lt;br /&gt;
#* The calculator page passes the W3C HTML validator (3 points)&lt;br /&gt;
#* '''''Make sure you have a README.md file in your individual repo with the the link to your calculator.''''' See the Creative Portion section for more information about .md files.&lt;br /&gt;
# '''File Sharing Site (40 Points):'''&lt;br /&gt;
#* '''''File Management (25 Points):'''''&lt;br /&gt;
#** Users should not be able to see any files until they enter a username and log in (4 points)&lt;br /&gt;
#**: ''Remember that users.txt should be stored in a secure location on your filesystem.  That is, '''you should not be able to type any URL into your browser and see the raw users.txt file!'''''&lt;br /&gt;
#** Users can see a list of all files they have uploaded (4 points)&lt;br /&gt;
#** Users can open files they have previously uploaded (5 points)&lt;br /&gt;
#**: ''Note: Users should be able to open not only plain text files but also other file formats: images, spreadsheets, etc.''&lt;br /&gt;
#** Users can upload files (4 points)&lt;br /&gt;
#**: ''Note: Like users.txt, uploaded files should be stored in a secure location on your filesystem.  That is, '''do not keep your uploads directory underneath a directory served by Apache!'''''&lt;br /&gt;
#** Users can delete files.  If a file is &amp;quot;deleted&amp;quot;, it should actually be removed from the filesystem (4 points)&lt;br /&gt;
#** The directory structure is hidden (2 points)&lt;br /&gt;
#** Users can log out (2 points)&lt;br /&gt;
#**: ''Note: If using session variables, you must ''actually'' log out the user by destroying their session; i.e., don't just redirect them to the login screen.''&lt;br /&gt;
#* '''''Best Practices (10 Points):'''''&lt;br /&gt;
#** Code is well formatted and easy to read, with proper commenting (4 points)&lt;br /&gt;
#** The site follows the FIEO philosophy (3 points)&lt;br /&gt;
#** All pages pass the W3C validator (3 points)&lt;br /&gt;
#* '''''Usability (5 Points):'''''&lt;br /&gt;
#** Site is intuitive to use and navigate (4 points)&lt;br /&gt;
#** Site is visually appealing (1 point)&lt;br /&gt;
# '''Creative Portion (15 Points)''' (see below)&lt;br /&gt;
#* '''''Make sure you have a README.md file in your group repo with the following:'''''&lt;br /&gt;
#** An .md file is a plain text file called a markdown file  [https://guides.github.com/features/mastering-markdown/ ] .  &lt;br /&gt;
#***The contents of your README.md file are shown on your repo, making it easier for us to grade&lt;br /&gt;
#*** You may style the page with bolding, hyperlings, images, block quotes and lists&lt;br /&gt;
#*** [http://dillinger.io/ This online markdown editor] makes it easy to learn this format  &lt;br /&gt;
#** The link to your file sharing site. '''''We need this to grade your work.'''''&lt;br /&gt;
#** A brief description of what you did for your creative portion&lt;br /&gt;
#** Any additional login details needed for the TA&lt;br /&gt;
&lt;br /&gt;
=== Creative Portion ===&lt;br /&gt;
&lt;br /&gt;
This module and all future modules will require that you invest some time into creating additional features for your group project.  Plan to invest at least 60 minutes of your time into the creative portion.&lt;br /&gt;
&lt;br /&gt;
* The creative portion is an opportunity for you to learn the material of your own interest.&lt;br /&gt;
* You will not earn credit for a creative-portion feature that simply rehashes something you've already done in a previous module.&lt;br /&gt;
&lt;br /&gt;
If you need ideas for a creative portion, or if you want to know whether or not your creative portion idea is &amp;quot;hard enough&amp;quot;, ask a TA.&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 2]]&lt;br /&gt;
[[Category:Modules]]&lt;/div&gt;</summary>
		<author><name>Alex</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Module_3&amp;diff=2503</id>
		<title>Module 3</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Module_3&amp;diff=2503"/>
		<updated>2018-02-12T17:44:03Z</updated>

		<summary type="html">&lt;p&gt;Alex: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;__NOTOC__&lt;br /&gt;
In Module 3, you will learn about MySQL, a web application database.&lt;br /&gt;
&lt;br /&gt;
This article contains your assignments for Module 3.&lt;br /&gt;
&lt;br /&gt;
== Reading ==&lt;br /&gt;
&lt;br /&gt;
The following articles on the online class wiki textbook contain information that will help you complete the assignments.&lt;br /&gt;
&lt;br /&gt;
* [[Introduction to MySQL]]&lt;br /&gt;
* [[MySQL Schema and State]]&lt;br /&gt;
* [[PHP and MySQL]]&lt;br /&gt;
* [[Web Application Security, Part 2]]&lt;br /&gt;
&lt;br /&gt;
== Individual Assignments ==&lt;br /&gt;
&lt;br /&gt;
You will create a simple grades database containing four tables.&lt;br /&gt;
&lt;br /&gt;
'''IMPORTANT:''' The individual assignment is to be done by writing queries by hand.  (You can use phpMyAdmin to run the queries, but '''do not let phpMyAdmin write your queries for you!''')  Writing your own queries gives you a greater understanding of the underlying mechanisms and databases in general.  Additionally, having SQL knowledge and experience is a very marketable trait.&lt;br /&gt;
&lt;br /&gt;
=== Install MySQL and phpMyAdmin ===&lt;br /&gt;
&lt;br /&gt;
Before you start, '''you need to install MySQL''' on your EC2 instance.  You may also install phpMyAdmin, a web frontend to MySQL, if you choose to do so.&lt;br /&gt;
&lt;br /&gt;
=== Set Up a Database ===&lt;br /&gt;
&lt;br /&gt;
You may find the following article to be very helpful: [[Introduction to MySQL]]&lt;br /&gt;
&lt;br /&gt;
# Create a database named '''wustl''' &lt;br /&gt;
# Create a user named '''wustl_inst''' and give them the password '''wustl_pass'''&lt;br /&gt;
&lt;br /&gt;
=== Create Tables ===&lt;br /&gt;
&lt;br /&gt;
You may find the following article to be very helpful: [[MySQL Schema and State]]&lt;br /&gt;
&lt;br /&gt;
When creating tables, keep the following items in mind:&lt;br /&gt;
&lt;br /&gt;
* You should create all tables such that they use the InnoDB storage engine, since we wish to make use of its support of foreign keys. In other database engines, foreign key constraints are not enforced.  (If you mess up, you can use ALTER TABLE to change the storage engine.)&lt;br /&gt;
* Where it is appropriate, you should take advantage of the ability to define fields NOT NULL so that you do not inadvertently insert incomplete data for a row.&lt;br /&gt;
&lt;br /&gt;
Create the following tables:&lt;br /&gt;
&lt;br /&gt;
# Create a table named '''students''' with the following fields:&lt;br /&gt;
#* '''id''' of an appropriately-sized unsigned integer type (we will never need to process more than a million students)&lt;br /&gt;
#* '''first_name''' of type '''VARCHAR(50)'''&lt;br /&gt;
#* '''last_name''' of type '''VARCHAR(50)'''&lt;br /&gt;
#* '''email_address''' of type '''VARCHAR(50)'''&lt;br /&gt;
#: The primary key should be on the '''id''' field.&lt;br /&gt;
# Create a table named '''departments''' with the following fields:&lt;br /&gt;
#* '''school_code''' of type '''ENUM''' (e.g. &amp;quot;L&amp;quot; for ArtSci and &amp;quot;E&amp;quot; for Engineering).  The options are as follows:&lt;br /&gt;
#*: 'L', 'B', 'A', 'F', 'E', 'T', 'I', 'W', 'S', 'U', 'M'&lt;br /&gt;
#* '''dept_id''' of an appropriately-sized unsigned integer type (in the foreseeable future there will never be more than 200 departments in a school)&lt;br /&gt;
#* '''abbreviation''' of type '''VARCHAR(9)''' (e.g. CSE, ChemE, etc)&lt;br /&gt;
#* '''dept_name''' of type '''VARCHAR(200)''' (e.g. Computer Science and Engineering)&lt;br /&gt;
#: The primary key should be on two fields: '''school_code''' and '''dept_id'''&lt;br /&gt;
#: '''Note:''' Why not just use the department ID for the primary key? The ID numbers are sometimes reused across schools. For instance, department 33 in The College of Arts and Sciences is Psychology while department 33 in The School of Engineering and Applied Sciences is Energy, Environmental and Chemical Engineering. Thus we must also include the school code to differentiate them  such that the record for  E33 is distinct from that of L33.&lt;br /&gt;
# Create a table named '''courses''' with the following fields:&lt;br /&gt;
#* '''school_code''' of type '''ENUM'''&lt;br /&gt;
#*: This should have the same letters in the same order as the '''school_code''' '''ENUM''' field in the '''departments''' table.&lt;br /&gt;
#* '''dept_id''' of the same size of integer as in the '''departments''' table&lt;br /&gt;
#* '''course_code''' of type '''CHAR(5)''' (this will hold course codes; e.g., '330S', '131', '2960')&lt;br /&gt;
#* '''name''' of type '''VARCHAR(150)'''&lt;br /&gt;
#: The appropriate fields in this table should make a foreign key reference to the corresponding fields in '''department'''.&lt;br /&gt;
#: In addition, it is up to you to determine the field(s) for the primary key.&lt;br /&gt;
#: '''Note:''' If you are unsure which fields to make the foreign keys and feel the need to beg your friends or the TAs to give you the answer, bang your head on your desk whilst repeating &amp;quot;I WILL EXERCISE REASON AND COMMON SENSE AND I WILL CURTAIL MY DESIRE TO BLINDLY FOLLOW DIRECTIONS&amp;quot;&lt;br /&gt;
#: ''Disclaimer: don't actually bang your head on your desk, the resulting head trauma may in fact make it harder for you to determine which fields should have associated foreign keys.''&lt;br /&gt;
# Create a table named '''grades''' with the following fields:&lt;br /&gt;
#* '''pk_grade_ID''' of an appropriately-sized unsigned integer type (should be larger than the one you chose for the '''students''' table). There will never be more than 1,000 grades per student.&lt;br /&gt;
#*: You should declare this field to be '''auto_increment''' and make it the primary key.&lt;br /&gt;
#*: This is called a ''surrogate key'' as opposed to a ''natural key'' because it doesn't arise &amp;quot;naturally&amp;quot; from the data; that is to say that it is not derived from application data. The use of surrogate keys vs. natural keys is a polemic issue amongst database designers.  For a decently unbiased take on the issue, see this page: http://www.agiledata.org/essays/keys.html#Comparison&lt;br /&gt;
#*: '''Food for thought:''' Aside from simply exposing you to the concept, can you think of any reasons why a surrogate key might be preferable for this table?  Alternatively, what attributes, if any, could you use as a natural key, and what might be the drawbacks of doing so?&lt;br /&gt;
#* '''student_id''' of the same integer (unsigned) type that you chose in the '''students''' table&lt;br /&gt;
#* '''grade''' of type '''decimal(5,2)'''&lt;br /&gt;
#* '''school_code''' of type '''ENUM'''&lt;br /&gt;
#*: Can you guess what entries to use for the enum?&lt;br /&gt;
#* '''dept_id''' of the same integer type that you've used for this field in other tables&lt;br /&gt;
#* '''course_code''' of the same type you chose for the course code in the '''courses''' table&lt;br /&gt;
#: The '''grades''' table should have foreign keys to both the '''students''' table and the '''courses''' table.&lt;br /&gt;
&lt;br /&gt;
=== Populate Tables ===&lt;br /&gt;
&lt;br /&gt;
Now, populate the tables by downloading the text files given below and loading them into the appropriate tables.&lt;br /&gt;
&lt;br /&gt;
'''Note:''' Do not insert all the values manually; instead, use the MySQL's ability to load in data from text files.&lt;br /&gt;
&lt;br /&gt;
You may find the following article to be very helpful: [[MySQL Schema and State]]&lt;br /&gt;
&lt;br /&gt;
The files containing the data are:&lt;br /&gt;
* students: http://classes.engineering.wustl.edu/cse330/content/students_data.txt&lt;br /&gt;
* courses: http://classes.engineering.wustl.edu/cse330/content/courses.txt&lt;br /&gt;
* departments: http://classes.engineering.wustl.edu/cse330/content/departments_data.txt&lt;br /&gt;
* grades: http://classes.engineering.wustl.edu/cse330/content/grades_data.txt&lt;br /&gt;
&lt;br /&gt;
=== Insert More Data ===&lt;br /&gt;
&lt;br /&gt;
Insert the following data into the tables that you have created and populated:&lt;br /&gt;
&lt;br /&gt;
# Insert entries for CSE 330S, CSE 131, and CSE 260M.&lt;br /&gt;
#: ''If you don't know CSE's department code, how can you find out using the tables in the database?''&lt;br /&gt;
# Insert the grades given for the students named below. &lt;br /&gt;
#* '''Ben Harper'''&lt;br /&gt;
#** E-mail: '''bharper@ffym.com'''&lt;br /&gt;
#** Student ID: '''88'''&lt;br /&gt;
#** Grades:&lt;br /&gt;
#*** 35.5 in CSE 330S&lt;br /&gt;
#*** 0 in CSE 131&lt;br /&gt;
#*** 95 in CSE 260M&lt;br /&gt;
#* '''Matt Freeman'''&lt;br /&gt;
#** E-mail: '''mfreeman@kickinbassist.net'''&lt;br /&gt;
#** Student ID: '''202'''&lt;br /&gt;
#** Grades:&lt;br /&gt;
#*** 100 in CSE 330S&lt;br /&gt;
#*** 90.5 in CSE 131&lt;br /&gt;
#*** 94.8 in CSE 260M&lt;br /&gt;
#* '''Marc Roberge'''&lt;br /&gt;
#** E-mail: '''mroberge@ofarevolution.us'''&lt;br /&gt;
#** Student ID: '''115'''&lt;br /&gt;
#** Grades:&lt;br /&gt;
#*** 75 in CSE 330S&lt;br /&gt;
#*** 37 in CSE 131&lt;br /&gt;
#*** 45.5 in CSE 260M&lt;br /&gt;
&lt;br /&gt;
=== Querying Your Database ===&lt;br /&gt;
&lt;br /&gt;
Now that you have a fully-functional, populated database, let's do some queries on it!&lt;br /&gt;
&lt;br /&gt;
Please Running the following &amp;lt;code&amp;gt;SELECT&amp;lt;/code&amp;gt; queries, then copy the output to a text file of the form &amp;lt;code&amp;gt;query1.txt&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;query2.txt&amp;lt;/code&amp;gt;, and so on, and commit them with the rest of your repository (be sure to include your query command and the entire response, including the number of results found). For each query, only the requested columns should be present. You will receive 0 points for any query that includes additional columns.&lt;br /&gt;
&lt;br /&gt;
# Select the entire grades table.&lt;br /&gt;
# Select all fields describing the courses offered in the College of Arts &amp;amp; Sciences (school code &amp;lt;code&amp;gt;L&amp;lt;/code&amp;gt;).&lt;br /&gt;
# The names, student IDs, and CSE330 grades of all students who are in CSE330S.&lt;br /&gt;
#: '''Note:''' This query should involve joins.  You don't need to use any aggregation functions.&lt;br /&gt;
# The names, e-mails, and average grades of any student with an average below 50 so that the dean can send them an email notification that they are now on academic probation.&lt;br /&gt;
#: ''You should be able to do this in only one query, without making any temporary tables.  You will need to use aggregation functions and the &amp;lt;code&amp;gt;HAVING&amp;lt;/code&amp;gt; keyword.''&lt;br /&gt;
# An individual report card for Jack Johnson, consisting of only his student ID, e-mail address, and average grade.&lt;br /&gt;
#: ''Again, you should be able to do this in just one query, using the correct combination of aggregation functions and joins.''&lt;br /&gt;
#: '''Note:''' Your query must look for students with the name &amp;quot;Jack Johnson&amp;quot; instead of hard-coding the student ID.&lt;br /&gt;
&lt;br /&gt;
== Group Project ==&lt;br /&gt;
&lt;br /&gt;
You will work in pairs on this project.  You may work with the same partner from Module 2, or change to someone else.&lt;br /&gt;
&lt;br /&gt;
'''Important Reminder:''' frequently commit your work to your Git repository as a backup!&lt;br /&gt;
&lt;br /&gt;
=== Simple News Web Site ===&lt;br /&gt;
&lt;br /&gt;
'''Examples:'''&lt;br /&gt;
* http://digg.com/&lt;br /&gt;
* http://slashdot.org/&lt;br /&gt;
&lt;br /&gt;
You should use '''PHP''' unless you get permission to use another web technology from the instructor.  You may also use phpMyAdmin to help set up databases.&lt;br /&gt;
&lt;br /&gt;
You may find this wiki article helpful: [[PHP and MySQL]]&lt;br /&gt;
&lt;br /&gt;
==== Requirements ====&lt;br /&gt;
&lt;br /&gt;
* Users can register for accounts and then log in to the website.&lt;br /&gt;
* Accounts should have both a username and a ''secure'' password.  '''NEVER store plaintext passwords in a database!'''&lt;br /&gt;
*: For more information on password security, refer to [[Web Application Security, Part 2#Password Security|the Web Application Security guide]].&lt;br /&gt;
* Registered users can submit story commentary.&lt;br /&gt;
*: A link can be associated with each story, and they should be stored in a separate database field from the story&lt;br /&gt;
* Registered users can comment on any story.&lt;br /&gt;
* Unregistered users can only view stories and comments.&lt;br /&gt;
* Registered users can edit and delete their stories and comments.&lt;br /&gt;
* All data must be kept in a MySQL database (user information, stories, comments, and links).&lt;br /&gt;
* Creative Portion&lt;br /&gt;
&lt;br /&gt;
=== Web Security and Validation ===&lt;br /&gt;
&lt;br /&gt;
No application is finished until much thought is put into web security and best practice.  Throughout this course, we heavily emphasize the dogma of [http://coderesponsibly.org/ responsible] coding.&lt;br /&gt;
&lt;br /&gt;
Read this week's Web Application Security guide: [[Web Application Security, Part 2]].  In particular, your project needs to:&lt;br /&gt;
&lt;br /&gt;
* '''Your application needs to be secure against SQL injection attacks'''. If you are using prepared queries, you should already be safe on this front.&lt;br /&gt;
* '''Your passwords need to be securely hashed salted''' to prevent rainbow table attacks.&lt;br /&gt;
* '''You should pass tokens in forms''' to prevent CSRF attacks.&lt;br /&gt;
* '''You should check all preconditions on the server side''' to prevent Abuse of Functionality attacks.&lt;br /&gt;
&lt;br /&gt;
You shouldn't forget the practices you learned last week:&lt;br /&gt;
&lt;br /&gt;
* '''Your page should validate''' with no errors through the W3C validator.&lt;br /&gt;
* '''Filter Input and Escape Output''', but not the other way around.&lt;br /&gt;
&lt;br /&gt;
== Grading ==&lt;br /&gt;
&lt;br /&gt;
We will be grading the following aspects of your work.  There are 100 points total.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Assignments (including code) must be committed to Bitbucket by the end of class on the due date (commit early and often). Failing to commit by the end of class on the due date will result in a 0. ''' &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''If you do not include a link to your group portion running on your instance in your group portion README.md, you will receive a 0 for the group portion.''' &lt;br /&gt;
________&lt;br /&gt;
&lt;br /&gt;
# '''MySQL Queries (25 Points):'''&lt;br /&gt;
#* A MySQL server is running on your instance (2 points)&lt;br /&gt;
#* Tables' fields, including data types and foreign keys, are correct (8 points)&lt;br /&gt;
#*: ''Note: To demonstrate the structure of your tables, you should commit a file containing the output of the &amp;lt;code&amp;gt;SHOW CREATE TABLE&amp;lt;/code&amp;gt; command '''for each table.''' Each table's file should have a name of the form &amp;lt;code&amp;gt;tablename.sql&amp;lt;/code&amp;gt; (e.g. &amp;lt;code&amp;gt;students.sql&amp;lt;/code&amp;gt;).''&lt;br /&gt;
#* The output of each of the five queries is correct. (3 points each)&lt;br /&gt;
#*: ''Note: To demonstrate the output of your queries, text files containing the 'entire' result (including the number of record found) of running each query should committed to BitBucket. The file for query 1 should be named &amp;lt;code&amp;gt;query1.txt&amp;lt;/code&amp;gt;, the file for query 2 should be named &amp;lt;code&amp;gt;query2.txt&amp;lt;/code&amp;gt;, and so on.''&lt;br /&gt;
# '''News Site (60 Points):'''&lt;br /&gt;
#* '''''User Management (20 Points):'''''&lt;br /&gt;
#** A session is created when a user logs in (3 points)&lt;br /&gt;
#** New users can register (3 points)&lt;br /&gt;
#** Passwords are hashed, salted, and checked securely (3 points)&lt;br /&gt;
#**: ''Note: You will receive 0 points for this section if you use the &amp;lt;code&amp;gt;==&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;===&amp;lt;/code&amp;gt; operators to compare password hashes, or if you use the &amp;lt;code&amp;gt;crypt&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;md5&amp;lt;/code&amp;gt; functions at any point.''&lt;br /&gt;
#** Users can log out (3 points)&lt;br /&gt;
#** A user can edit and delete his/her own stories and comments but cannot edit or delete the stories or comments of another user (8 points)&lt;br /&gt;
#* '''''Story and Comment Management (20 Points):'''''&lt;br /&gt;
#** Relational database is configured with correct data types and foreign keys (4 points)&lt;br /&gt;
#*: ''Note: To demonstrate the structure of your database, you should commit a 'single' text file containing the output of the &amp;lt;code&amp;gt;SHOW CREATE TABLE&amp;lt;/code&amp;gt; command '''for all tables in your database,''' called &amp;lt;code&amp;gt;tables.sql&amp;lt;/code&amp;gt;. This one file should contain the output for all of your tables.&lt;br /&gt;
#** Stories can be posted (3 points)&lt;br /&gt;
#** A link can be associated with each story, and is stored in a separate database field from the story (3 points)&lt;br /&gt;
#** Comments can be posted in association with a story (4 points)&lt;br /&gt;
#** Stories can be edited and deleted (3 points)&lt;br /&gt;
#** Comments can be edited and deleted (3 points)&lt;br /&gt;
#**: ''Note: Although there are only 6 points allocated for editing/deleting in this section, there are 8 more points at stake in the User Management section that cannot be earned unless editing/deleting is implemented.  Implementing editing but not deleting, or vice-versa, will result in earning half the points.''&lt;br /&gt;
#* '''''Best Practices (15 Points):'''''&lt;br /&gt;
#** Code is well formatted and easy to read, with proper commenting (3 points)&lt;br /&gt;
#** Safe from SQL Injection attacks (2 points)&lt;br /&gt;
#** Site follows the FIEO philosophy (3 points)&lt;br /&gt;
#** All pages pass the W3C HTML and CSS validators (2 points)&lt;br /&gt;
#** CSRF tokens are passed when creating, editing, and deleting comments and stories (5 points)&lt;br /&gt;
#* '''''Usability (5 Points):'''''&lt;br /&gt;
#** Site is intuitive to use and navigate (4 points)&lt;br /&gt;
#** Site is visually appealing (1 point)&lt;br /&gt;
# '''Creative Portion (15 Points)''' (see below)&lt;br /&gt;
#* '''''Make sure you have a README.md file in your group repo with the following:'''''&lt;br /&gt;
#** Names and Student IDs of all the group members&lt;br /&gt;
#** A link to your homepage of the site&lt;br /&gt;
#** A brief description of what you did for your creative portion&lt;br /&gt;
#** Any additional login details needed for the TA&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 3]]&lt;br /&gt;
[[Category:Modules]]&lt;/div&gt;</summary>
		<author><name>Alex</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=JavaScript&amp;diff=2502</id>
		<title>JavaScript</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=JavaScript&amp;diff=2502"/>
		<updated>2018-02-05T18:13:25Z</updated>

		<summary type="html">&lt;p&gt;Alex: /* Events */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;JavaScript is the most widely used scripting language for implementing client-side functionality in Web applications, and, in recent years, it's become very popular for server-side application, too.  Unlike PHP, JavaScript code can be interpreted and executed in a client's web browser, instead of on the web server, depending on how it's being used.&lt;br /&gt;
&lt;br /&gt;
== JavaScript?  Did you mean Java? ==&lt;br /&gt;
&lt;br /&gt;
'''JavaScript''' is a prototype-based programming language focused on web interactivity.  It was first introduced in Netscape Navigator, and it in turn gave rise to what is now '''[http://www.ecmascript.org/ ECMAScript]'''.  Originally, JavaScript was called &amp;quot;LiveScript&amp;quot;.  Sun, the developer of Java at the time, wanted a language that would complement its compiled Java language, and so LiveScript was renamed JavaScript.&lt;br /&gt;
&lt;br /&gt;
Beyond that, '''Java and JavaScript are as similar as Ham and Hamster.'''&lt;br /&gt;
&lt;br /&gt;
Java and JavaScript have similar syntax, but the under workings are quite different.  For example, Java requires strict typing, but JavaScript allows for dynamic typing.  Java is object-oriented, but JavaScript is prototype-oriented.  Java is compiled, but JavaScript is interpreted.  Java supports event listeners, but JavaScript makes them a fundamental part of the language.  Java variables are scoped to the innermost method or loop, but JavaScript variables are scoped only to the innermost function.&lt;br /&gt;
&lt;br /&gt;
== JavaScript Language Components ==&lt;br /&gt;
&lt;br /&gt;
This section highlights some features of the JavaScript language that differentiate it from other languages.  For a more comprehensive JavaScript tutorial, the following tutorials are both quality:&lt;br /&gt;
&lt;br /&gt;
* [https://webplatform.github.io/ WebPlatform]: Great for learning JavaScript for the first time.  Advocates best practices for modern JavaScript development.&lt;br /&gt;
* [http://www.quirksmode.org/js/contents.html QuirksMode]: More advanced than the WebPlatform tutorial, but it thoroughly covers the most powerful aspects of pure JavaScript and gives unparalleled advice on browser compatibility.&lt;br /&gt;
&lt;br /&gt;
Advice: Do '''NOT''' Google for &amp;quot;JavaScript Tutorial&amp;quot;.  The first few hits advocate bad or outdated practices.  Stick with the ones listed here.&lt;br /&gt;
&lt;br /&gt;
=== Variables and Scope ===&lt;br /&gt;
&lt;br /&gt;
To define a variable in JavaScript, use the '''let''' keyword.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
let foo = &amp;quot;bar&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To define a constant in JavaScript, use the '''const''' keyword.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
const foo = &amp;quot;bar&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
All variables are objects.  In the case above, the variable '''foo''' is an object of the class '''String'''.&lt;br /&gt;
&lt;br /&gt;
Notice that like PHP, you do not have to explicitly define a type for a variable like '''int''' or '''String'''; this is because JavaScript and PHP are ''dynamically typed languages''.&lt;br /&gt;
&lt;br /&gt;
JavaScript code can access any variable higher in the “function tree”, but not vice-versa.  This is called '''scope'''.  ''All functions create their own scope.''&lt;br /&gt;
&lt;br /&gt;
When you reference a variable, JavaScript will look up through the &amp;quot;function tree&amp;quot; until it finds the variable you asked for.  This means that you could define variables of the same name as global variables inside of functions.  For demonstration of concept:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
const a = &amp;quot;hello&amp;quot;;&lt;br /&gt;
const b = &amp;quot;world&amp;quot;;&lt;br /&gt;
&lt;br /&gt;
function sayGoodByeWorld(){&lt;br /&gt;
	const a = &amp;quot;goodbye&amp;quot;;&lt;br /&gt;
&lt;br /&gt;
	alert(a); // goodbye&lt;br /&gt;
	alert(b); // world&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
sayGoodByeWorld();&lt;br /&gt;
&lt;br /&gt;
alert(a); // hello&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Object Literals ===&lt;br /&gt;
&lt;br /&gt;
A very common way of storing and transporting data in JavaScript is by using objects.  You can define an object with certain properties using an '''object literal''':&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
const apple = {&lt;br /&gt;
	color: &amp;quot;red&amp;quot;,&lt;br /&gt;
	flavor: &amp;quot;sweet&amp;quot;,&lt;br /&gt;
	season: &amp;quot;autumn&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
alert(apple.color);  // red&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Functions ===&lt;br /&gt;
&lt;br /&gt;
To define a function in JavaScript, use the '''function''' keyword.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
function sayHello(){&lt;br /&gt;
	alert(&amp;quot;Hello World&amp;quot;);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
sayHello(); // call the function&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Pass an argument to a function like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
function sayHello(name){&lt;br /&gt;
	alert(&amp;quot;Hello, &amp;quot;+name);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
sayHello(&amp;quot;Todd&amp;quot;); // call the function and pass an argument&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Functions are Objects ====&lt;br /&gt;
&lt;br /&gt;
In JavaScript, functions are objects.  This means that they can be assigned to variables, manipulated on the fly, and even passed as arguments to other functions!  '''''This is an extremely important feature of JavaScript''''' that makes it such a robust language for web development.&lt;br /&gt;
&lt;br /&gt;
You create a function variable like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
const sayHello = function(){&lt;br /&gt;
	alert(&amp;quot;Hello World&amp;quot;);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
sayHello(); // call the function&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Observe that you can make [[#Variables and Scope|scope-dependent]] functions in this way.&lt;br /&gt;
&lt;br /&gt;
=== Closures ===&lt;br /&gt;
&lt;br /&gt;
{{DoctypeTV&lt;br /&gt;
|youtube_id=HaPlj796ngQ&lt;br /&gt;
|time=5m45s&lt;br /&gt;
|desc=JavaScript Closures&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
A '''closure''' is a way to separate a certain snippet of JavaScript code from the global scope.  This is useful if you do not want to &amp;quot;muck up&amp;quot; global variables.  Closures are nothing more than anonymous functions that are called as soon as they are created:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
const a = &amp;quot;hello&amp;quot;;&lt;br /&gt;
&lt;br /&gt;
(​​​​function(){&lt;br /&gt;
	const b = &amp;quot;world&amp;quot;;&lt;br /&gt;
	&lt;br /&gt;
	alert(a); // hello&lt;br /&gt;
	alert(b); // world&lt;br /&gt;
})();&lt;br /&gt;
&lt;br /&gt;
alert(a); // hello&lt;br /&gt;
alert(b);​ // ReferenceError: b is not defined​​​​​​​​​​​​​​​&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{JSFiddleExample&lt;br /&gt;
|title=Passing Variables to a Closure&lt;br /&gt;
|desc=This example demonstrates how you can &amp;quot;save&amp;quot; previous versions of a variable using closures.  This is possible because of scoping and the fact that function variables can be returned as objects.&lt;br /&gt;
|fiddle_id=YURqa&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
Most JavaScript libraries (like jQuery) write all of their code in a closure.  What this means is that except for one or two variable names (jQuery or $), everything associated with the library is completely self-contained.&lt;br /&gt;
&lt;br /&gt;
=== Prototypal Inheritance ===&lt;br /&gt;
&lt;br /&gt;
JavaScript implements '''prototypal inheritance''', as opposed to a language like Java or C++, which implements '''classical inheritance'''.  JavaScript is one of only a handful of languages implementing prototype-based inheritance.&lt;br /&gt;
&lt;br /&gt;
Here's how it works.  Every callable object (function) has a '''prototype'''.  When instances of that object are created, their properties and methods are copied (inherited) from the prototype.  Additionally, changes made to the prototype later in the program are &amp;quot;copied&amp;quot; to every instance.&lt;br /&gt;
&lt;br /&gt;
For example, if you wanted to make a method on all strings that added a “!”, you could modify String’s prototype:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
String.prototype.bang = function(){&lt;br /&gt;
	return this+&amp;quot;!&amp;quot;; // Notice: the context is the instance itself&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
alert(&amp;quot;Hello&amp;quot;.bang()); // alerts Hello!&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To &amp;quot;extend&amp;quot; an object, just copy its prototype to a new object.  However, since classical inheritance and prototypal inheritance are different concepts, copying prototypes may have results that you don't expect.  [http://beej.us/blog/data/javascript-prototypes-inheritance/ This article] seems to have a pretty good explanation of how to &amp;quot;inherit&amp;quot; prototypes with example implementations.&lt;br /&gt;
&lt;br /&gt;
==== Extending Built-In Prototypes ====&lt;br /&gt;
&lt;br /&gt;
You should be aware that there is an active debate in the web development community about whether it is good programming style to extend the prototypes of built-in objects like String and Array, such as in the ''String.prototype.bang'' example above.  There are legitimate arguments on both sides.  [http://stackoverflow.com/questions/8859828/javascript-what-dangers-are-in-extending-array-prototype This Stack Overflow post] has good links to some articles discussing this issue.&lt;br /&gt;
&lt;br /&gt;
=== Context ===&lt;br /&gt;
&lt;br /&gt;
{{DoctypeTV&lt;br /&gt;
|youtube_id=0a4r4bm1nQA&lt;br /&gt;
|time=4m32s&lt;br /&gt;
|desc=The ''this'' Variable in JavaScript&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
Every function is called on a certain object, which is not necessarily the same object in which it was defined.  This is called '''context'''.&lt;br /&gt;
&lt;br /&gt;
To call a function on an arbitrary context, use either '''call''' or '''apply'''.  ''call'' takes a list of arguments, while ''apply'' takes them all in an array.&lt;br /&gt;
&lt;br /&gt;
To access the current context, use the '''this''' keyword.  Demonstration of concept:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
const sayThisColor = function(){&lt;br /&gt;
	alert(this.color);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
const apple = { color: &amp;quot;red&amp;quot; }&lt;br /&gt;
&lt;br /&gt;
sayThisColor();   // undefined&lt;br /&gt;
sayThisColor.call(apple); // red&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Events ==&lt;br /&gt;
&lt;br /&gt;
Events are really what make JavaScript such a powerful language for web development.&lt;br /&gt;
&lt;br /&gt;
Rather than being thread based, JavaScript is event based.  Since all JavaScript code runs in a single thread, '''there are no concurrency issues'''.  When an event occurs, JavaScript automatically calls the ''event callback'' as soon as all previous events' callbacks have finished executing.&lt;br /&gt;
&lt;br /&gt;
Code in the form of a '''callback function''' is associated with events via a '''listener'''.  For example, the following JavaScript causes ''sayHello()'' (the callback function) to be run whenever the button with ID &amp;quot;hello&amp;quot; is clicked (the event):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
const sayHello = function(){&lt;br /&gt;
	alert(&amp;quot;Hello World&amp;quot;);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
document.getElementById(&amp;quot;hello&amp;quot;).addEventListener(&amp;quot;click&amp;quot;, sayHello, false);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{JSFiddleExample&lt;br /&gt;
|title=Binding Callbacks to a Button Click&lt;br /&gt;
|fiddle_id=L8c4Z&lt;br /&gt;
|cse330=true&lt;br /&gt;
|desc=In this example, notice how we bind the callback function when the ''DOMContentLoaded'' event fires.  This is because JavaScript requires that the button has been parsed by the browser before it can add event listeners to it.&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
The '''addEventListener''' method takes three parameters:&lt;br /&gt;
* The event type&lt;br /&gt;
* The callback function&lt;br /&gt;
*: The callback function is passed one parameter: the event object.&lt;br /&gt;
* A boolean representing bubble (false) or capture (true) phase&lt;br /&gt;
*: You usually want Bubble phase.  For more information on event phase, see [[#Event Phase]]&lt;br /&gt;
&lt;br /&gt;
Note that versions of Internet Explorer prior to version 9 required that you use a different, albeit similar, function for assigning event listeners called '''attachEvent'''.  attachEvent takes the same arguments as addEventListener, except you need to put '''on''' before the event type (e.g. &amp;quot;onclick&amp;quot;), and the third argument (phase) is not necessary.&lt;br /&gt;
&lt;br /&gt;
It is perfectly valid to use an '''anonymous function''' as your callback function:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
document.getElementById(&amp;quot;hello&amp;quot;).addEventListener(&amp;quot;click&amp;quot;, function(event){&lt;br /&gt;
	alert(`Hello, World!  Event Type: ${event.type}`);&lt;br /&gt;
}, false);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
QuirksMode has perhaps the best series of articles about the ins and outs of JavaScript events on the internet: http://www.quirksmode.org/js/contents.html#events&lt;br /&gt;
&lt;br /&gt;
=== The Event Object ===&lt;br /&gt;
&lt;br /&gt;
Callback functions are passed one argument: an ''event object''.  You see above that one property of the event object is ''event.type''.  To see the full list of properties of the event object, you could run the code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
document.getElementById(&amp;quot;my_btn&amp;quot;).addEventListener(&amp;quot;click&amp;quot;, function(event){&lt;br /&gt;
	let strout = &amp;quot;&amp;quot;;&lt;br /&gt;
	for(var i in event){&lt;br /&gt;
		strout += `${i}: ${event[i]}\n`;&lt;br /&gt;
	}&lt;br /&gt;
	console.log(strout);&lt;br /&gt;
}, false);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Some of the most useful properties and methods include:&lt;br /&gt;
* '''event.target''' references the object on which the event occurred.&lt;br /&gt;
* '''event.currentTarget''' references the object whose listener is currently being processed.&lt;br /&gt;
*: ''Note:'' event.target and event.currentTarget might be the same or might be different, depending on whether you are listening for bubbled events.&lt;br /&gt;
* '''event.preventDefault()''' stops the normal result of the event from being executed.  For example, if you listen for a form's ''submit'' event, you can call event.preventDefault() to stop the form from being submitted.&lt;br /&gt;
* '''event.stopPropagation()''' prevents any other event listeners from being executed.  For more detail, read the section on Event Phase below.&lt;br /&gt;
&lt;br /&gt;
For more detail on the event object, see [http://dev.w3.org/2006/webapi/DOM-Level-3-Events/html/DOM3-Events.html#interface-Event the W3C specification].&lt;br /&gt;
&lt;br /&gt;
'''Note:''' If your callback function does not take any parameters, it will still run; you just won't have as easy of access to the event object.&lt;br /&gt;
&lt;br /&gt;
=== Event Handlers and Memory Management ===&lt;br /&gt;
&lt;br /&gt;
JavaScript is an automatically garbage-collected language, meaning that memory management is mostly taken care of for you.  However, there are some instances when you need to be careful about creating &amp;quot;zombie&amp;quot; objects.  In JavaScript, this mostly revolves around the idea of event listeners.&lt;br /&gt;
&lt;br /&gt;
I could give an explanatory example, but instead I'll tell you straightaway that '''the moral of the story is that for every &amp;quot;addEventListener&amp;quot;, there should probably be a &amp;quot;removeEventListener&amp;quot;.'''  Here are some good articles to satisfy your hunger for more details on event listeners and JavaScript memory management:&lt;br /&gt;
&lt;br /&gt;
* http://www.vladalexandruionescu.com/2012/08/javascript-memory-leaks.html&lt;br /&gt;
* http://lostechies.com/derickbailey/2012/03/19/backbone-js-and-javascript-garbage-collection/&lt;br /&gt;
* http://stackoverflow.com/questions/5326300/garbage-collection-with-node-js&lt;br /&gt;
&lt;br /&gt;
When you start working with Node.JS in the next module, it's more important than ever to keep good accounting of your event listeners.&lt;br /&gt;
&lt;br /&gt;
=== Event Phase ===&lt;br /&gt;
&lt;br /&gt;
In JavaScript, events occur in two phases: '''Capture Phase''' and '''Bubble Phase'''.  Consider the following HTML document:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE html&amp;gt;&lt;br /&gt;
&amp;lt;html&amp;gt;&lt;br /&gt;
&amp;lt;head&amp;gt;&amp;lt;title&amp;gt;Event Test&amp;lt;/title&amp;gt;&amp;lt;/head&amp;gt;&lt;br /&gt;
&amp;lt;body&amp;gt;&lt;br /&gt;
  &amp;lt;div id=&amp;quot;box&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;button id=&amp;quot;btn&amp;quot;&amp;gt;&lt;br /&gt;
      Hello&lt;br /&gt;
    &amp;lt;/button&amp;gt;&lt;br /&gt;
  &amp;lt;/div&amp;gt;&lt;br /&gt;
&amp;lt;/body&amp;gt;&lt;br /&gt;
&amp;lt;/html&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Suppose the user clicks on the &amp;quot;Hello&amp;quot; button.  Events will be fired in the following order:&lt;br /&gt;
&lt;br /&gt;
# Capture Phase CLICK on the Document&lt;br /&gt;
# Capture Phase CLICK on the Body&lt;br /&gt;
# Capture Phase CLICK on the Div#box&lt;br /&gt;
# Target Phase CLICK on the Button#btn&lt;br /&gt;
# Bubble Phase CLICK on the Div#box&lt;br /&gt;
# Bubble Phase CLICK on the Body&lt;br /&gt;
# Bubble Phase CLICK on the Document&lt;br /&gt;
&lt;br /&gt;
{{JSFiddleExample&lt;br /&gt;
|title=Using Capture Phase to Enable or Disable a Toolbar&lt;br /&gt;
|fiddle_id=r32Dz&lt;br /&gt;
|desc=We bind an event in the capture phase to the div with ID ''toolbar''.  When ''e.stopPropagation()'' is called, the event does not reach the buttons in the toolbar.&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
Graphically, here is the order in which an event occurs in three generic nested elements:&lt;br /&gt;
&lt;br /&gt;
[[File:EventPhase.gif]]&lt;br /&gt;
&lt;br /&gt;
Why is this useful?  Suppose you have a control panel (toolbar, etc) that you want to temporarily deactivate.  (For example, Bold/Italic/Underline buttons on a graphic text editor that currently has no content.)  You could keep bubble phase event listeners on your buttons, but prevent those events from occurring by stopping the event in the capture phase on the parent element before the event reaches your buttons!  Example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
const disableToolbarFunc = function(e){&lt;br /&gt;
	e.stopPropogation();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
// To disable toolbar:&lt;br /&gt;
document.getElementById(&amp;quot;box&amp;quot;).addEventListener(&amp;quot;click&amp;quot;, disableToolbarFunc, true);&lt;br /&gt;
&lt;br /&gt;
// To re-enable toolbar:&lt;br /&gt;
document.getElementById(&amp;quot;box&amp;quot;).removeEventListener(&amp;quot;click&amp;quot;, disableToolbarFunc, true);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Word of caution:''' Like many great things in web development, capture phase does not work in versions of Internet Explorer prior to version 9.  There is no elegant substitution for older versions of Internet Explorer.&lt;br /&gt;
&lt;br /&gt;
'''Note:''' When the event reaches the innermost element, there is no distinction between capture phase and bubble phase.  The order in which event handlers were added to the element determines the order in which those callbacks are evaluated.&lt;br /&gt;
&lt;br /&gt;
== Document Object Model ==&lt;br /&gt;
&lt;br /&gt;
The '''Document Object Model (DOM)'''  is what enables JavaScript to manipulate the content of your web page.&lt;br /&gt;
&lt;br /&gt;
=== Nodes and Traversing the DOM ===&lt;br /&gt;
&lt;br /&gt;
Each element on your page, whether it is a &amp;lt;nowiki&amp;gt;&amp;lt;p&amp;gt;, &amp;lt;img/&amp;gt;&amp;lt;/nowiki&amp;gt;, a string of text, or even an attribute, is called a '''node'''.&lt;br /&gt;
&lt;br /&gt;
Every node, except for the document itself, has exactly one parent.  A single node may have multiple children.&lt;br /&gt;
&lt;br /&gt;
Consider the following HTML code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;ul id=&amp;quot;my-list&amp;quot;&amp;gt;&lt;br /&gt;
	&amp;lt;li class=&amp;quot;fruits&amp;quot;&amp;gt;Apples&amp;lt;/li&amp;gt;&lt;br /&gt;
	&amp;lt;li class=&amp;quot;citrus&amp;quot;&amp;gt;Oranges and &amp;lt;strong&amp;gt;Lemons&amp;lt;/strong&amp;gt;&amp;lt;/li&amp;gt;&lt;br /&gt;
	&amp;lt;li class=&amp;quot;berries&amp;quot;&amp;gt;Cherries&amp;lt;/li&amp;gt;&lt;br /&gt;
&amp;lt;/ul&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here, the ul with ID &amp;quot;my-list&amp;quot; has three child '''element nodes''' (the three li's) as well as four child '''text nodes''' (the whitespace counts as a text node) and a child '''attribute node'''.  The second LI has one child '''text node''' as well as one child '''element node''' and one child '''attribute node'''.&lt;br /&gt;
&lt;br /&gt;
The DOM can be traversed in JavaScript.  First, let's look at an example.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
e = document.getElementById(&amp;quot;my-list&amp;quot;).getElementsByClassName(&amp;quot;citrus&amp;quot;)[0].lastChild.nodeName;&lt;br /&gt;
alert(e);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{JSFiddleExample&lt;br /&gt;
|title=Currently Selected Radio Button&lt;br /&gt;
|fiddle_id=SHcng&lt;br /&gt;
|desc=In pure JavaScript, in order to determine the currently selected radio button, it is necessary to iterate over an array of pointers to all possible radio buttons, and stop when you find one that is &amp;quot;checked&amp;quot;.&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
The above snippet gets the element with class name '''citrus''' that is a child of the element with ID '''my-list''' (the second LI in the example above), and alerts the type of its second child node (which in this case is '''STRONG''').&lt;br /&gt;
&lt;br /&gt;
Some common methods for traversing the DOM include:&lt;br /&gt;
&lt;br /&gt;
* Node.parentNode&lt;br /&gt;
* Node.childNodes - returns an array of nodes&lt;br /&gt;
* Node.firstChild - same as Node.childNodes[0]&lt;br /&gt;
* Node.lastChild - same as Node.childNodes[Node.childNodes.length-1]&lt;br /&gt;
* Node.previousSibling&lt;br /&gt;
* Node.nextSibling&lt;br /&gt;
&lt;br /&gt;
You can also search for child (including all descendants) using one of the following methods:&lt;br /&gt;
&lt;br /&gt;
* Node.getElementsByTagName(&amp;quot;tag-name&amp;quot;) - returns an array of element nodes having the tag name '''tag-name''' that are descendants of Node&lt;br /&gt;
* Node.getElementById(&amp;quot;id&amp;quot;) - returns a single node having the ID '''id''' that is a descendant of Node&lt;br /&gt;
* Node.getElementsByName(&amp;quot;what-name&amp;quot;) - returns an array of element nodes having their '''name''' attribute set to '''what-name'''.  Useful for radio buttons and other form elements.&lt;br /&gt;
* Node.getElementsByClassName(&amp;quot;class&amp;quot;) - returns an array of nodes having the class '''class'''&lt;br /&gt;
*: '''Note:''' As of October 2012, 82% of the browser market supports Node.getElementsByClassName ([http://caniuse.com/getelementsbyclassname more info]).  In order to support the other 18%, you need to either add your own getElementsByClassName to Node's prototype or use a JavaScript library like jQuery or MooTools.&lt;br /&gt;
&lt;br /&gt;
It is common in JavaScript to have long statements like the one in the example above, where you call methods on several objects in sequence.&lt;br /&gt;
&lt;br /&gt;
=== Creating, Moving, and Removing Nodes ===&lt;br /&gt;
&lt;br /&gt;
You will frequently find yourself wanting to modify the DOM.  JavaScript provides methods that help you do this.&lt;br /&gt;
&lt;br /&gt;
Consider the same HTML as above.  If you wanted to add another element to the list, you could use this code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
const newLi = document.createElement(&amp;quot;li&amp;quot;);  // creates a node with the tag name li&lt;br /&gt;
newLi.appendChild(document.createTextNode(&amp;quot;Broccoli&amp;quot;));&lt;br /&gt;
newLi.setAttribute(&amp;quot;class&amp;quot;, &amp;quot;veggies&amp;quot;);&lt;br /&gt;
document.getElementById(&amp;quot;my-list&amp;quot;).appendChild(newLi);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If you wanted to remove the apples from the list, you could do:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
const apple = document.getElementById(&amp;quot;my-list&amp;quot;).getElementsByClassName(&amp;quot;fruits&amp;quot;)[0];&lt;br /&gt;
document.getElementById(&amp;quot;my-list&amp;quot;).removeChild(apple);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If you wanted to move the apples to the end of the list, you could do this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
const apple = document.getElementById(&amp;quot;my-list&amp;quot;).getElementsByClassName(&amp;quot;fruits&amp;quot;)[0];&lt;br /&gt;
document.getElementById(&amp;quot;my-list&amp;quot;).appendChild(apple);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Notice that '''Node.append()''' both removes a node from its previous location ''and'' appends it to its new location, which is always going to be as the last child of the parent node.&lt;br /&gt;
&lt;br /&gt;
In summary, here are the methods to know from this section:&lt;br /&gt;
&lt;br /&gt;
* Node.append(otherNode) - removes otherNode from its current location in the DOM (if applicable) and then adds it as the last child of Node&lt;br /&gt;
* Node.removeChild(otherNode) - removes otherNode, a child of Node, from the DOM&lt;br /&gt;
* document.createElement(&amp;quot;tag-name&amp;quot;) - create a new node with the tag name &amp;quot;tag-name&amp;quot;&lt;br /&gt;
* document.createTextNode(&amp;quot;text&amp;quot;) - create a node containing only the string '''text'''&lt;br /&gt;
* Node.setAttribute(&amp;quot;attribute&amp;quot;, &amp;quot;value&amp;quot;) - sets the attribute node of name &amp;quot;attribute&amp;quot; to &amp;quot;value&amp;quot;&lt;br /&gt;
&lt;br /&gt;
=== DOM Shortcuts ===&lt;br /&gt;
&lt;br /&gt;
In the above sections, we have been creating, reading, modifying, and deleting Nodes.  This is the most &amp;quot;correct&amp;quot; way to change the content of a web page from inside JavaScript.&lt;br /&gt;
&lt;br /&gt;
This section documents a few shortcuts that are not as &amp;quot;pure&amp;quot; as using Nodes but can be less confusing and cumbersome.&lt;br /&gt;
&lt;br /&gt;
{{JSFiddleExample&lt;br /&gt;
|title=Displaying Information&lt;br /&gt;
|fiddle_id=Q3BPZ&lt;br /&gt;
|desc=This example shows how to use some of the shortcut methods for using JavaScript to display information on the page.&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
==== textContent ====&lt;br /&gt;
&lt;br /&gt;
Using textContent to display information is probably the easiest method out there.  For example, the following code overwrites whatever is in the element with ID &amp;quot;holder&amp;quot; with the string &amp;quot;Hello World&amp;quot;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
document.getElementById(&amp;quot;holder&amp;quot;).textContent = &amp;quot;Hello World&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If you wanted to instead append the text, simply use '''+=''' instead of '''=''':&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
document.getElementById(&amp;quot;holder&amp;quot;).textContent += &amp;quot; -  Later, he said Hello World  - &amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note that textContent displays strings literally; that is, it does not allow for HTML.  Setting the textContent property also removes any HTML that may have already been in that element.&lt;br /&gt;
&lt;br /&gt;
==== innerHTML ====&lt;br /&gt;
&lt;br /&gt;
If you need to use HTML in your output but don't want to use the method described earlier in this section, a straightforward strategy is to use the innerHTML property of an element. For example, the following code would add a paragraph saying &amp;quot;Hello World&amp;quot; to the element with ID &amp;quot;holder&amp;quot;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
document.getElementById(&amp;quot;holder&amp;quot;).innerHTML += &amp;quot;&amp;lt;p&amp;gt;Hello World&amp;lt;/p&amp;gt;&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Important:''' You need to be careful to prevent XSS-type attacks if you display information using innerHTML.  For example, be sure to escape a user-supplied string before appending it to innerHTML.&lt;br /&gt;
&lt;br /&gt;
=== JavaScript Inspectors ===&lt;br /&gt;
&lt;br /&gt;
{{DoctypeTV&lt;br /&gt;
|youtube_id=PKzrmbN-pMg&lt;br /&gt;
|time=4m13s&lt;br /&gt;
|desc=Using Firebug, WebKit Inspector, and IE Developer Tools&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
Various browsers and browser plugins give you, the developer, tools to debug your code, inspect the DOM, and much more.  Using these tools is essential for an efficient workflow.&lt;br /&gt;
&lt;br /&gt;
* '''Firebug'''.  Firebug is a plugin for Firefox that is a toolkit full of web developer tools, one of which is a DOM inspector.  To inspect the DOM of a web page, simply open the Firebug window while viewing the web page.&lt;br /&gt;
* '''WebKit Inspector'''.  The WebKit Inspector, which is available in both Chrome and Safari, enables you to see the DOM tree and relationships between elements.  However, its DOM inspection tools are not as robust as those of Firebug.&lt;br /&gt;
* '''Opera Dragonfly'''.  The web browser Opera comes with a web developer toolkit similar to the WebKit Inspector called Dragonfly.  It is important that you test your sites in Opera, because although Opera has only a small fraction of the desktop browser market, it is second only to WebKit on the mobile market.  Opera also has extremely strong CSS support, so it is good for testing for bugs in your CSS.&lt;br /&gt;
&lt;br /&gt;
All of the above-mentioned tools enable you to look at the DOM of your web page and find what properties and methods are associated with each node.  This is helpful because if you have JavaScript that manipulates HTML elements, you cannot tell which properties are associated with which elements by looking at the source code alone.&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 6]]&lt;/div&gt;</summary>
		<author><name>Alex</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=JavaScript&amp;diff=2501</id>
		<title>JavaScript</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=JavaScript&amp;diff=2501"/>
		<updated>2018-02-05T18:12:32Z</updated>

		<summary type="html">&lt;p&gt;Alex: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;JavaScript is the most widely used scripting language for implementing client-side functionality in Web applications, and, in recent years, it's become very popular for server-side application, too.  Unlike PHP, JavaScript code can be interpreted and executed in a client's web browser, instead of on the web server, depending on how it's being used.&lt;br /&gt;
&lt;br /&gt;
== JavaScript?  Did you mean Java? ==&lt;br /&gt;
&lt;br /&gt;
'''JavaScript''' is a prototype-based programming language focused on web interactivity.  It was first introduced in Netscape Navigator, and it in turn gave rise to what is now '''[http://www.ecmascript.org/ ECMAScript]'''.  Originally, JavaScript was called &amp;quot;LiveScript&amp;quot;.  Sun, the developer of Java at the time, wanted a language that would complement its compiled Java language, and so LiveScript was renamed JavaScript.&lt;br /&gt;
&lt;br /&gt;
Beyond that, '''Java and JavaScript are as similar as Ham and Hamster.'''&lt;br /&gt;
&lt;br /&gt;
Java and JavaScript have similar syntax, but the under workings are quite different.  For example, Java requires strict typing, but JavaScript allows for dynamic typing.  Java is object-oriented, but JavaScript is prototype-oriented.  Java is compiled, but JavaScript is interpreted.  Java supports event listeners, but JavaScript makes them a fundamental part of the language.  Java variables are scoped to the innermost method or loop, but JavaScript variables are scoped only to the innermost function.&lt;br /&gt;
&lt;br /&gt;
== JavaScript Language Components ==&lt;br /&gt;
&lt;br /&gt;
This section highlights some features of the JavaScript language that differentiate it from other languages.  For a more comprehensive JavaScript tutorial, the following tutorials are both quality:&lt;br /&gt;
&lt;br /&gt;
* [https://webplatform.github.io/ WebPlatform]: Great for learning JavaScript for the first time.  Advocates best practices for modern JavaScript development.&lt;br /&gt;
* [http://www.quirksmode.org/js/contents.html QuirksMode]: More advanced than the WebPlatform tutorial, but it thoroughly covers the most powerful aspects of pure JavaScript and gives unparalleled advice on browser compatibility.&lt;br /&gt;
&lt;br /&gt;
Advice: Do '''NOT''' Google for &amp;quot;JavaScript Tutorial&amp;quot;.  The first few hits advocate bad or outdated practices.  Stick with the ones listed here.&lt;br /&gt;
&lt;br /&gt;
=== Variables and Scope ===&lt;br /&gt;
&lt;br /&gt;
To define a variable in JavaScript, use the '''let''' keyword.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
let foo = &amp;quot;bar&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To define a constant in JavaScript, use the '''const''' keyword.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
const foo = &amp;quot;bar&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
All variables are objects.  In the case above, the variable '''foo''' is an object of the class '''String'''.&lt;br /&gt;
&lt;br /&gt;
Notice that like PHP, you do not have to explicitly define a type for a variable like '''int''' or '''String'''; this is because JavaScript and PHP are ''dynamically typed languages''.&lt;br /&gt;
&lt;br /&gt;
JavaScript code can access any variable higher in the “function tree”, but not vice-versa.  This is called '''scope'''.  ''All functions create their own scope.''&lt;br /&gt;
&lt;br /&gt;
When you reference a variable, JavaScript will look up through the &amp;quot;function tree&amp;quot; until it finds the variable you asked for.  This means that you could define variables of the same name as global variables inside of functions.  For demonstration of concept:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
const a = &amp;quot;hello&amp;quot;;&lt;br /&gt;
const b = &amp;quot;world&amp;quot;;&lt;br /&gt;
&lt;br /&gt;
function sayGoodByeWorld(){&lt;br /&gt;
	const a = &amp;quot;goodbye&amp;quot;;&lt;br /&gt;
&lt;br /&gt;
	alert(a); // goodbye&lt;br /&gt;
	alert(b); // world&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
sayGoodByeWorld();&lt;br /&gt;
&lt;br /&gt;
alert(a); // hello&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Object Literals ===&lt;br /&gt;
&lt;br /&gt;
A very common way of storing and transporting data in JavaScript is by using objects.  You can define an object with certain properties using an '''object literal''':&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
const apple = {&lt;br /&gt;
	color: &amp;quot;red&amp;quot;,&lt;br /&gt;
	flavor: &amp;quot;sweet&amp;quot;,&lt;br /&gt;
	season: &amp;quot;autumn&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
alert(apple.color);  // red&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Functions ===&lt;br /&gt;
&lt;br /&gt;
To define a function in JavaScript, use the '''function''' keyword.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
function sayHello(){&lt;br /&gt;
	alert(&amp;quot;Hello World&amp;quot;);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
sayHello(); // call the function&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Pass an argument to a function like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
function sayHello(name){&lt;br /&gt;
	alert(&amp;quot;Hello, &amp;quot;+name);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
sayHello(&amp;quot;Todd&amp;quot;); // call the function and pass an argument&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Functions are Objects ====&lt;br /&gt;
&lt;br /&gt;
In JavaScript, functions are objects.  This means that they can be assigned to variables, manipulated on the fly, and even passed as arguments to other functions!  '''''This is an extremely important feature of JavaScript''''' that makes it such a robust language for web development.&lt;br /&gt;
&lt;br /&gt;
You create a function variable like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
const sayHello = function(){&lt;br /&gt;
	alert(&amp;quot;Hello World&amp;quot;);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
sayHello(); // call the function&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Observe that you can make [[#Variables and Scope|scope-dependent]] functions in this way.&lt;br /&gt;
&lt;br /&gt;
=== Closures ===&lt;br /&gt;
&lt;br /&gt;
{{DoctypeTV&lt;br /&gt;
|youtube_id=HaPlj796ngQ&lt;br /&gt;
|time=5m45s&lt;br /&gt;
|desc=JavaScript Closures&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
A '''closure''' is a way to separate a certain snippet of JavaScript code from the global scope.  This is useful if you do not want to &amp;quot;muck up&amp;quot; global variables.  Closures are nothing more than anonymous functions that are called as soon as they are created:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
const a = &amp;quot;hello&amp;quot;;&lt;br /&gt;
&lt;br /&gt;
(​​​​function(){&lt;br /&gt;
	const b = &amp;quot;world&amp;quot;;&lt;br /&gt;
	&lt;br /&gt;
	alert(a); // hello&lt;br /&gt;
	alert(b); // world&lt;br /&gt;
})();&lt;br /&gt;
&lt;br /&gt;
alert(a); // hello&lt;br /&gt;
alert(b);​ // ReferenceError: b is not defined​​​​​​​​​​​​​​​&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{JSFiddleExample&lt;br /&gt;
|title=Passing Variables to a Closure&lt;br /&gt;
|desc=This example demonstrates how you can &amp;quot;save&amp;quot; previous versions of a variable using closures.  This is possible because of scoping and the fact that function variables can be returned as objects.&lt;br /&gt;
|fiddle_id=YURqa&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
Most JavaScript libraries (like jQuery) write all of their code in a closure.  What this means is that except for one or two variable names (jQuery or $), everything associated with the library is completely self-contained.&lt;br /&gt;
&lt;br /&gt;
=== Prototypal Inheritance ===&lt;br /&gt;
&lt;br /&gt;
JavaScript implements '''prototypal inheritance''', as opposed to a language like Java or C++, which implements '''classical inheritance'''.  JavaScript is one of only a handful of languages implementing prototype-based inheritance.&lt;br /&gt;
&lt;br /&gt;
Here's how it works.  Every callable object (function) has a '''prototype'''.  When instances of that object are created, their properties and methods are copied (inherited) from the prototype.  Additionally, changes made to the prototype later in the program are &amp;quot;copied&amp;quot; to every instance.&lt;br /&gt;
&lt;br /&gt;
For example, if you wanted to make a method on all strings that added a “!”, you could modify String’s prototype:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
String.prototype.bang = function(){&lt;br /&gt;
	return this+&amp;quot;!&amp;quot;; // Notice: the context is the instance itself&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
alert(&amp;quot;Hello&amp;quot;.bang()); // alerts Hello!&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To &amp;quot;extend&amp;quot; an object, just copy its prototype to a new object.  However, since classical inheritance and prototypal inheritance are different concepts, copying prototypes may have results that you don't expect.  [http://beej.us/blog/data/javascript-prototypes-inheritance/ This article] seems to have a pretty good explanation of how to &amp;quot;inherit&amp;quot; prototypes with example implementations.&lt;br /&gt;
&lt;br /&gt;
==== Extending Built-In Prototypes ====&lt;br /&gt;
&lt;br /&gt;
You should be aware that there is an active debate in the web development community about whether it is good programming style to extend the prototypes of built-in objects like String and Array, such as in the ''String.prototype.bang'' example above.  There are legitimate arguments on both sides.  [http://stackoverflow.com/questions/8859828/javascript-what-dangers-are-in-extending-array-prototype This Stack Overflow post] has good links to some articles discussing this issue.&lt;br /&gt;
&lt;br /&gt;
=== Context ===&lt;br /&gt;
&lt;br /&gt;
{{DoctypeTV&lt;br /&gt;
|youtube_id=0a4r4bm1nQA&lt;br /&gt;
|time=4m32s&lt;br /&gt;
|desc=The ''this'' Variable in JavaScript&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
Every function is called on a certain object, which is not necessarily the same object in which it was defined.  This is called '''context'''.&lt;br /&gt;
&lt;br /&gt;
To call a function on an arbitrary context, use either '''call''' or '''apply'''.  ''call'' takes a list of arguments, while ''apply'' takes them all in an array.&lt;br /&gt;
&lt;br /&gt;
To access the current context, use the '''this''' keyword.  Demonstration of concept:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
const sayThisColor = function(){&lt;br /&gt;
	alert(this.color);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
const apple = { color: &amp;quot;red&amp;quot; }&lt;br /&gt;
&lt;br /&gt;
sayThisColor();   // undefined&lt;br /&gt;
sayThisColor.call(apple); // red&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Events ==&lt;br /&gt;
&lt;br /&gt;
Events are really what make JavaScript such a powerful language for web development.&lt;br /&gt;
&lt;br /&gt;
Rather than being thread based, JavaScript is event based.  Since all JavaScript code runs in a single thread, '''there are no concurrency issues'''.  When an event occurs, JavaScript automatically calls the ''event callback'' as soon as all previous events' callbacks have finished executing.&lt;br /&gt;
&lt;br /&gt;
Code in the form of a '''callback function''' is associated with events via a '''listener'''.  For example, the following JavaScript causes ''sayHello()'' (the callback function) to be run whenever the button with ID &amp;quot;hello&amp;quot; is clicked (the event):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
const sayHello = function(){&lt;br /&gt;
	alert(&amp;quot;Hello World&amp;quot;);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
document.getElementById(&amp;quot;hello&amp;quot;).addEventListener(&amp;quot;click&amp;quot;, sayHello, false);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{JSFiddleExample&lt;br /&gt;
|title=Binding Callbacks to a Button Click&lt;br /&gt;
|fiddle_id=L8c4Z&lt;br /&gt;
|cse330=true&lt;br /&gt;
|desc=In this example, notice how we bind the callback function when the ''DOMContentLoaded'' event fires.  This is because JavaScript requires that the button has been parsed by the browser before it can add event listeners to it.&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
The '''addEventListener''' method takes three parameters:&lt;br /&gt;
* The event type&lt;br /&gt;
* The callback function&lt;br /&gt;
*: The callback function is passed one parameter: the event object.&lt;br /&gt;
* A boolean representing bubble (false) or capture (true) phase&lt;br /&gt;
*: You usually want Bubble phase.  For more information on event phase, see [[#Event Phase]]&lt;br /&gt;
&lt;br /&gt;
Note that versions of Internet Explorer prior to version 9 required that you use a different, albeit similar, function for assigning event listeners called '''attachEvent'''.  attachEvent takes the same arguments as addEventListener, except you need to put '''on''' before the event type (e.g. &amp;quot;onclick&amp;quot;), and the third argument (phase) is not necessary.&lt;br /&gt;
&lt;br /&gt;
It is perfectly valid to use an '''anonymous function''' as your callback function:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
document.getElementById(&amp;quot;hello&amp;quot;).addEventListener(&amp;quot;click&amp;quot;, function(event){&lt;br /&gt;
	alert(&amp;quot;Hello, World!  Event Type: &amp;quot;+event.type);&lt;br /&gt;
}, false);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
QuirksMode has perhaps the best series of articles about the ins and outs of JavaScript events on the internet: http://www.quirksmode.org/js/contents.html#events&lt;br /&gt;
&lt;br /&gt;
=== The Event Object ===&lt;br /&gt;
&lt;br /&gt;
Callback functions are passed one argument: an ''event object''.  You see above that one property of the event object is ''event.type''.  To see the full list of properties of the event object, you could run the code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
document.getElementById(&amp;quot;my_btn&amp;quot;).addEventListener(&amp;quot;click&amp;quot;, function(event){&lt;br /&gt;
	let strout = &amp;quot;&amp;quot;;&lt;br /&gt;
	for(var i in event){&lt;br /&gt;
		strout += `${i}: ${event[i]}\n`;&lt;br /&gt;
	}&lt;br /&gt;
	console.log(strout);&lt;br /&gt;
}, false);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Some of the most useful properties and methods include:&lt;br /&gt;
* '''event.target''' references the object on which the event occurred.&lt;br /&gt;
* '''event.currentTarget''' references the object whose listener is currently being processed.&lt;br /&gt;
*: ''Note:'' event.target and event.currentTarget might be the same or might be different, depending on whether you are listening for bubbled events.&lt;br /&gt;
* '''event.preventDefault()''' stops the normal result of the event from being executed.  For example, if you listen for a form's ''submit'' event, you can call event.preventDefault() to stop the form from being submitted.&lt;br /&gt;
* '''event.stopPropagation()''' prevents any other event listeners from being executed.  For more detail, read the section on Event Phase below.&lt;br /&gt;
&lt;br /&gt;
For more detail on the event object, see [http://dev.w3.org/2006/webapi/DOM-Level-3-Events/html/DOM3-Events.html#interface-Event the W3C specification].&lt;br /&gt;
&lt;br /&gt;
'''Note:''' If your callback function does not take any parameters, it will still run; you just won't have as easy of access to the event object.&lt;br /&gt;
&lt;br /&gt;
=== Event Handlers and Memory Management ===&lt;br /&gt;
&lt;br /&gt;
JavaScript is an automatically garbage-collected language, meaning that memory management is mostly taken care of for you.  However, there are some instances when you need to be careful about creating &amp;quot;zombie&amp;quot; objects.  In JavaScript, this mostly revolves around the idea of event listeners.&lt;br /&gt;
&lt;br /&gt;
I could give an explanatory example, but instead I'll tell you straightaway that '''the moral of the story is that for every &amp;quot;addEventListener&amp;quot;, there should probably be a &amp;quot;removeEventListener&amp;quot;.'''  Here are some good articles to satisfy your hunger for more details on event listeners and JavaScript memory management:&lt;br /&gt;
&lt;br /&gt;
* http://www.vladalexandruionescu.com/2012/08/javascript-memory-leaks.html&lt;br /&gt;
* http://lostechies.com/derickbailey/2012/03/19/backbone-js-and-javascript-garbage-collection/&lt;br /&gt;
* http://stackoverflow.com/questions/5326300/garbage-collection-with-node-js&lt;br /&gt;
&lt;br /&gt;
When you start working with Node.JS in the next module, it's more important than ever to keep good accounting of your event listeners.&lt;br /&gt;
&lt;br /&gt;
=== Event Phase ===&lt;br /&gt;
&lt;br /&gt;
In JavaScript, events occur in two phases: '''Capture Phase''' and '''Bubble Phase'''.  Consider the following HTML document:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE html&amp;gt;&lt;br /&gt;
&amp;lt;html&amp;gt;&lt;br /&gt;
&amp;lt;head&amp;gt;&amp;lt;title&amp;gt;Event Test&amp;lt;/title&amp;gt;&amp;lt;/head&amp;gt;&lt;br /&gt;
&amp;lt;body&amp;gt;&lt;br /&gt;
  &amp;lt;div id=&amp;quot;box&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;button id=&amp;quot;btn&amp;quot;&amp;gt;&lt;br /&gt;
      Hello&lt;br /&gt;
    &amp;lt;/button&amp;gt;&lt;br /&gt;
  &amp;lt;/div&amp;gt;&lt;br /&gt;
&amp;lt;/body&amp;gt;&lt;br /&gt;
&amp;lt;/html&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Suppose the user clicks on the &amp;quot;Hello&amp;quot; button.  Events will be fired in the following order:&lt;br /&gt;
&lt;br /&gt;
# Capture Phase CLICK on the Document&lt;br /&gt;
# Capture Phase CLICK on the Body&lt;br /&gt;
# Capture Phase CLICK on the Div#box&lt;br /&gt;
# Target Phase CLICK on the Button#btn&lt;br /&gt;
# Bubble Phase CLICK on the Div#box&lt;br /&gt;
# Bubble Phase CLICK on the Body&lt;br /&gt;
# Bubble Phase CLICK on the Document&lt;br /&gt;
&lt;br /&gt;
{{JSFiddleExample&lt;br /&gt;
|title=Using Capture Phase to Enable or Disable a Toolbar&lt;br /&gt;
|fiddle_id=r32Dz&lt;br /&gt;
|desc=We bind an event in the capture phase to the div with ID ''toolbar''.  When ''e.stopPropagation()'' is called, the event does not reach the buttons in the toolbar.&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
Graphically, here is the order in which an event occurs in three generic nested elements:&lt;br /&gt;
&lt;br /&gt;
[[File:EventPhase.gif]]&lt;br /&gt;
&lt;br /&gt;
Why is this useful?  Suppose you have a control panel (toolbar, etc) that you want to temporarily deactivate.  (For example, Bold/Italic/Underline buttons on a graphic text editor that currently has no content.)  You could keep bubble phase event listeners on your buttons, but prevent those events from occurring by stopping the event in the capture phase on the parent element before the event reaches your buttons!  Example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
const disableToolbarFunc = function(e){&lt;br /&gt;
	e.stopPropogation();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
// To disable toolbar:&lt;br /&gt;
document.getElementById(&amp;quot;box&amp;quot;).addEventListener(&amp;quot;click&amp;quot;, disableToolbarFunc, true);&lt;br /&gt;
&lt;br /&gt;
// To re-enable toolbar:&lt;br /&gt;
document.getElementById(&amp;quot;box&amp;quot;).removeEventListener(&amp;quot;click&amp;quot;, disableToolbarFunc, true);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Word of caution:''' Like many great things in web development, capture phase does not work in versions of Internet Explorer prior to version 9.  There is no elegant substitution for older versions of Internet Explorer.&lt;br /&gt;
&lt;br /&gt;
'''Note:''' When the event reaches the innermost element, there is no distinction between capture phase and bubble phase.  The order in which event handlers were added to the element determines the order in which those callbacks are evaluated.&lt;br /&gt;
&lt;br /&gt;
== Document Object Model ==&lt;br /&gt;
&lt;br /&gt;
The '''Document Object Model (DOM)'''  is what enables JavaScript to manipulate the content of your web page.&lt;br /&gt;
&lt;br /&gt;
=== Nodes and Traversing the DOM ===&lt;br /&gt;
&lt;br /&gt;
Each element on your page, whether it is a &amp;lt;nowiki&amp;gt;&amp;lt;p&amp;gt;, &amp;lt;img/&amp;gt;&amp;lt;/nowiki&amp;gt;, a string of text, or even an attribute, is called a '''node'''.&lt;br /&gt;
&lt;br /&gt;
Every node, except for the document itself, has exactly one parent.  A single node may have multiple children.&lt;br /&gt;
&lt;br /&gt;
Consider the following HTML code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;ul id=&amp;quot;my-list&amp;quot;&amp;gt;&lt;br /&gt;
	&amp;lt;li class=&amp;quot;fruits&amp;quot;&amp;gt;Apples&amp;lt;/li&amp;gt;&lt;br /&gt;
	&amp;lt;li class=&amp;quot;citrus&amp;quot;&amp;gt;Oranges and &amp;lt;strong&amp;gt;Lemons&amp;lt;/strong&amp;gt;&amp;lt;/li&amp;gt;&lt;br /&gt;
	&amp;lt;li class=&amp;quot;berries&amp;quot;&amp;gt;Cherries&amp;lt;/li&amp;gt;&lt;br /&gt;
&amp;lt;/ul&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here, the ul with ID &amp;quot;my-list&amp;quot; has three child '''element nodes''' (the three li's) as well as four child '''text nodes''' (the whitespace counts as a text node) and a child '''attribute node'''.  The second LI has one child '''text node''' as well as one child '''element node''' and one child '''attribute node'''.&lt;br /&gt;
&lt;br /&gt;
The DOM can be traversed in JavaScript.  First, let's look at an example.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
e = document.getElementById(&amp;quot;my-list&amp;quot;).getElementsByClassName(&amp;quot;citrus&amp;quot;)[0].lastChild.nodeName;&lt;br /&gt;
alert(e);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{JSFiddleExample&lt;br /&gt;
|title=Currently Selected Radio Button&lt;br /&gt;
|fiddle_id=SHcng&lt;br /&gt;
|desc=In pure JavaScript, in order to determine the currently selected radio button, it is necessary to iterate over an array of pointers to all possible radio buttons, and stop when you find one that is &amp;quot;checked&amp;quot;.&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
The above snippet gets the element with class name '''citrus''' that is a child of the element with ID '''my-list''' (the second LI in the example above), and alerts the type of its second child node (which in this case is '''STRONG''').&lt;br /&gt;
&lt;br /&gt;
Some common methods for traversing the DOM include:&lt;br /&gt;
&lt;br /&gt;
* Node.parentNode&lt;br /&gt;
* Node.childNodes - returns an array of nodes&lt;br /&gt;
* Node.firstChild - same as Node.childNodes[0]&lt;br /&gt;
* Node.lastChild - same as Node.childNodes[Node.childNodes.length-1]&lt;br /&gt;
* Node.previousSibling&lt;br /&gt;
* Node.nextSibling&lt;br /&gt;
&lt;br /&gt;
You can also search for child (including all descendants) using one of the following methods:&lt;br /&gt;
&lt;br /&gt;
* Node.getElementsByTagName(&amp;quot;tag-name&amp;quot;) - returns an array of element nodes having the tag name '''tag-name''' that are descendants of Node&lt;br /&gt;
* Node.getElementById(&amp;quot;id&amp;quot;) - returns a single node having the ID '''id''' that is a descendant of Node&lt;br /&gt;
* Node.getElementsByName(&amp;quot;what-name&amp;quot;) - returns an array of element nodes having their '''name''' attribute set to '''what-name'''.  Useful for radio buttons and other form elements.&lt;br /&gt;
* Node.getElementsByClassName(&amp;quot;class&amp;quot;) - returns an array of nodes having the class '''class'''&lt;br /&gt;
*: '''Note:''' As of October 2012, 82% of the browser market supports Node.getElementsByClassName ([http://caniuse.com/getelementsbyclassname more info]).  In order to support the other 18%, you need to either add your own getElementsByClassName to Node's prototype or use a JavaScript library like jQuery or MooTools.&lt;br /&gt;
&lt;br /&gt;
It is common in JavaScript to have long statements like the one in the example above, where you call methods on several objects in sequence.&lt;br /&gt;
&lt;br /&gt;
=== Creating, Moving, and Removing Nodes ===&lt;br /&gt;
&lt;br /&gt;
You will frequently find yourself wanting to modify the DOM.  JavaScript provides methods that help you do this.&lt;br /&gt;
&lt;br /&gt;
Consider the same HTML as above.  If you wanted to add another element to the list, you could use this code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
const newLi = document.createElement(&amp;quot;li&amp;quot;);  // creates a node with the tag name li&lt;br /&gt;
newLi.appendChild(document.createTextNode(&amp;quot;Broccoli&amp;quot;));&lt;br /&gt;
newLi.setAttribute(&amp;quot;class&amp;quot;, &amp;quot;veggies&amp;quot;);&lt;br /&gt;
document.getElementById(&amp;quot;my-list&amp;quot;).appendChild(newLi);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If you wanted to remove the apples from the list, you could do:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
const apple = document.getElementById(&amp;quot;my-list&amp;quot;).getElementsByClassName(&amp;quot;fruits&amp;quot;)[0];&lt;br /&gt;
document.getElementById(&amp;quot;my-list&amp;quot;).removeChild(apple);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If you wanted to move the apples to the end of the list, you could do this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
const apple = document.getElementById(&amp;quot;my-list&amp;quot;).getElementsByClassName(&amp;quot;fruits&amp;quot;)[0];&lt;br /&gt;
document.getElementById(&amp;quot;my-list&amp;quot;).appendChild(apple);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Notice that '''Node.append()''' both removes a node from its previous location ''and'' appends it to its new location, which is always going to be as the last child of the parent node.&lt;br /&gt;
&lt;br /&gt;
In summary, here are the methods to know from this section:&lt;br /&gt;
&lt;br /&gt;
* Node.append(otherNode) - removes otherNode from its current location in the DOM (if applicable) and then adds it as the last child of Node&lt;br /&gt;
* Node.removeChild(otherNode) - removes otherNode, a child of Node, from the DOM&lt;br /&gt;
* document.createElement(&amp;quot;tag-name&amp;quot;) - create a new node with the tag name &amp;quot;tag-name&amp;quot;&lt;br /&gt;
* document.createTextNode(&amp;quot;text&amp;quot;) - create a node containing only the string '''text'''&lt;br /&gt;
* Node.setAttribute(&amp;quot;attribute&amp;quot;, &amp;quot;value&amp;quot;) - sets the attribute node of name &amp;quot;attribute&amp;quot; to &amp;quot;value&amp;quot;&lt;br /&gt;
&lt;br /&gt;
=== DOM Shortcuts ===&lt;br /&gt;
&lt;br /&gt;
In the above sections, we have been creating, reading, modifying, and deleting Nodes.  This is the most &amp;quot;correct&amp;quot; way to change the content of a web page from inside JavaScript.&lt;br /&gt;
&lt;br /&gt;
This section documents a few shortcuts that are not as &amp;quot;pure&amp;quot; as using Nodes but can be less confusing and cumbersome.&lt;br /&gt;
&lt;br /&gt;
{{JSFiddleExample&lt;br /&gt;
|title=Displaying Information&lt;br /&gt;
|fiddle_id=Q3BPZ&lt;br /&gt;
|desc=This example shows how to use some of the shortcut methods for using JavaScript to display information on the page.&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
==== textContent ====&lt;br /&gt;
&lt;br /&gt;
Using textContent to display information is probably the easiest method out there.  For example, the following code overwrites whatever is in the element with ID &amp;quot;holder&amp;quot; with the string &amp;quot;Hello World&amp;quot;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
document.getElementById(&amp;quot;holder&amp;quot;).textContent = &amp;quot;Hello World&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If you wanted to instead append the text, simply use '''+=''' instead of '''=''':&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
document.getElementById(&amp;quot;holder&amp;quot;).textContent += &amp;quot; -  Later, he said Hello World  - &amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note that textContent displays strings literally; that is, it does not allow for HTML.  Setting the textContent property also removes any HTML that may have already been in that element.&lt;br /&gt;
&lt;br /&gt;
==== innerHTML ====&lt;br /&gt;
&lt;br /&gt;
If you need to use HTML in your output but don't want to use the method described earlier in this section, a straightforward strategy is to use the innerHTML property of an element. For example, the following code would add a paragraph saying &amp;quot;Hello World&amp;quot; to the element with ID &amp;quot;holder&amp;quot;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
document.getElementById(&amp;quot;holder&amp;quot;).innerHTML += &amp;quot;&amp;lt;p&amp;gt;Hello World&amp;lt;/p&amp;gt;&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Important:''' You need to be careful to prevent XSS-type attacks if you display information using innerHTML.  For example, be sure to escape a user-supplied string before appending it to innerHTML.&lt;br /&gt;
&lt;br /&gt;
=== JavaScript Inspectors ===&lt;br /&gt;
&lt;br /&gt;
{{DoctypeTV&lt;br /&gt;
|youtube_id=PKzrmbN-pMg&lt;br /&gt;
|time=4m13s&lt;br /&gt;
|desc=Using Firebug, WebKit Inspector, and IE Developer Tools&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
Various browsers and browser plugins give you, the developer, tools to debug your code, inspect the DOM, and much more.  Using these tools is essential for an efficient workflow.&lt;br /&gt;
&lt;br /&gt;
* '''Firebug'''.  Firebug is a plugin for Firefox that is a toolkit full of web developer tools, one of which is a DOM inspector.  To inspect the DOM of a web page, simply open the Firebug window while viewing the web page.&lt;br /&gt;
* '''WebKit Inspector'''.  The WebKit Inspector, which is available in both Chrome and Safari, enables you to see the DOM tree and relationships between elements.  However, its DOM inspection tools are not as robust as those of Firebug.&lt;br /&gt;
* '''Opera Dragonfly'''.  The web browser Opera comes with a web developer toolkit similar to the WebKit Inspector called Dragonfly.  It is important that you test your sites in Opera, because although Opera has only a small fraction of the desktop browser market, it is second only to WebKit on the mobile market.  Opera also has extremely strong CSS support, so it is good for testing for bugs in your CSS.&lt;br /&gt;
&lt;br /&gt;
All of the above-mentioned tools enable you to look at the DOM of your web page and find what properties and methods are associated with each node.  This is helpful because if you have JavaScript that manipulates HTML elements, you cannot tell which properties are associated with which elements by looking at the source code alone.&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 6]]&lt;/div&gt;</summary>
		<author><name>Alex</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=JavaScript&amp;diff=2500</id>
		<title>JavaScript</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=JavaScript&amp;diff=2500"/>
		<updated>2018-02-05T18:05:35Z</updated>

		<summary type="html">&lt;p&gt;Alex: /* Variables and Scope */ New variable declarations&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;JavaScript is the most widely used scripting language for implementing client-side functionality in Web applications, and, in recent years, it's become very popular for server-side application, too.  Unlike PHP, JavaScript code can be interpreted and executed in a client's web browser, instead of on the web server, depending on how it's being used.&lt;br /&gt;
&lt;br /&gt;
== JavaScript?  Did you mean Java? ==&lt;br /&gt;
&lt;br /&gt;
'''JavaScript''' is a prototype-based programming language focused on web interactivity.  It was first introduced in Netscape Navigator, and it in turn gave rise to what is now '''[http://www.ecmascript.org/ ECMAScript]'''.  Originally, JavaScript was called &amp;quot;LiveScript&amp;quot;.  Sun, the developer of Java at the time, wanted a language that would complement its compiled Java language, and so LiveScript was renamed JavaScript.&lt;br /&gt;
&lt;br /&gt;
Beyond that, '''Java and JavaScript are as similar as Ham and Hamster.'''&lt;br /&gt;
&lt;br /&gt;
Java and JavaScript have similar syntax, but the under workings are quite different.  For example, Java requires strict typing, but JavaScript allows for dynamic typing.  Java is object-oriented, but JavaScript is prototype-oriented.  Java is compiled, but JavaScript is interpreted.  Java supports event listeners, but JavaScript makes them a fundamental part of the language.  Java variables are scoped to the innermost method or loop, but JavaScript variables are scoped only to the innermost function.&lt;br /&gt;
&lt;br /&gt;
== JavaScript Language Components ==&lt;br /&gt;
&lt;br /&gt;
This section highlights some features of the JavaScript language that differentiate it from other languages.  For a more comprehensive JavaScript tutorial, the following tutorials are both quality:&lt;br /&gt;
&lt;br /&gt;
* [https://webplatform.github.io/ WebPlatform]: Great for learning JavaScript for the first time.  Advocates best practices for modern JavaScript development.&lt;br /&gt;
* [http://www.quirksmode.org/js/contents.html QuirksMode]: More advanced than the WebPlatform tutorial, but it thoroughly covers the most powerful aspects of pure JavaScript and gives unparalleled advice on browser compatibility.&lt;br /&gt;
&lt;br /&gt;
Advice: Do '''NOT''' Google for &amp;quot;JavaScript Tutorial&amp;quot;.  The first few hits advocate bad or outdated practices.  Stick with the ones listed here.&lt;br /&gt;
&lt;br /&gt;
=== Variables and Scope ===&lt;br /&gt;
&lt;br /&gt;
To define a variable in JavaScript, use the '''let''' keyword.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
let foo = &amp;quot;bar&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To define a constant in JavaScript, use the '''const''' keyword.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
const foo = &amp;quot;bar&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
All variables are objects.  In the case above, the variable '''foo''' is an object of the class '''String'''.&lt;br /&gt;
&lt;br /&gt;
Notice that like PHP, you do not have to explicitly define a type for a variable like '''int''' or '''String'''; this is because JavaScript and PHP are ''dynamically typed languages''.&lt;br /&gt;
&lt;br /&gt;
JavaScript code can access any variable higher in the “function tree”, but not vice-versa.  This is called '''scope'''.  ''All functions create their own scope.''&lt;br /&gt;
&lt;br /&gt;
When you reference a variable, JavaScript will look up through the &amp;quot;function tree&amp;quot; until it finds the variable you asked for.  This means that you could define variables of the same name as global variables inside of functions.  For demonstration of concept:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
const a = &amp;quot;hello&amp;quot;;&lt;br /&gt;
const b = &amp;quot;world&amp;quot;;&lt;br /&gt;
&lt;br /&gt;
function sayGoodByeWorld(){&lt;br /&gt;
	const a = &amp;quot;goodbye&amp;quot;;&lt;br /&gt;
&lt;br /&gt;
	alert(a); // goodbye&lt;br /&gt;
	alert(b); // world&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
sayGoodByeWorld();&lt;br /&gt;
&lt;br /&gt;
alert(a); // hello&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Object Literals ===&lt;br /&gt;
&lt;br /&gt;
A very common way of storing and transporting data in JavaScript is by using objects.  You can define an object with certain properties using an '''object literal''':&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var apple = {&lt;br /&gt;
	color: &amp;quot;red&amp;quot;,&lt;br /&gt;
	flavor: &amp;quot;sweet&amp;quot;,&lt;br /&gt;
	season: &amp;quot;autumn&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
alert(apple.color);  // red&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Functions ===&lt;br /&gt;
&lt;br /&gt;
To define a function in JavaScript, use the '''function''' keyword.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
function sayHello(){&lt;br /&gt;
	alert(&amp;quot;Hello World&amp;quot;);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
sayHello(); // call the function&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Pass an argument to a function like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
function sayHello(name){&lt;br /&gt;
	alert(&amp;quot;Hello, &amp;quot;+name);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
sayHello(&amp;quot;Todd&amp;quot;); // call the function and pass an argument&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Functions are Objects ====&lt;br /&gt;
&lt;br /&gt;
In JavaScript, functions are objects.  This means that they can be assigned to variables, manipulated on the fly, and even passed as arguments to other functions!  '''''This is an extremely important feature of JavaScript''''' that makes it such a robust language for web development.&lt;br /&gt;
&lt;br /&gt;
You create a function variable like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var sayHello = function(){&lt;br /&gt;
	alert(&amp;quot;Hello World&amp;quot;);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
sayHello(); // call the function&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Observe that you can make [[#Variables and Scope|scope-dependent]] functions in this way.&lt;br /&gt;
&lt;br /&gt;
=== Closures ===&lt;br /&gt;
&lt;br /&gt;
{{DoctypeTV&lt;br /&gt;
|youtube_id=HaPlj796ngQ&lt;br /&gt;
|time=5m45s&lt;br /&gt;
|desc=JavaScript Closures&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
A '''closure''' is a way to separate a certain snippet of JavaScript code from the global scope.  This is useful if you do not want to &amp;quot;muck up&amp;quot; global variables.  Closures are nothing more than anonymous functions that are called as soon as they are created:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
​var a = &amp;quot;hello&amp;quot;;&lt;br /&gt;
&lt;br /&gt;
(​​​​function(){&lt;br /&gt;
	var b = &amp;quot;world&amp;quot;;&lt;br /&gt;
	&lt;br /&gt;
	alert(a); // hello&lt;br /&gt;
	alert(b); // world&lt;br /&gt;
})();&lt;br /&gt;
&lt;br /&gt;
alert(a); // hello&lt;br /&gt;
alert(b);​ // ReferenceError: b is not defined​​​​​​​​​​​​​​​&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{JSFiddleExample&lt;br /&gt;
|title=Passing Variables to a Closure&lt;br /&gt;
|desc=This example demonstrates how you can &amp;quot;save&amp;quot; previous versions of a variable using closures.  This is possible because of scoping and the fact that function variables can be returned as objects.&lt;br /&gt;
|fiddle_id=YURqa&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
Most JavaScript libraries (like jQuery) write all of their code in a closure.  What this means is that except for one or two variable names (jQuery or $), everything associated with the library is completely self-contained.&lt;br /&gt;
&lt;br /&gt;
=== Prototypal Inheritance ===&lt;br /&gt;
&lt;br /&gt;
JavaScript implements '''prototypal inheritance''', as opposed to a language like Java or C++, which implements '''classical inheritance'''.  JavaScript is one of only a handful of languages implementing prototype-based inheritance.&lt;br /&gt;
&lt;br /&gt;
Here's how it works.  Every callable object (function) has a '''prototype'''.  When instances of that object are created, their properties and methods are copied (inherited) from the prototype.  Additionally, changes made to the prototype later in the program are &amp;quot;copied&amp;quot; to every instance.&lt;br /&gt;
&lt;br /&gt;
For example, if you wanted to make a method on all strings that added a “!”, you could modify String’s prototype:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
String.prototype.bang = function(){&lt;br /&gt;
	return this+&amp;quot;!&amp;quot;; // Notice: the context is the instance itself&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
alert(&amp;quot;Hello&amp;quot;.bang()); // alerts Hello!&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To &amp;quot;extend&amp;quot; an object, just copy its prototype to a new object.  However, since classical inheritance and prototypal inheritance are different concepts, copying prototypes may have results that you don't expect.  [http://beej.us/blog/data/javascript-prototypes-inheritance/ This article] seems to have a pretty good explanation of how to &amp;quot;inherit&amp;quot; prototypes with example implementations.&lt;br /&gt;
&lt;br /&gt;
==== Extending Built-In Prototypes ====&lt;br /&gt;
&lt;br /&gt;
You should be aware that there is an active debate in the web development community about whether it is good programming style to extend the prototypes of built-in objects like String and Array, such as in the ''String.prototype.bang'' example above.  There are legitimate arguments on both sides.  [http://stackoverflow.com/questions/8859828/javascript-what-dangers-are-in-extending-array-prototype This Stack Overflow post] has good links to some articles discussing this issue.&lt;br /&gt;
&lt;br /&gt;
=== Context ===&lt;br /&gt;
&lt;br /&gt;
{{DoctypeTV&lt;br /&gt;
|youtube_id=0a4r4bm1nQA&lt;br /&gt;
|time=4m32s&lt;br /&gt;
|desc=The ''this'' Variable in JavaScript&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
Every function is called on a certain object, which is not necessarily the same object in which it was defined.  This is called '''context'''.&lt;br /&gt;
&lt;br /&gt;
To call a function on an arbitrary context, use either '''call''' or '''apply'''.  ''call'' takes a list of arguments, while ''apply'' takes them all in an array.&lt;br /&gt;
&lt;br /&gt;
To access the current context, use the '''this''' keyword.  Demonstration of concept:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var sayThisColor = function(){&lt;br /&gt;
	alert(this.color);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
var apple = { color: &amp;quot;red&amp;quot; }&lt;br /&gt;
&lt;br /&gt;
sayThisColor();   // undefined&lt;br /&gt;
sayThisColor.call(apple); // red&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Events ==&lt;br /&gt;
&lt;br /&gt;
Events are really what make JavaScript such a powerful language for web development.&lt;br /&gt;
&lt;br /&gt;
Rather than being thread based, JavaScript is event based.  Since all JavaScript code runs in a single thread, '''there are no concurrency issues'''.  When an event occurs, JavaScript automatically calls the ''event callback'' as soon as all previous events' callbacks have finished executing.&lt;br /&gt;
&lt;br /&gt;
Code in the form of a '''callback function''' is associated with events via a '''listener'''.  For example, the following JavaScript causes ''sayHello()'' (the callback function) to be run whenever the button with ID &amp;quot;hello&amp;quot; is clicked (the event):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var sayHello = function(){&lt;br /&gt;
	alert(&amp;quot;Hello World&amp;quot;);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
document.getElementById(&amp;quot;hello&amp;quot;).addEventListener(&amp;quot;click&amp;quot;, sayHello, false);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{JSFiddleExample&lt;br /&gt;
|title=Binding Callbacks to a Button Click&lt;br /&gt;
|fiddle_id=L8c4Z&lt;br /&gt;
|cse330=true&lt;br /&gt;
|desc=In this example, notice how we bind the callback function when the ''DOMContentLoaded'' event fires.  This is because JavaScript requires that the button has been parsed by the browser before it can add event listeners to it.&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
The '''addEventListener''' method takes three parameters:&lt;br /&gt;
* The event type&lt;br /&gt;
* The callback function&lt;br /&gt;
*: The callback function is passed one parameter: the event object.&lt;br /&gt;
* A boolean representing bubble (false) or capture (true) phase&lt;br /&gt;
*: You usually want Bubble phase.  For more information on event phase, see [[#Event Phase]]&lt;br /&gt;
&lt;br /&gt;
Note that versions of Internet Explorer prior to version 9 required that you use a different, albeit similar, function for assigning event listeners called '''attachEvent'''.  attachEvent takes the same arguments as addEventListener, except you need to put '''on''' before the event type (e.g. &amp;quot;onclick&amp;quot;), and the third argument (phase) is not necessary.&lt;br /&gt;
&lt;br /&gt;
It is perfectly valid to use an '''anonymous function''' as your callback function:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
document.getElementById(&amp;quot;hello&amp;quot;).addEventListener(&amp;quot;click&amp;quot;, function(event){&lt;br /&gt;
	alert(&amp;quot;Hello, World!  Event Type: &amp;quot;+event.type);&lt;br /&gt;
}, false);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
QuirksMode has perhaps the best series of articles about the ins and outs of JavaScript events on the internet: http://www.quirksmode.org/js/contents.html#events&lt;br /&gt;
&lt;br /&gt;
=== The Event Object ===&lt;br /&gt;
&lt;br /&gt;
Callback functions are passed one argument: an ''event object''.  You see above that one property of the event object is ''event.type''.  To see the full list of properties of the event object, you could run the code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
document.getElementById(&amp;quot;my_btn&amp;quot;).addEventListener(&amp;quot;click&amp;quot;, function(event){&lt;br /&gt;
	var strout = &amp;quot;&amp;quot;;&lt;br /&gt;
	for(var i in event){&lt;br /&gt;
		strout += i + &amp;quot;: &amp;quot; + event[i] + &amp;quot;\n&amp;quot;;&lt;br /&gt;
	}&lt;br /&gt;
	console.log(strout);&lt;br /&gt;
}, false);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Some of the most useful properties and methods include:&lt;br /&gt;
* '''event.target''' references the object on which the event occurred.&lt;br /&gt;
* '''event.currentTarget''' references the object whose listener is currently being processed.&lt;br /&gt;
*: ''Note:'' event.target and event.currentTarget might be the same or might be different, depending on whether you are listening for bubbled events.&lt;br /&gt;
* '''event.preventDefault()''' stops the normal result of the event from being executed.  For example, if you listen for a form's ''submit'' event, you can call event.preventDefault() to stop the form from being submitted.&lt;br /&gt;
* '''event.stopPropagation()''' prevents any other event listeners from being executed.  For more detail, read the section on Event Phase below.&lt;br /&gt;
&lt;br /&gt;
For more detail on the event object, see [http://dev.w3.org/2006/webapi/DOM-Level-3-Events/html/DOM3-Events.html#interface-Event the W3C specification].&lt;br /&gt;
&lt;br /&gt;
'''Note:''' If your callback function does not take any parameters, it will still run; you just won't have as easy of access to the event object.&lt;br /&gt;
&lt;br /&gt;
=== Event Handlers and Memory Management ===&lt;br /&gt;
&lt;br /&gt;
JavaScript is an automatically garbage-collected language, meaning that memory management is mostly taken care of for you.  However, there are some instances when you need to be careful about creating &amp;quot;zombie&amp;quot; objects.  In JavaScript, this mostly revolves around the idea of event listeners.&lt;br /&gt;
&lt;br /&gt;
I could give an explanatory example, but instead I'll tell you straightaway that '''the moral of the story is that for every &amp;quot;addEventListener&amp;quot;, there should probably be a &amp;quot;removeEventListener&amp;quot;.'''  Here are some good articles to satisfy your hunger for more details on event listeners and JavaScript memory management:&lt;br /&gt;
&lt;br /&gt;
* http://www.vladalexandruionescu.com/2012/08/javascript-memory-leaks.html&lt;br /&gt;
* http://lostechies.com/derickbailey/2012/03/19/backbone-js-and-javascript-garbage-collection/&lt;br /&gt;
* http://stackoverflow.com/questions/5326300/garbage-collection-with-node-js&lt;br /&gt;
&lt;br /&gt;
When you start working with Node.JS in the next module, it's more important than ever to keep good accounting of your event listeners.&lt;br /&gt;
&lt;br /&gt;
=== Event Phase ===&lt;br /&gt;
&lt;br /&gt;
In JavaScript, events occur in two phases: '''Capture Phase''' and '''Bubble Phase'''.  Consider the following HTML document:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE html&amp;gt;&lt;br /&gt;
&amp;lt;html&amp;gt;&lt;br /&gt;
&amp;lt;head&amp;gt;&amp;lt;title&amp;gt;Event Test&amp;lt;/title&amp;gt;&amp;lt;/head&amp;gt;&lt;br /&gt;
&amp;lt;body&amp;gt;&lt;br /&gt;
  &amp;lt;div id=&amp;quot;box&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;button id=&amp;quot;btn&amp;quot;&amp;gt;&lt;br /&gt;
      Hello&lt;br /&gt;
    &amp;lt;/button&amp;gt;&lt;br /&gt;
  &amp;lt;/div&amp;gt;&lt;br /&gt;
&amp;lt;/body&amp;gt;&lt;br /&gt;
&amp;lt;/html&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Suppose the user clicks on the &amp;quot;Hello&amp;quot; button.  Events will be fired in the following order:&lt;br /&gt;
&lt;br /&gt;
# Capture Phase CLICK on the Document&lt;br /&gt;
# Capture Phase CLICK on the Body&lt;br /&gt;
# Capture Phase CLICK on the Div#box&lt;br /&gt;
# Target Phase CLICK on the Button#btn&lt;br /&gt;
# Bubble Phase CLICK on the Div#box&lt;br /&gt;
# Bubble Phase CLICK on the Body&lt;br /&gt;
# Bubble Phase CLICK on the Document&lt;br /&gt;
&lt;br /&gt;
{{JSFiddleExample&lt;br /&gt;
|title=Using Capture Phase to Enable or Disable a Toolbar&lt;br /&gt;
|fiddle_id=r32Dz&lt;br /&gt;
|desc=We bind an event in the capture phase to the div with ID ''toolbar''.  When ''e.stopPropagation()'' is called, the event does not reach the buttons in the toolbar.&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
Graphically, here is the order in which an event occurs in three generic nested elements:&lt;br /&gt;
&lt;br /&gt;
[[File:EventPhase.gif]]&lt;br /&gt;
&lt;br /&gt;
Why is this useful?  Suppose you have a control panel (toolbar, etc) that you want to temporarily deactivate.  (For example, Bold/Italic/Underline buttons on a graphic text editor that currently has no content.)  You could keep bubble phase event listeners on your buttons, but prevent those events from occurring by stopping the event in the capture phase on the parent element before the event reaches your buttons!  Example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var disableToolbarFunc = function(e){&lt;br /&gt;
	e.stopPropogation();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
// To disable toolbar:&lt;br /&gt;
document.getElementById(&amp;quot;box&amp;quot;).addEventListener(&amp;quot;click&amp;quot;, disableToolbarFunc, true);&lt;br /&gt;
&lt;br /&gt;
// To re-enable toolbar:&lt;br /&gt;
document.getElementById(&amp;quot;box&amp;quot;).removeEventListener(&amp;quot;click&amp;quot;, disableToolbarFunc, true);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Word of caution:''' Like many great things in web development, capture phase does not work in versions of Internet Explorer prior to version 9.  There is no elegant substitution for older versions of Internet Explorer.&lt;br /&gt;
&lt;br /&gt;
'''Note:''' When the event reaches the innermost element, there is no distinction between capture phase and bubble phase.  The order in which event handlers were added to the element determines the order in which those callbacks are evaluated.&lt;br /&gt;
&lt;br /&gt;
== Document Object Model ==&lt;br /&gt;
&lt;br /&gt;
The '''Document Object Model (DOM)'''  is what enables JavaScript to manipulate the content of your web page.&lt;br /&gt;
&lt;br /&gt;
=== Nodes and Traversing the DOM ===&lt;br /&gt;
&lt;br /&gt;
Each element on your page, whether it is a &amp;lt;nowiki&amp;gt;&amp;lt;p&amp;gt;, &amp;lt;img/&amp;gt;&amp;lt;/nowiki&amp;gt;, a string of text, or even an attribute, is called a '''node'''.&lt;br /&gt;
&lt;br /&gt;
Every node, except for the document itself, has exactly one parent.  A single node may have multiple children.&lt;br /&gt;
&lt;br /&gt;
Consider the following HTML code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;ul id=&amp;quot;my-list&amp;quot;&amp;gt;&lt;br /&gt;
	&amp;lt;li class=&amp;quot;fruits&amp;quot;&amp;gt;Apples&amp;lt;/li&amp;gt;&lt;br /&gt;
	&amp;lt;li class=&amp;quot;citrus&amp;quot;&amp;gt;Oranges and &amp;lt;strong&amp;gt;Lemons&amp;lt;/strong&amp;gt;&amp;lt;/li&amp;gt;&lt;br /&gt;
	&amp;lt;li class=&amp;quot;berries&amp;quot;&amp;gt;Cherries&amp;lt;/li&amp;gt;&lt;br /&gt;
&amp;lt;/ul&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here, the ul with ID &amp;quot;my-list&amp;quot; has three child '''element nodes''' (the three li's) as well as four child '''text nodes''' (the whitespace counts as a text node) and a child '''attribute node'''.  The second LI has one child '''text node''' as well as one child '''element node''' and one child '''attribute node'''.&lt;br /&gt;
&lt;br /&gt;
The DOM can be traversed in JavaScript.  First, let's look at an example.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
e = document.getElementById(&amp;quot;my-list&amp;quot;).getElementsByClassName(&amp;quot;citrus&amp;quot;)[0].lastChild.nodeName;&lt;br /&gt;
alert(e);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{JSFiddleExample&lt;br /&gt;
|title=Currently Selected Radio Button&lt;br /&gt;
|fiddle_id=SHcng&lt;br /&gt;
|desc=In pure JavaScript, in order to determine the currently selected radio button, it is necessary to iterate over an array of pointers to all possible radio buttons, and stop when you find one that is &amp;quot;checked&amp;quot;.&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
The above snippet gets the element with class name '''citrus''' that is a child of the element with ID '''my-list''' (the second LI in the example above), and alerts the type of its second child node (which in this case is '''STRONG''').&lt;br /&gt;
&lt;br /&gt;
Some common methods for traversing the DOM include:&lt;br /&gt;
&lt;br /&gt;
* Node.parentNode&lt;br /&gt;
* Node.childNodes - returns an array of nodes&lt;br /&gt;
* Node.firstChild - same as Node.childNodes[0]&lt;br /&gt;
* Node.lastChild - same as Node.childNodes[Node.childNodes.length-1]&lt;br /&gt;
* Node.previousSibling&lt;br /&gt;
* Node.nextSibling&lt;br /&gt;
&lt;br /&gt;
You can also search for child (including all descendants) using one of the following methods:&lt;br /&gt;
&lt;br /&gt;
* Node.getElementsByTagName(&amp;quot;tag-name&amp;quot;) - returns an array of element nodes having the tag name '''tag-name''' that are descendants of Node&lt;br /&gt;
* Node.getElementById(&amp;quot;id&amp;quot;) - returns a single node having the ID '''id''' that is a descendant of Node&lt;br /&gt;
* Node.getElementsByName(&amp;quot;what-name&amp;quot;) - returns an array of element nodes having their '''name''' attribute set to '''what-name'''.  Useful for radio buttons and other form elements.&lt;br /&gt;
* Node.getElementsByClassName(&amp;quot;class&amp;quot;) - returns an array of nodes having the class '''class'''&lt;br /&gt;
*: '''Note:''' As of October 2012, 82% of the browser market supports Node.getElementsByClassName ([http://caniuse.com/getelementsbyclassname more info]).  In order to support the other 18%, you need to either add your own getElementsByClassName to Node's prototype or use a JavaScript library like jQuery or MooTools.&lt;br /&gt;
&lt;br /&gt;
It is common in JavaScript to have long statements like the one in the example above, where you call methods on several objects in sequence.&lt;br /&gt;
&lt;br /&gt;
=== Creating, Moving, and Removing Nodes ===&lt;br /&gt;
&lt;br /&gt;
You will frequently find yourself wanting to modify the DOM.  JavaScript provides methods that help you do this.&lt;br /&gt;
&lt;br /&gt;
Consider the same HTML as above.  If you wanted to add another element to the list, you could use this code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var newLi = document.createElement(&amp;quot;li&amp;quot;);  // creates a node with the tag name li&lt;br /&gt;
newLi.appendChild(document.createTextNode(&amp;quot;Broccoli&amp;quot;));&lt;br /&gt;
newLi.setAttribute(&amp;quot;class&amp;quot;, &amp;quot;veggies&amp;quot;);&lt;br /&gt;
document.getElementById(&amp;quot;my-list&amp;quot;).appendChild(newLi);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If you wanted to remove the apples from the list, you could do:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var apple = document.getElementById(&amp;quot;my-list&amp;quot;).getElementsByClassName(&amp;quot;fruits&amp;quot;)[0];&lt;br /&gt;
document.getElementById(&amp;quot;my-list&amp;quot;).removeChild(apple);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If you wanted to move the apples to the end of the list, you could do this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
var apple = document.getElementById(&amp;quot;my-list&amp;quot;).getElementsByClassName(&amp;quot;fruits&amp;quot;)[0];&lt;br /&gt;
document.getElementById(&amp;quot;my-list&amp;quot;).appendChild(apple);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Notice that '''Node.append()''' both removes a node from its previous location ''and'' appends it to its new location, which is always going to be as the last child of the parent node.&lt;br /&gt;
&lt;br /&gt;
In summary, here are the methods to know from this section:&lt;br /&gt;
&lt;br /&gt;
* Node.append(otherNode) - removes otherNode from its current location in the DOM (if applicable) and then adds it as the last child of Node&lt;br /&gt;
* Node.removeChild(otherNode) - removes otherNode, a child of Node, from the DOM&lt;br /&gt;
* document.createElement(&amp;quot;tag-name&amp;quot;) - create a new node with the tag name &amp;quot;tag-name&amp;quot;&lt;br /&gt;
* document.createTextNode(&amp;quot;text&amp;quot;) - create a node containing only the string '''text'''&lt;br /&gt;
* Node.setAttribute(&amp;quot;attribute&amp;quot;, &amp;quot;value&amp;quot;) - sets the attribute node of name &amp;quot;attribute&amp;quot; to &amp;quot;value&amp;quot;&lt;br /&gt;
&lt;br /&gt;
=== DOM Shortcuts ===&lt;br /&gt;
&lt;br /&gt;
In the above sections, we have been creating, reading, modifying, and deleting Nodes.  This is the most &amp;quot;correct&amp;quot; way to change the content of a web page from inside JavaScript.&lt;br /&gt;
&lt;br /&gt;
This section documents a few shortcuts that are not as &amp;quot;pure&amp;quot; as using Nodes but can be less confusing and cumbersome.&lt;br /&gt;
&lt;br /&gt;
{{JSFiddleExample&lt;br /&gt;
|title=Displaying Information&lt;br /&gt;
|fiddle_id=Q3BPZ&lt;br /&gt;
|desc=This example shows how to use some of the shortcut methods for using JavaScript to display information on the page.&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
==== textContent ====&lt;br /&gt;
&lt;br /&gt;
Using textContent to display information is probably the easiest method out there.  For example, the following code overwrites whatever is in the element with ID &amp;quot;holder&amp;quot; with the string &amp;quot;Hello World&amp;quot;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
document.getElementById(&amp;quot;holder&amp;quot;).textContent = &amp;quot;Hello World&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If you wanted to instead append the text, simply use '''+=''' instead of '''=''':&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
document.getElementById(&amp;quot;holder&amp;quot;).textContent += &amp;quot; -  Later, he said Hello World  - &amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note that textContent displays strings literally; that is, it does not allow for HTML.  Setting the textContent property also removes any HTML that may have already been in that element.&lt;br /&gt;
&lt;br /&gt;
==== innerHTML ====&lt;br /&gt;
&lt;br /&gt;
If you need to use HTML in your output but don't want to use the method described earlier in this section, a straightforward strategy is to use the innerHTML property of an element. For example, the following code would add a paragraph saying &amp;quot;Hello World&amp;quot; to the element with ID &amp;quot;holder&amp;quot;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
document.getElementById(&amp;quot;holder&amp;quot;).innerHTML += &amp;quot;&amp;lt;p&amp;gt;Hello World&amp;lt;/p&amp;gt;&amp;quot;;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Important:''' You need to be careful to prevent XSS-type attacks if you display information using innerHTML.  For example, be sure to escape a user-supplied string before appending it to innerHTML.&lt;br /&gt;
&lt;br /&gt;
=== JavaScript Inspectors ===&lt;br /&gt;
&lt;br /&gt;
{{DoctypeTV&lt;br /&gt;
|youtube_id=PKzrmbN-pMg&lt;br /&gt;
|time=4m13s&lt;br /&gt;
|desc=Using Firebug, WebKit Inspector, and IE Developer Tools&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
Various browsers and browser plugins give you, the developer, tools to debug your code, inspect the DOM, and much more.  Using these tools is essential for an efficient workflow.&lt;br /&gt;
&lt;br /&gt;
* '''Firebug'''.  Firebug is a plugin for Firefox that is a toolkit full of web developer tools, one of which is a DOM inspector.  To inspect the DOM of a web page, simply open the Firebug window while viewing the web page.&lt;br /&gt;
* '''WebKit Inspector'''.  The WebKit Inspector, which is available in both Chrome and Safari, enables you to see the DOM tree and relationships between elements.  However, its DOM inspection tools are not as robust as those of Firebug.&lt;br /&gt;
* '''Opera Dragonfly'''.  The web browser Opera comes with a web developer toolkit similar to the WebKit Inspector called Dragonfly.  It is important that you test your sites in Opera, because although Opera has only a small fraction of the desktop browser market, it is second only to WebKit on the mobile market.  Opera also has extremely strong CSS support, so it is good for testing for bugs in your CSS.&lt;br /&gt;
&lt;br /&gt;
All of the above-mentioned tools enable you to look at the DOM of your web page and find what properties and methods are associated with each node.  This is helpful because if you have JavaScript that manipulates HTML elements, you cannot tell which properties are associated with which elements by looking at the source code alone.&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 6]]&lt;/div&gt;</summary>
		<author><name>Alex</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Module_4&amp;diff=2499</id>
		<title>Module 4</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Module_4&amp;diff=2499"/>
		<updated>2018-02-05T18:03:15Z</updated>

		<summary type="html">&lt;p&gt;Alex: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;__NOTOC__&lt;br /&gt;
In Module 4, you will learn the fundamentals of Python, a popular scripting language, and Regular Expressions, which give you power in text processing.&lt;br /&gt;
&lt;br /&gt;
This article contains your assignments for Module 4.&lt;br /&gt;
&lt;br /&gt;
== Reading ==&lt;br /&gt;
&lt;br /&gt;
The following articles on the online class wiki textbook contain information that will help you complete the assignments.&lt;br /&gt;
&lt;br /&gt;
* [[Python]]&lt;br /&gt;
* [[Regular Expressions]]&lt;br /&gt;
&lt;br /&gt;
== Individual Assignments ==&lt;br /&gt;
&lt;br /&gt;
=== Learn Python and Regular Expressions ===&lt;br /&gt;
&lt;br /&gt;
Up to this point in CSE 330, you have used only one programming language: PHP.  In Module 4, you will learn a new language: Python.  Before starting this assignment, you should look over the [[Python|online textbook article about Python]].  You should be using version 3 (or greater) of Python. Additionally, you may find it helpful to look over the [[Regular Expressions|online textbook article about Regular Expressions]].&lt;br /&gt;
&lt;br /&gt;
=== Write some Regular Expressions ===&lt;br /&gt;
&lt;br /&gt;
Please write regular expressions that do each the following:&lt;br /&gt;
&lt;br /&gt;
# Match the string &amp;quot;hello world&amp;quot; in a sentence&lt;br /&gt;
# Find all words in an input string that contains three consecutive vowels, regardless of case.&lt;br /&gt;
# Match an input string that is '''entirely''' a flight code, of the format AA####, where '''AA''' is a two-letter uppercase airline code, and '''####''' is a three- or four-digit flight number&lt;br /&gt;
Examples:&lt;br /&gt;
   Note: text in ''[[red]]'' is matched by the regular expression. Each line is a separate test input string.&lt;br /&gt;
   Regex 1:  Programmers will often write ''[[hello world]]'' as their first project with a programming language.&lt;br /&gt;
   Regex 2:  The ''[[gooey]]'' peanut butter and jelly sandwich was a ''[[beauty]]''.&lt;br /&gt;
   Regex 3:  ''[[AA312]]''&lt;br /&gt;
             ''[[AA1298]]''&lt;br /&gt;
             ''[[NW1234]]''&lt;br /&gt;
             ''[[US443]]''&lt;br /&gt;
             US31344&lt;br /&gt;
             AA123 extratext&lt;br /&gt;
&lt;br /&gt;
            &lt;br /&gt;
&lt;br /&gt;
Save your regexes to a text file.  The TA will test them in regexpal on Demo Day.&lt;br /&gt;
&lt;br /&gt;
=== Baseball Stats Counter ===&lt;br /&gt;
&lt;br /&gt;
The St. Louis Cardinals are the most legendary baseball team in the national league.  In this exercise, you will be creating a Python script that reads box scores from a file and computes the Cardinals' players' batting averages in a particular season.&lt;br /&gt;
&lt;br /&gt;
==== Tips and Instructions ====&lt;br /&gt;
&lt;br /&gt;
* You should write a Python script file to solve this problem.&lt;br /&gt;
* You should use a regular expression to parse players' names, at-bats, hits, and runs from the input file.&lt;br /&gt;
* You may want to create a class to hold and compute information about each player.&lt;br /&gt;
* Your file should take one command-line argument: the path to an input file.  If no path is given, your program should print a usage message.&lt;br /&gt;
&lt;br /&gt;
==== Input ====&lt;br /&gt;
&lt;br /&gt;
Sample input files may be found here: http://classes.engineering.wustl.edu/cse330/content/cardinals/&lt;br /&gt;
&lt;br /&gt;
The top of the file contains a citation, and what follows is an entire season of Cardinals Baseball box scores.  Each game starts with a title; for example:&lt;br /&gt;
&lt;br /&gt;
 === St.Louis Cardinals vs. Chicago Cubs, 1940-04-19 ===&lt;br /&gt;
&lt;br /&gt;
What follows are the performance of each player in that game.  The format of each line is as follows:&lt;br /&gt;
&lt;br /&gt;
 XXX batted # times with # hits and # runs&lt;br /&gt;
&lt;br /&gt;
where '''XXX''' is the player's name (you may assume that the name is unique), and each '''#''' are integers representing the number of &amp;quot;at bats&amp;quot;, the number of &amp;quot;hits&amp;quot;, and the number of &amp;quot;runs&amp;quot;, respectively.&lt;br /&gt;
&lt;br /&gt;
==== Output ====&lt;br /&gt;
&lt;br /&gt;
Your script needs to output all players' batting average across the season.  A player's batting average is that player's total hits divided by that player's total at-bats throughout the entire season.  For example, Johnny Hopp was at bat 149 times in 1940, and he had 41 hits, so his batting average was 0.275.&lt;br /&gt;
&lt;br /&gt;
Each line in the output should have the format:&lt;br /&gt;
&lt;br /&gt;
 XXX: #.###&lt;br /&gt;
&lt;br /&gt;
where '''XXX''' is the player's name, and '''#.###''' is the player's batting average, '''rounded''' (not truncated) to three decimal places.&lt;br /&gt;
&lt;br /&gt;
The players should be sorted by batting average, with the highest batting average on top.  If two players have the exact same batting average (before rounding occurs), the order between those two players is unimportant.&lt;br /&gt;
&lt;br /&gt;
For example, the correct output for the 1940 season is:&lt;br /&gt;
&amp;lt;!-- Jimmy Brown was 0.280 and Ira Hutchinson was 0.125 --&amp;gt;&lt;br /&gt;
&amp;lt;source lang=&amp;quot;text&amp;quot;&amp;gt;&lt;br /&gt;
Pepper Martin: 0.316&lt;br /&gt;
Walker Cooper: 0.316&lt;br /&gt;
Johnny Mize: 0.314&lt;br /&gt;
Ernie Koy: 0.310&lt;br /&gt;
Enos Slaughter: 0.306&lt;br /&gt;
Joe Medwick: 0.304&lt;br /&gt;
Terry Moore: 0.304&lt;br /&gt;
Joe Orengo: 0.286&lt;br /&gt;
Jimmy Brown: 0.280&lt;br /&gt;
Marty Marion: 0.279&lt;br /&gt;
Don Gutteridge: 0.276&lt;br /&gt;
Johnny Hopp: 0.275&lt;br /&gt;
Creepy Crespi: 0.273&lt;br /&gt;
Mickey Owen: 0.265&lt;br /&gt;
Bill DeLancey: 0.250&lt;br /&gt;
Don Padgett: 0.242&lt;br /&gt;
Stu Martin: 0.238&lt;br /&gt;
Eddie Lake: 0.222&lt;br /&gt;
Hal Epps: 0.214&lt;br /&gt;
Lon Warneke: 0.209&lt;br /&gt;
Harry Walker: 0.185&lt;br /&gt;
Max Lanier: 0.179&lt;br /&gt;
Bill McGee: 0.178&lt;br /&gt;
Carl Doyle: 0.174&lt;br /&gt;
Mort Cooper: 0.157&lt;br /&gt;
Clyde Shoun: 0.145&lt;br /&gt;
Carden Gillenwater: 0.130&lt;br /&gt;
Bob Bowman: 0.067&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Grading ==&lt;br /&gt;
&lt;br /&gt;
We will be grading the following aspects of your work.  There are 50 points total.&lt;br /&gt;
&lt;br /&gt;
'''Assignments must be committed to Bitbucket by the end of class on the due date (commit early and often). Failing to commit by the end of class on the due date will result in a 0. ''' &lt;br /&gt;
&lt;br /&gt;
Upload your baseball code, a file with your Regular expressions, and a screenshot of your python output onto Bitbucket.&lt;br /&gt;
&lt;br /&gt;
# '''Regular Expressions (15 Points):'''&lt;br /&gt;
#* Regular Expression 1 Correct and saved in a file named &amp;lt;code&amp;gt;regex1.txt&amp;lt;/code&amp;gt; (5 points)&lt;br /&gt;
#* Regular Expression 2 Correct and saved in a file named &amp;lt;code&amp;gt;regex2.txt&amp;lt;/code&amp;gt;(5 points)&lt;br /&gt;
#* Regular Expression 3 Correct and saved in a file named &amp;lt;code&amp;gt;regex3.txt&amp;lt;/code&amp;gt;(5 points)&lt;br /&gt;
# '''Baseball Stats Counter (35 Points):'''&lt;br /&gt;
#* Solution is written entirely in Python and saved in a file named &amp;lt;code&amp;gt;baseball.py&amp;lt;/code&amp;gt; (8 points)&lt;br /&gt;
#* Correct usage of one or more regular expressions to parse and extract data from each line of the input file (8 points)&lt;br /&gt;
#* Script prints a usage message if a command line argument is not present (4 points)&lt;br /&gt;
#* Output is correct for all test cases (15 points)&lt;br /&gt;
#*: ''This includes sorting and rounding.''&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 4]]&lt;br /&gt;
[[Category:Modules]]&lt;/div&gt;</summary>
		<author><name>Alex</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Module_1&amp;diff=2498</id>
		<title>Module 1</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Module_1&amp;diff=2498"/>
		<updated>2018-01-31T00:56:17Z</updated>

		<summary type="html">&lt;p&gt;Alex: /* Grading */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;__NOTOC__ &lt;br /&gt;
Module 1 introduces the fundamentals of HTML and CSS.  You will first make a static document using HTML and CSS, and then you will make a portal to a DuckDuckGo search.  This module is worth 50 points.&lt;br /&gt;
&lt;br /&gt;
== Reading ==&lt;br /&gt;
&lt;br /&gt;
The following articles on the online class wiki textbook contain information that will help you complete the assignment.&lt;br /&gt;
&lt;br /&gt;
* [[Git]]&lt;br /&gt;
* [[HTML and CSS]]&lt;br /&gt;
* [[HTML Forms]]&lt;br /&gt;
&lt;br /&gt;
== Assignments ==&lt;br /&gt;
&lt;br /&gt;
=== Write a Birthday Card ===&lt;br /&gt;
&lt;br /&gt;
'''Write a birthday card to a friend or family member using HTML and CSS.'''  Use HTML to define the content of the card (like the headings and the paragraphs), and use CSS to define the appearance.  Some ideas:&lt;br /&gt;
&lt;br /&gt;
* Make the background-color of the page baby blue and use purple ink to write a card to a little boy&lt;br /&gt;
* Make the text big and include pictures of hearts&lt;br /&gt;
* Use a font with text shadows (more advanced)&lt;br /&gt;
&lt;br /&gt;
Use this opportunity to experiment with the plethora of CSS properties.  Remember that you're in a computer science class (not an art class), so we don't care if your card looks ugly.  The main thing is that you learn HTML and CSS and use them appropriately.&lt;br /&gt;
&lt;br /&gt;
==== How to Edit Your File ====&lt;br /&gt;
&lt;br /&gt;
Starting in Module 2, we will be using Komodo Edit as our primary development tool.  However, for the purposes of this exercise, we want you to edit your HTML file using a more basic text editor. '''If you already have a text editor that works for you, like [https://www.sublimetext.com/ Sublime Text], [https://atom.io/ Atom], Vim, or Emacs, feel free to use it for the entirety of this course. The same is true if you're already a fan of an IDE - you don't ''have'' to use any of the suggestions below.'''&lt;br /&gt;
&lt;br /&gt;
* On Windows, consider Notepad++.  This is already installed for you in the CEC labs.  If you prefer to use your personal computer, you can download it from [https://notepad-plus-plus.org/ here].&lt;br /&gt;
&amp;lt;!-- As of February 11th, 2017, TextWrangler's website has an improperly configured SSL certificate, so we can't link to HTTPS yet. --&amp;gt;&lt;br /&gt;
* On Mac OS X, consider TextWrangler.  You can download it from [http://www.barebones.com/products/textwrangler/ here] or from the Mac App Store.&lt;br /&gt;
* Most Linux distributions come with gedit pre-installed, which you can use for this lab.&lt;br /&gt;
&lt;br /&gt;
Please save your file as ''birthday.html'' from the plain text editor of your choice.&lt;br /&gt;
&lt;br /&gt;
'''Important Note:''' Writing your web page in a word processor like Microsoft Word or even WordPad or TextEdit will ''not'' work.  You need a plain text editor.&lt;br /&gt;
&lt;br /&gt;
==== How to View Your HTML Document ====&lt;br /&gt;
&lt;br /&gt;
Once you have ''birthday.html'', you can open it using your favorite web browser (like Firefox).  For the purposes of this exercise, it suffices to right-click the file and tell it to &amp;quot;open with&amp;quot; Firefox.  When the file opens, it should be under the file:/// protocol.&lt;br /&gt;
&lt;br /&gt;
In Module 2, we will install a web server that serves up pages on the http:// and https:// protocols.&lt;br /&gt;
&lt;br /&gt;
==== Validation ====&lt;br /&gt;
&lt;br /&gt;
'''Your birthday card must pass the W3C Validators for both HTML and CSS with no errors.'''  You can upload your HTML to [https://validator.w3.org/ the HTML validator] and your CSS to [https://jigsaw.w3.org/css-validator/ the CSS validator].&lt;br /&gt;
&lt;br /&gt;
For more information on validation, see the HTML and CSS guide: [[HTML and CSS#Validation]]&lt;br /&gt;
&lt;br /&gt;
=== Make a Portal to a DuckDuckGo Search ===&lt;br /&gt;
&lt;br /&gt;
'''Write an HTML document containing a form that searches DuckDuckGo's web site.'''  You should be able to type in a search term and have your form load the DuckDuckGo search page.&lt;br /&gt;
&lt;br /&gt;
# Visit [https://www.duckduckgo.com/ www.duckduckgo.com].  Search for something easy to spot in the URL, like &amp;quot;QUERY&amp;quot;.&lt;br /&gt;
# Look at the URL of the search page.  What is the script URL?  What is the query variable?&lt;br /&gt;
# Make an HTML document containing a text field and a submit button.  Typing a search query into the text field and pressing the submit button should load the DuckDuckGo search page.&lt;br /&gt;
&lt;br /&gt;
== Grading ==&lt;br /&gt;
&lt;br /&gt;
We will be grading the following aspects of your work.  There are 50 points total.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Assignments must be committed to Bitbucket by the end of class on the due date. Commit early and often. Failing to commit by the end of class on the due date will result in a 0. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# '''Birthday Card (30 Points):'''&lt;br /&gt;
#* Correct usage of HTML and CSS in your birthday card (10 points).&lt;br /&gt;
#*: ''Make sure that you use HTML for &amp;quot;content&amp;quot; and CSS for &amp;quot;appearance.&amp;quot;  Don't write inline styles: use a separate stylesheet and link your HTML file to it.''&lt;br /&gt;
#* Experimenting with at least 5 different CSS properties in your birthday card (10 points).&lt;br /&gt;
#* Birthday card passes the W3C validation for HTML 5 and CSS. (10 points).&lt;br /&gt;
# '''Search Portal (10 Points):'''&lt;br /&gt;
#* DuckDuckGo search portal is functional (10 points).&lt;br /&gt;
# '''Account Creation and Version Control (10 Points):'''&lt;br /&gt;
#* Bitbucket account created (2 Points)&lt;br /&gt;
#* Module 1 repo created using the link provided on Piazza (2 Points)&lt;br /&gt;
#* Account created on Amazon Web Services and an image file containing a screenshot of your account page pushed to Bitbucket. (4 Points)&lt;br /&gt;
#* Files pushed to repo on Bitbucket using Git (2 Points)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 1]]&lt;br /&gt;
[[Category:Modules]]&lt;/div&gt;</summary>
		<author><name>Alex</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Module_2&amp;diff=2497</id>
		<title>Module 2</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Module_2&amp;diff=2497"/>
		<updated>2018-01-27T01:56:24Z</updated>

		<summary type="html">&lt;p&gt;Alex: /* Grading */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;__NOTOC__ &lt;br /&gt;
Module 2 introduces you to Linux, a command-line environment, the Apache web server, and PHP.  You will create and configure your own cloud instance, install Apache and related software, and then form groups to make a simple file sharing site.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;span style=&amp;quot;font-size:1.3em; line-height:1.2em; color:blue;&amp;quot;&amp;gt;'''DO NOT WAIT UNTIL THE LAST MINUTE TO START ON THIS (or any) MODULE!'''  The most common reason students perform poorly in this class is procrastination.  You have been warned.&amp;lt;/span&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Reading ==&lt;br /&gt;
&lt;br /&gt;
The following articles on the online class wiki textbook contain information that will help you complete the assignments.&lt;br /&gt;
&lt;br /&gt;
* [[Linux]]&lt;br /&gt;
* [[Bash]]&lt;br /&gt;
* [[Amazon Web Services]]&lt;br /&gt;
* [[SSH]]&lt;br /&gt;
* [[Apache]]&lt;br /&gt;
* [[PHP]]&lt;br /&gt;
* [[Workflow]]&lt;br /&gt;
* [[Web Application Security, Part 1]]&lt;br /&gt;
&lt;br /&gt;
== Individual Assignments ==&lt;br /&gt;
&lt;br /&gt;
{{RequiredInstructions|content=&lt;br /&gt;
&lt;br /&gt;
&amp;lt;span style=&amp;quot;color:red&amp;quot;&amp;gt;There are a lot of wiki pages that you need to read in order to complete the individual portion of Module 2.  The wiki pages contain an assortment of required steps, optional steps, and information.  To make things easier, we have highlighted the ''required steps'' with a red bar, like you see on the left of this message.  Do not skip anything marked with a red bar, or else you will not have a perfectly configured instance.&amp;lt;/span&amp;gt;&lt;br /&gt;
&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
=== Learn About Linux ===&lt;br /&gt;
&lt;br /&gt;
Linux is an open-source operating system based on UNIX. Linux is highly versatile and is used in a wide range of applications.&lt;br /&gt;
&lt;br /&gt;
If you are not a Linux guru, read the Linux guide to get started: [[Linux]]&lt;br /&gt;
&lt;br /&gt;
=== Windows Users Only: Enable Windows Subsystem for Linux (WSL) or Install Cygwin ===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
You will need WSL or Cygwin in order to log into and configure your EC2 instance. Cygwin is already installed on the CEC machines. If you're using Windows 10, you can use WSL, which is an officially-supported way of accessing a Linux terminal on Windows. If not, you'll have to use Cygwin. Instructions for installing either on your personal machine are located in [[Workflow#Cygwin|the Workflow guide]].&lt;br /&gt;
&lt;br /&gt;
Mac OS X users should located the &amp;quot;Terminal&amp;quot; application, which is installed by default; you will need this in the coming steps.&lt;br /&gt;
&lt;br /&gt;
=== Create an AWS EC2 Instance ===&lt;br /&gt;
&lt;br /&gt;
Once you understand [[Linux]], you need to set up your Amazon EC2 Instance.  Use the AWS article to guide you through the process: [[Amazon Web Services]]&lt;br /&gt;
&lt;br /&gt;
=== Configure SSH ===&lt;br /&gt;
&lt;br /&gt;
Follow the instructions in [[SSH#SSH Configuration|the SSH guide]] to do the following:&lt;br /&gt;
&lt;br /&gt;
# Create your own SSH key pair&lt;br /&gt;
# Log in as the default user to your EC2 instance&lt;br /&gt;
# Create a new user&lt;br /&gt;
# Give the new user your SSH public key&lt;br /&gt;
&lt;br /&gt;
From now on, when you need to log into your EC2 instance as an administrator, just pop up a terminal and run:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ ssh your-username@ec2-xx-xx-xx-xx.compute-1.amazonaws.com&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Install Essential Packages ===&lt;br /&gt;
&lt;br /&gt;
Recall that software installation in Linux instances is usually handled through a package manager, like '''yum'''.  For more information, refer to [[Linux#Repository-Based Package Managers|the Linux guide]].&lt;br /&gt;
&lt;br /&gt;
To make sure everything is working properly, '''install your first package(s) according to the ''Essential Packages'' subsection in the Linux guide.'''&lt;br /&gt;
&lt;br /&gt;
=== Set the Timezone ===&lt;br /&gt;
&lt;br /&gt;
'''Set your server to use US Central time (America/Chicago).'''  Instructions are in the Linux guide: [[Linux#Synchronizing Date and Time]]&lt;br /&gt;
&lt;br /&gt;
=== Set Up the Apache Web Server ===&lt;br /&gt;
&lt;br /&gt;
You need to '''install the Apache web server on your EC2 instance'''.  Refer to [[Apache|the Apache guide]].&lt;br /&gt;
&lt;br /&gt;
In order for your web server to be accessible, you need to '''open up Port 80 on your EC2 instance'''.  Instructions are in the AWS guide: [[Amazon Web Services#Enabling Web Access to your EC2 Instance]]&lt;br /&gt;
&lt;br /&gt;
'''Enable the UserDir module in Apache.'''  Instructions are in the Apache guide: [[Apache#The UserDir Module]]&lt;br /&gt;
&lt;br /&gt;
=== Install PHP ===&lt;br /&gt;
&lt;br /&gt;
You need to '''install PHP on your EC2 server'''.  Instructions are at the top of the PHP guide: [[PHP]]&lt;br /&gt;
&lt;br /&gt;
You need to '''configure PHP to show errors'''.  Instructions are immediately below installation in the PHP guide.&lt;br /&gt;
&lt;br /&gt;
=== Learn about the PHP Language ===&lt;br /&gt;
&lt;br /&gt;
Before you can continue, you will need to make yourself acquainted with PHP language components.  Read the PHP guide for an overview: [[PHP#PHP Language Components]]&lt;br /&gt;
&lt;br /&gt;
=== Set Up your Workspace ===&lt;br /&gt;
&lt;br /&gt;
You are now ready to set up the workspace that you will be using for the rest of the semester.  Follow the instructions in [[Workflow]] to:&lt;br /&gt;
&lt;br /&gt;
# Make an account on Bitbucket&lt;br /&gt;
# Setup a repo using the CSE 330 Repo Creation Tool&lt;br /&gt;
# Install SourceTree&lt;br /&gt;
# '''Windows only:''' Set up Pageant so that SourceTree can conect to Bitbucket&lt;br /&gt;
# Clone your CSE 330 repo from Bitbucket&lt;br /&gt;
# Install Komodo Edit&lt;br /&gt;
# Create a Komodo Edit Project inside of your Git repository&lt;br /&gt;
# Add the ''*.komodoproject'' file to ''.gitignore''&lt;br /&gt;
# Install FileZilla&lt;br /&gt;
# Connect FileZilla to your remote instance&lt;br /&gt;
&lt;br /&gt;
=== Calculator ===&lt;br /&gt;
&lt;br /&gt;
'''Make a calculator using PHP and an HTML form.'''  The form should have two inputs.  The form should submit a GET request either back to the same page or to a different results page.  The calculator should support addition, subtraction, multiplication, and division by means of a radio button group on the page.  (Consider edge cases!)&lt;br /&gt;
&lt;br /&gt;
== Group Project ==&lt;br /&gt;
&lt;br /&gt;
You will work in pairs (that means you and one other person) on this project.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;span style=&amp;quot;font-size:1.3em; line-height:1.2em; color:blue;&amp;quot;&amp;gt;In this module, and all future modules, the group portion builds off of material you learn in the individual portion.  You should therefore complete the individual portions prior to working on the group portions.  (Trust us: it will make your life easier!)&amp;lt;/span&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Important Reminder:''' frequently commit your work to your repository as a backup!&lt;br /&gt;
&lt;br /&gt;
=== Simple File Sharing Site ===&lt;br /&gt;
&lt;br /&gt;
You will be making a simple file sharing site that supports uploading, viewing, and deleting files associated with various users.  Details:&lt;br /&gt;
&lt;br /&gt;
* You should have a file named '''users.txt''' stored in a secure place on your filesystem.  It should have at least three usernames, with one username per line.&lt;br /&gt;
*: Passwords add an extra layer of complexity (encryption) that we will cover in Module 3.  You will not earn credit for implementing passwords as your creative portion for this module.&lt;br /&gt;
* Users of the file sharing site should be able to enter their username and then log in.&lt;br /&gt;
*: You may implement logins using session variables, or you may implement them using a GET parameter that is passed between pages.  You will need to always use sessions starting in Module 3.&lt;br /&gt;
* Users should see a list of all files associated with their username after the log in.&lt;br /&gt;
* Users should be able to view, upload, and delete files associated with their username.&lt;br /&gt;
* The URI should NOT reveal the internal file structure of your web site.&lt;br /&gt;
** Example of what not to do:  http://www.example.com/download.php?file=/home/paul/file.txt&lt;br /&gt;
** Another bad example:  http://www.example.com/~user/file.txt&lt;br /&gt;
** Good example: http://www.example.com/view.php?user=music&amp;amp;name=file.txt&lt;br /&gt;
*: In general, don't reveal any internal information about the site.&lt;br /&gt;
*: '''Food for thought:''' Given that Apache processes (with the exception of the main process) do not run as root, but rather as the user apache, how can you allow both your user account and the php scripts to read and write the &lt;br /&gt;
*:necessary files?&lt;br /&gt;
*:: ''Hint:'' You shouldn't be storing the user-uploaded files in public_html (that is only the place for your own web-page files), &lt;br /&gt;
*::''Hint number 2:''  you will need to use chown to change permissions to let user apache have permissions on the user-files (that '''are not''' in the public_html folder). If you don't know what this does or how to do this, look at the [[Apache]] page&lt;br /&gt;
* You should customize your file sharing site by implementing an additional feature or two as part of the '''creative portion'''.&lt;br /&gt;
&lt;br /&gt;
You will probably find the PHP guide on this wiki to be helpful: [[PHP#Other PHP Tips]]&lt;br /&gt;
&lt;br /&gt;
=== Web Security and Validation ===&lt;br /&gt;
&lt;br /&gt;
Your project needs to demonstrate that thought was put into web security and best practice.  For more information, see this week's Web Application Security guide: [[Web Application Security, Part 1]]&lt;br /&gt;
&lt;br /&gt;
In particular:&lt;br /&gt;
&lt;br /&gt;
* '''Your application needs to follow the conventions of FIEO (Filter Input and Escape Output)'''.  Things you should filter include file names, usernames, and so on.&lt;br /&gt;
* '''Your project must pass the W3C Validator with no errors'''.  For more information, see the HTML and CSS guide: [[HTML and CSS#Validation]]&lt;br /&gt;
&lt;br /&gt;
== Grading ==&lt;br /&gt;
&lt;br /&gt;
We will be grading the following aspects of your work.  There are 100 points total. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Assignments must be committed to BitBucket by the end of class on the due date. Commit early and often. Failing to commit by the end of class on the due date will result in a 0. &lt;br /&gt;
&lt;br /&gt;
_____________&lt;br /&gt;
&lt;br /&gt;
# '''Cloud Instance and Web Server (30 Points):'''&lt;br /&gt;
#* You can SSH into your instance using your own custom username and SSH key. Put a screenshot in your repository of your terminal SSH-ing into your instance (15 points)&lt;br /&gt;
#* Your custom username is able to perform SUDO commands. Put a screenshot in your repository of you successfully executing a command with sudo (5 points)&lt;br /&gt;
#* The time zone is correct on your instance. Put a screenshot in your repository of the results of the `date` command (5 points)&lt;br /&gt;
#* The UserDir Apache module is working. Place a file in /home/&amp;lt;username&amp;gt;/public_html and link to the file in your README.md (5 points)&lt;br /&gt;
# '''PHP Calculator (15 Points):'''&lt;br /&gt;
#* The calculator is able to perform all four functions with floating point numbers (2 points each, 8 points in total)&lt;br /&gt;
#* Each function is given as a radio button choice (4 points)&lt;br /&gt;
#* The calculator page passes the W3C HTML validator (3 points)&lt;br /&gt;
#* '''''Make sure you have a README.md file in your individual repo with the the link to your calculator.''''' See the Creative Portion section for more information about .md files.&lt;br /&gt;
# '''File Sharing Site (40 Points):'''&lt;br /&gt;
#* '''''File Management (25 Points):'''''&lt;br /&gt;
#** Users should not be able to see any files until they enter a username and log in (4 points)&lt;br /&gt;
#**: ''Remember that users.txt should be stored in a secure location on your filesystem.  That is, '''you should not be able to type any URL into your browser and see the raw users.txt file!'''''&lt;br /&gt;
#** Users can see a list of all files they have uploaded (4 points)&lt;br /&gt;
#** Users can open files they have previously uploaded (5 points)&lt;br /&gt;
#**: ''Note: Users should be able to open not only plain text files but also other file formats: images, spreadsheets, etc.''&lt;br /&gt;
#** Users can upload files (4 points)&lt;br /&gt;
#**: ''Note: Like users.txt, uploaded files should be stored in a secure location on your filesystem.  That is, '''do not keep your uploads directory underneath a directory served by Apache!'''''&lt;br /&gt;
#** Users can delete files.  If a file is &amp;quot;deleted&amp;quot;, it should actually be removed from the filesystem (4 points)&lt;br /&gt;
#** The directory structure is hidden (2 points)&lt;br /&gt;
#** Users can log out (2 points)&lt;br /&gt;
#**: ''Note: If using session variables, you must ''actually'' log out the user by destroying their session; i.e., don't just redirect them to the login screen.''&lt;br /&gt;
#* '''''Best Practices (10 Points):'''''&lt;br /&gt;
#** Code is well formatted and easy to read, with proper commenting (4 points)&lt;br /&gt;
#** The site follows the FIEO philosophy (3 points)&lt;br /&gt;
#** All pages pass the W3C validator (3 points)&lt;br /&gt;
#* '''''Usability (5 Points):'''''&lt;br /&gt;
#** Site is intuitive to use and navigate (4 points)&lt;br /&gt;
#** Site is visually appealing (1 point)&lt;br /&gt;
# '''Creative Portion (15 Points)''' (see below)&lt;br /&gt;
#* '''''Make sure you have a README.md file in your group repo with the following:'''''&lt;br /&gt;
#** An .md file is a plain text file called a markdown file  [https://guides.github.com/features/mastering-markdown/ ] .  &lt;br /&gt;
#***The contents of your README.md file are shown on your repo, making it easier for us to grade&lt;br /&gt;
#*** You may style the page with bolding, hyperlings, images, block quotes and lists&lt;br /&gt;
#*** [http://dillinger.io/ This online markdown editor] makes it easy to learn this format  &lt;br /&gt;
#** The link to your file sharing site. '''''We need this to grade your work.'''''&lt;br /&gt;
#** A brief description of what you did for your creative portion&lt;br /&gt;
#** Any additional login details needed for the TA&lt;br /&gt;
&lt;br /&gt;
=== Creative Portion ===&lt;br /&gt;
&lt;br /&gt;
This module and all future modules will require that you invest some time into creating additional features for your group project.  Plan to invest at least 60 minutes of your time into the creative portion.&lt;br /&gt;
&lt;br /&gt;
* The creative portion is an opportunity for you to learn the material of your own interest.&lt;br /&gt;
* You will not earn credit for a creative-portion feature that simply rehashes something you've already done in a previous module.&lt;br /&gt;
&lt;br /&gt;
If you need ideas for a creative portion, or if you want to know whether or not your creative portion idea is &amp;quot;hard enough&amp;quot;, ask a TA.&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 2]]&lt;br /&gt;
[[Category:Modules]]&lt;/div&gt;</summary>
		<author><name>Alex</name></author>
		
	</entry>
</feed>