<?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=Connor</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=Connor"/>
	<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Special:Contributions/Connor"/>
	<updated>2026-11-15T18:16:47Z</updated>
	<subtitle>User contributions</subtitle>
	<generator>MediaWiki 1.34.4</generator>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Socket.IO&amp;diff=2716</id>
		<title>Socket.IO</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Socket.IO&amp;diff=2716"/>
		<updated>2020-04-10T16:21:35Z</updated>

		<summary type="html">&lt;p&gt;Connor: /* Installing Socket.IO */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;AJAX is useful when one-way communication is satisfactory for your web application.  However, what happens when you need two-way communication, like a chat client or multiplayer game?  AJAX isn't the tool for the job.  This is where '''Socket.IO''' comes in.&lt;br /&gt;
&lt;br /&gt;
Built to work natively with Node.JS, Socket.IO enables asynchronous, two-way communication between the server and the client.  This means that the server can send messages to the client without the client having to ask first, as is the case with AJAX.  As you learn Socket.IO, Non-Blocking I/O will become your best friend!&lt;br /&gt;
&lt;br /&gt;
== Installing Socket.IO ==&lt;br /&gt;
&lt;br /&gt;
Before you install Socket.IO, you need to install [[Node.JS]] and NPM, which is often installed automatically when you install Node.JS.&lt;br /&gt;
&lt;br /&gt;
The NPM package manager is different from many of the package managers we've used in that you need to install remote packages for every project in which you use them.  This means that you need to '''cd''' to the working directory in which you want to keep your Node.JS JavaScript file, ''and then'' run the following command:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ npm install socket.io --save&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Note:''' If you pass the ''-g'' to ''npm install'', then the package will be installed &amp;quot;globally&amp;quot; on your instance, so all Node.JS projects will be able to use it.  However, this is not recommended for all projects.  [http://blog.nodejs.org/2011/04/06/npm-1-0-link/ Read Node.JS's justification here.]&lt;br /&gt;
&lt;br /&gt;
== Messaging ==&lt;br /&gt;
&lt;br /&gt;
Socket.IO works by having clients send messages to the server and the server send messages to clients.  For example, consider the code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// Computer A:&lt;br /&gt;
socket.emit(&amp;quot;info&amp;quot;, {&lt;br /&gt;
	&amp;quot;hello&amp;quot;: &amp;quot;world&amp;quot;&lt;br /&gt;
});&lt;br /&gt;
&lt;br /&gt;
// Computer B:&lt;br /&gt;
socket.on(&amp;quot;info&amp;quot;, function (data) {&lt;br /&gt;
	console.log(data.hello);&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Computer A could be ''either the client or the server'', and Computer B would be the other.  When '''socket.emit(name, data)''' is called on either end, the callback function in '''socket.on''' that listens for the message named ''name'' is called with the ''data'' from '''socket.emit'''.&lt;br /&gt;
&lt;br /&gt;
== A First Socket.IO Application: Chat Server and Client ==&lt;br /&gt;
&lt;br /&gt;
Building a chat client is surprising simple using Socket.IO and Node.JS, and it gives great insight into the workings of Socket.IO.  Take the time to understand how this example works, and ask questions; if you understand this, the group portion will be easy!&lt;br /&gt;
&lt;br /&gt;
=== The Chat Server ===&lt;br /&gt;
&lt;br /&gt;
You can make a file called ''chat-server.js'' with the following code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// Require the packages we will use:&lt;br /&gt;
var http = require(&amp;quot;http&amp;quot;),&lt;br /&gt;
	socketio = require(&amp;quot;socket.io&amp;quot;),&lt;br /&gt;
	fs = require(&amp;quot;fs&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
// Listen for HTTP connections.  This is essentially a miniature static file server that only serves our one file, client.html:&lt;br /&gt;
var app = http.createServer(function(req, resp){&lt;br /&gt;
	// This callback runs when a new connection is made to our HTTP server.&lt;br /&gt;
	&lt;br /&gt;
	fs.readFile(&amp;quot;client.html&amp;quot;, function(err, data){&lt;br /&gt;
		// This callback runs when the client.html file has been read from the filesystem.&lt;br /&gt;
		&lt;br /&gt;
		if(err) return resp.writeHead(500);&lt;br /&gt;
		resp.writeHead(200);&lt;br /&gt;
		resp.end(data);&lt;br /&gt;
	});&lt;br /&gt;
});&lt;br /&gt;
app.listen(3456);&lt;br /&gt;
&lt;br /&gt;
// Do the Socket.IO magic:&lt;br /&gt;
var io = socketio.listen(app);&lt;br /&gt;
io.sockets.on(&amp;quot;connection&amp;quot;, function(socket){&lt;br /&gt;
	// This callback runs when a new Socket.IO connection is established.&lt;br /&gt;
	&lt;br /&gt;
	socket.on('message_to_server', function(data) {&lt;br /&gt;
		// This callback runs when the server receives a new message from the client.&lt;br /&gt;
		&lt;br /&gt;
		console.log(&amp;quot;message: &amp;quot;+data[&amp;quot;message&amp;quot;]); // log it to the Node.JS output&lt;br /&gt;
		io.sockets.emit(&amp;quot;message_to_client&amp;quot;,{message:data[&amp;quot;message&amp;quot;] }) // broadcast the message to other users&lt;br /&gt;
	});&lt;br /&gt;
});&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above code makes a simple HTTP server that responds to all connections with the contents of the file &amp;quot;client.html&amp;quot;, which we will make in the next step.  We tell Socket.IO to listen for &amp;quot;message&amp;quot; events, and when it hears one, it should emit a new event called &amp;quot;someone said&amp;quot; back to the connected clients.&lt;br /&gt;
&lt;br /&gt;
=== The Chat Client ===&lt;br /&gt;
&lt;br /&gt;
Here is a front-end client that could work with our server, in ''client.html'':&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&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;&lt;br /&gt;
      &amp;lt;script src=&amp;quot;/socket.io/socket.io.js&amp;quot;&amp;gt;&amp;lt;/script&amp;gt;&lt;br /&gt;
      &amp;lt;script type =&amp;quot;text/javascript&amp;quot;&amp;gt;&lt;br /&gt;
&lt;br /&gt;
      var socketio = io.connect();&lt;br /&gt;
      socketio.on(&amp;quot;message_to_client&amp;quot;,function(data) {&lt;br /&gt;
         //Append an HR thematic break and the escaped HTML of the new message&lt;br /&gt;
         document.getElementById(&amp;quot;chatlog&amp;quot;).appendChild(document.createElement(&amp;quot;hr&amp;quot;));&lt;br /&gt;
         document.getElementById(&amp;quot;chatlog&amp;quot;).appendChild(document.createTextNode(data['message']));&lt;br /&gt;
      });&lt;br /&gt;
&lt;br /&gt;
      function sendMessage(){&lt;br /&gt;
         var msg = document.getElementById(&amp;quot;message_input&amp;quot;).value;&lt;br /&gt;
         socketio.emit(&amp;quot;message_to_server&amp;quot;, {message:msg});&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
      &amp;lt;/script&amp;gt;&lt;br /&gt;
   &amp;lt;/head&amp;gt;&lt;br /&gt;
   &amp;lt;body&amp;gt;&lt;br /&gt;
      &amp;lt;input type=text&amp;quot; id=&amp;quot;message_input&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;button onclick=&amp;quot;sendMessage()&amp;quot;&amp;gt;send&amp;lt;/button&amp;gt;&lt;br /&gt;
      &amp;lt;div id=&amp;quot;chatlog&amp;quot;&amp;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;
&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Note:''' This example passes strings as the event data, but you can pass any JavaScript datatype, including object literals.&lt;br /&gt;
&lt;br /&gt;
To see this in action, save these two files in the same directory, cd over to the directory, and start the server:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;$ node chat-server.js&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Fire up your favorite browser and navigate to http://localhost:3456/.  Open the page in two windows.  Violà: you have your (very basic) chat client!&lt;br /&gt;
&lt;br /&gt;
== Resources ==&lt;br /&gt;
&lt;br /&gt;
The [http://socket.io/ Socket.IO web site] has concise examples that tell you pretty much all you need to know in order to build a functional Socket.IO web application.&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 7]]&lt;/div&gt;</summary>
		<author><name>Connor</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Node.JS&amp;diff=2715</id>
		<title>Node.JS</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Node.JS&amp;diff=2715"/>
		<updated>2020-04-10T16:21:00Z</updated>

		<summary type="html">&lt;p&gt;Connor: /* Installing Packages */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;AJAX is a useful technology for web applications that need to pull periodic updates from your server.  But what do you do when you have thousands of clients all requesting data that changes real-time?  A PHP+AJAX approach could choke without a lot of effort on your part.  It is situations like these that Node.js comes to the rescue. Node.js is a web framework, made in JavaScript, that's become extremely popular over the last few years.&lt;br /&gt;
&lt;br /&gt;
In general, JavaScript frameworks are very trendy right now; it can be hard to keep up with the new cool thing. In fact, there's a joke website https://dayssincelastjavascriptframework.com/, that &amp;quot;tracks&amp;quot; how long it's been since a new framework has come out.&lt;br /&gt;
&lt;br /&gt;
== Non-Blocking I/O ==&lt;br /&gt;
&lt;br /&gt;
You dabbled in the concept of non-blocking I/O when you implemented AJAX in the previous JavaScript module.  Node.js uses this execution model at its core.&lt;br /&gt;
&lt;br /&gt;
The core idea is the use of '''''anonymous functions''''' as ''callbacks'' for processing the results of intensive operations.  Consider the pseudo-code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// Blocking I/O Pseudo-Code&lt;br /&gt;
&lt;br /&gt;
var data = database.query(&amp;quot;select * from news&amp;quot;);&lt;br /&gt;
print data[0].title;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above pseudo-code queries a database, saves the result of the query in a variable named ''data'', and then prints out the first title in ''data''.  The problem arises when multiple clients all want to access the server at the same time.  ''In a blocking I/O model, a client needs to wait until all other clients are finished before it can start its process.''  With intensive operations and thousands of clients, this can easily crash your server!&lt;br /&gt;
&lt;br /&gt;
The solution is to use ''non-blocking I/O''.  Consider this revised pseudo-code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// Non-Blocking I/O Pseudo-Code&lt;br /&gt;
&lt;br /&gt;
database.query(&amp;quot;select * from news&amp;quot;, function(data){&lt;br /&gt;
	print data[0].title;&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The revised pseudo-code achieves the same end result as the first version.  However, ''it allows other clients to perform tasks while this process is waiting for the database to be queried!''  The code occurs in two parts: first, we start the query.  Second, ''when the query is complete'', our '''anonymous callback function''' is executed.  In Node.js, callback functions are usually passed one or more parameters.&lt;br /&gt;
&lt;br /&gt;
Better yet, with non-blocking I/O, you have no concurrency issues, because everything runs in just one thread.  Nifty!&lt;br /&gt;
&lt;br /&gt;
== Installing Node.js ==&lt;br /&gt;
&lt;br /&gt;
Run the following commands to install Node and NPM:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ curl --silent --location https://rpm.nodesource.com/setup_12.x | sudo bash -&lt;br /&gt;
$ sudo yum install -y nodejs&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;!-- The unofficial instructions for installing Node.js can be found here: https://gist.github.com/isaacs/579814&lt;br /&gt;
&lt;br /&gt;
There are several choices, but my favorite is probably ''use-nave-no-shell.sh''.&lt;br /&gt;
&lt;br /&gt;
The instructions at the above link have a couple bugs.  If you run this sequence of commands, Node and NPM will install correctly:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ mkdir ~/.nave&lt;br /&gt;
$ cd ~/.nave&lt;br /&gt;
$ wget http://github.com/isaacs/nave/raw/master/nave.sh&lt;br /&gt;
$ sudo ln -s $PWD/nave.sh /usr/local/bin/nave&lt;br /&gt;
$ chmod a+x nave.sh&lt;br /&gt;
$ sudo chown -R $USER:$USER /usr/local&lt;br /&gt;
$ nave usemain stable&lt;br /&gt;
$ curl -L https://www.npmjs.org/install.sh | sh&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Your First Node.js Application: Hello World ==&lt;br /&gt;
&lt;br /&gt;
Let's try running the example application given on the front page of nodejs.org:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
const http = require('http');&lt;br /&gt;
http.createServer(function (req, res) {&lt;br /&gt;
	res.writeHead(200, {&lt;br /&gt;
		'Content-Type': 'text/plain'&lt;br /&gt;
	});&lt;br /&gt;
	res.end('Hello World\n');&lt;br /&gt;
}).listen(3456);&lt;br /&gt;
console.log('Server running at http://localhost:3456/');&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Paste the example into a file named `hello.js`, and then run it by calling `node hello.js`.  You should now be able to see your Hello World by visiting your server at port 3456!  (Press ^C to stop the application.)  '''Note:''' If you're running the code from your EC2 instance, you will need to open port 3456.&lt;br /&gt;
&lt;br /&gt;
Let's walk through each line in the above example.&lt;br /&gt;
&lt;br /&gt;
* &amp;lt;code&amp;gt;var http = require('http');&amp;lt;/code&amp;gt; enables us to use Node's built-in HTTP server.  We've been spoiled that languages like PHP automatically load all of the libraries that we need.  However, '''''most functionality in Node.js is NOT loaded by default.'''''  When you want to use any non-fundamental feature of Node, you need to ''require'' it into a variable, as this example does with the HTTP package.  You should be familiar with this concept when you needed to use ArrayList and other specialty packages in Java in CSE 132.&lt;br /&gt;
* &amp;lt;code&amp;gt;http.createServer(function (req, res) { ... }).listen(3456);&amp;lt;/code&amp;gt; uses the HTTP server API to listen for HTTP connections on port 3456.  The anonymous callback function will be called whenever a connection is made.&lt;br /&gt;
* &amp;lt;code&amp;gt;res.writeHead(200, { 'Content-Type': 'text/plain' });&amp;lt;/code&amp;gt; specifies the Content-Type header to be &amp;quot;text/plain&amp;quot;.&lt;br /&gt;
* &amp;lt;code&amp;gt;res.end('Hello World\n');&amp;lt;/code&amp;gt; writes &amp;quot;Hello World&amp;quot; to the response.&lt;br /&gt;
&lt;br /&gt;
Note the use of non-blocking I/O, even in this one little example.  ''Whenever a connection is made, the callback function will be called and passed parameters associated with that connection.''&lt;br /&gt;
&lt;br /&gt;
== A Static File Server Using Node.js ==&lt;br /&gt;
&lt;br /&gt;
Node.js does not automatically serve up static files in the way that an Apache/PHP does.  We need to either use an extension that handles this for us, like Express, or we need to write our own code to make a simple static file server.  The latter option is really not all that difficult, and it gives good insight into how a static file server works.&lt;br /&gt;
&lt;br /&gt;
=== Installing Packages ===&lt;br /&gt;
&lt;br /&gt;
In order for the example code below to work, you need to install the ''mime'' package.  To do this, '''cd to the working directory where you will save your Node.js JavaScript file''' and run:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;$ npm install mime --save&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
''npm'' is the package manager for Node.js.  Unlike all of the package managers we've used up to this point, ''npm'' installs dependencies locally, ''not'' globally.  This means that you can have two different projects using different versions of the same package.  ''npm'' will create a ''node_modules'' directory in the CWD and will install the packages into it.&lt;br /&gt;
&lt;br /&gt;
'''Note:''' When using npm to install local dependencies, '''''do not use sudo'''''.  It will screw up your file permissions.&lt;br /&gt;
&lt;br /&gt;
=== Static Fileserver Code ===&lt;br /&gt;
&lt;br /&gt;
The following code will make an HTTP server on port 3456 that serves up all static files in &amp;lt;STATIC DIRECTORY NAME&amp;gt; relative to app.js.&lt;br /&gt;
&lt;br /&gt;
'''Make an attempt to understand this code.'''  It's important that you are comfortable with the non-blocking nature, as well as how we handle file I/O. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// Require the functionality we need to use:&lt;br /&gt;
var http = require('http'),&lt;br /&gt;
	url = require('url'),&lt;br /&gt;
	path = require('path'),&lt;br /&gt;
	mime = require('mime'),&lt;br /&gt;
	path = require('path'),&lt;br /&gt;
	fs = require('fs');&lt;br /&gt;
&lt;br /&gt;
// Make a simple fileserver for all of our static content.&lt;br /&gt;
// Everything underneath &amp;lt;STATIC DIRECTORY NAME&amp;gt; will be served.&lt;br /&gt;
var app = http.createServer(function(req, resp){&lt;br /&gt;
	var filename = path.join(__dirname, &amp;quot;&amp;lt;STATIC DIRECTORY NAME&amp;gt;&amp;quot;, url.parse(req.url).pathname);&lt;br /&gt;
	(fs.exists || path.exists)(filename, function(exists){&lt;br /&gt;
		if (exists) {&lt;br /&gt;
			fs.readFile(filename, function(err, data){&lt;br /&gt;
				if (err) {&lt;br /&gt;
					// File exists but is not readable (permissions issue?)&lt;br /&gt;
					resp.writeHead(500, {&lt;br /&gt;
						&amp;quot;Content-Type&amp;quot;: &amp;quot;text/plain&amp;quot;&lt;br /&gt;
					});&lt;br /&gt;
					resp.write(&amp;quot;Internal server error: could not read file&amp;quot;);&lt;br /&gt;
					resp.end();&lt;br /&gt;
					return;&lt;br /&gt;
				}&lt;br /&gt;
				&lt;br /&gt;
				// File exists and is readable&lt;br /&gt;
				var mimetype = mime.getType(filename);&lt;br /&gt;
				resp.writeHead(200, {&lt;br /&gt;
					&amp;quot;Content-Type&amp;quot;: mimetype&lt;br /&gt;
				});&lt;br /&gt;
				resp.write(data);&lt;br /&gt;
				resp.end();&lt;br /&gt;
				return;&lt;br /&gt;
			});&lt;br /&gt;
		}else{&lt;br /&gt;
			// File does not exist&lt;br /&gt;
			resp.writeHead(404, {&lt;br /&gt;
				&amp;quot;Content-Type&amp;quot;: &amp;quot;text/plain&amp;quot;&lt;br /&gt;
			});&lt;br /&gt;
			resp.write(&amp;quot;Requested file not found: &amp;quot;+filename);&lt;br /&gt;
			resp.end();&lt;br /&gt;
			return;&lt;br /&gt;
		}&lt;br /&gt;
	});&lt;br /&gt;
});&lt;br /&gt;
app.listen(3456);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Port 3456 ===&lt;br /&gt;
&lt;br /&gt;
We are running our server on port 3456 as opposed to the default web server port, which of course is 80.  We therefore need to open our Node.js application like this:&lt;br /&gt;
&lt;br /&gt;
http://ec2-xx-xx-xx-xx.compute-1.amazonaws.com:3456/path.extension&lt;br /&gt;
&lt;br /&gt;
However, this won't work on the first time.  ''Why?'' (Try to figure this out on your own before reading the next paragraph.)&lt;br /&gt;
&lt;br /&gt;
We need to open port 3456 on our Amazon EC2 instance.  Remember when you opened port 80 way back in Module 2?  We need to do the same sort of procedure again now.&lt;br /&gt;
&lt;br /&gt;
# Log into your EC2 management console&lt;br /&gt;
# Go to &amp;quot;Security Groups&amp;quot;&lt;br /&gt;
# Select your security group from Module 2&lt;br /&gt;
# Under &amp;quot;Inbound&amp;quot;, create a custom TCP rule for port 3456, and apply your changes.&lt;br /&gt;
&lt;br /&gt;
== Node.js Security ==&lt;br /&gt;
&lt;br /&gt;
Just because we're writing in JavaScript doesn't mean that we can forget about the security practices you've been learning in the last three months of CSE 330.  XSS is still a problem, as is the use of ''eval'', CSRF attacks, and so on.&lt;br /&gt;
&lt;br /&gt;
The two links below have good information about security vulnerabilities specific to Node.js that you should think about when crafting your application.&lt;br /&gt;
&lt;br /&gt;
# Book from PragProg ($24, 2015): https://pragprog.com/book/kdnodesec/secure-your-node-js-web-application&lt;br /&gt;
# Slideshow from a Switzerland Conference on Application Security (2012): http://www.slideshare.net/ASF-WS/asfws-2012-nodejs-security-old-vulnerabilities-in-new-dresses-par-sven-vetsch&lt;br /&gt;
&lt;br /&gt;
== Node.js Conventions ==&lt;br /&gt;
&lt;br /&gt;
There ought to be a standard way to save metadata about your app, right?  Well, ''npm'' introduces a straightforward way to do this in the form of a ''package.json'' file.&lt;br /&gt;
&lt;br /&gt;
To make your ''npm'' file with a step-by-step prompt, run in your project root directory:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ npm init&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
One nifty feature of ''package.json'' is the way it automatically handles dependencies.  For example, you can put the following lines in your ''package.json'':&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
  &amp;quot;dependencies&amp;quot;: {&lt;br /&gt;
    &amp;quot;mime&amp;quot;: &amp;quot;~1.6.0&amp;quot;,&lt;br /&gt;
    &amp;quot;socket.io&amp;quot;: &amp;quot;~0.9.16&amp;quot;&lt;br /&gt;
  },&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Then, back on the command line, when you run&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ npm install&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
it automatically installs the dependencies for you!  No more headaches of trying to figure out which modules you need to install; all that information is saved for you in your code base.&lt;br /&gt;
&lt;br /&gt;
'''Tip:''' Once you set up your ''package.json'' file, you can automatically add a dependency to it by using the ''--save'' argument on ''npm install'': &amp;lt;code&amp;gt;npm install --save socket.io&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 7]]&lt;/div&gt;</summary>
		<author><name>Connor</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Python&amp;diff=2713</id>
		<title>Python</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Python&amp;diff=2713"/>
		<updated>2020-02-26T04:04:52Z</updated>

		<summary type="html">&lt;p&gt;Connor: /* A Few Gotchas */&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&amp;gt;. You can also use three sets of quotes (single or double again) 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>Connor</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Python&amp;diff=2712</id>
		<title>Python</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Python&amp;diff=2712"/>
		<updated>2020-02-26T04:03:31Z</updated>

		<summary type="html">&lt;p&gt;Connor: /* A Few Gotchas */&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&amp;gt;. 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>Connor</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Python&amp;diff=2711</id>
		<title>Python</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Python&amp;diff=2711"/>
		<updated>2020-02-26T04:03:11Z</updated>

		<summary type="html">&lt;p&gt;Connor: /* A Few Gotchas */&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&amp;gt;. 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>Connor</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Python&amp;diff=2710</id>
		<title>Python</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Python&amp;diff=2710"/>
		<updated>2020-02-26T04:02:21Z</updated>

		<summary type="html">&lt;p&gt;Connor: /* A Few Gotchas */&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&amp;gt;. 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>Connor</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Python&amp;diff=2709</id>
		<title>Python</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Python&amp;diff=2709"/>
		<updated>2020-02-26T04:01:19Z</updated>

		<summary type="html">&lt;p&gt;Connor: /* A Few Gotchas */&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&amp;gt;. 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>Connor</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Python&amp;diff=2708</id>
		<title>Python</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Python&amp;diff=2708"/>
		<updated>2020-02-26T04:00:51Z</updated>

		<summary type="html">&lt;p&gt;Connor: /* A Few Gotchas */&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&amp;gt;. 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>Connor</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Python&amp;diff=2707</id>
		<title>Python</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Python&amp;diff=2707"/>
		<updated>2020-02-26T04:00:31Z</updated>

		<summary type="html">&lt;p&gt;Connor: /* A Few Gotchas */&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&amp;gt;. 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>Connor</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Introduction_to_MySQL&amp;diff=2706</id>
		<title>Introduction to MySQL</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Introduction_to_MySQL&amp;diff=2706"/>
		<updated>2020-02-04T04:32:10Z</updated>

		<summary type="html">&lt;p&gt;Connor: /* Installing phpMyAdmin */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This article is an introduction to MySQL, a database used in conjunction with web applications.&lt;br /&gt;
&lt;br /&gt;
== Why Use a Database? ==&lt;br /&gt;
&lt;br /&gt;
In Module 2, you made a web site that used flatfiles to keep track of usernames and uploaded file associations.  However, flatfiles are insecure, lack complex logic, and are impractical for a large-scale web application.  This is where databases come in.  Databases are designed from the ground up to be fast, efficient, and powerful storage solutions for any amount of data.&lt;br /&gt;
&lt;br /&gt;
In CSE330, we will be using '''MySQL''', which is a popular, open-source ''relational database management system'' for web applications.&lt;br /&gt;
&lt;br /&gt;
== Database Structure ==&lt;br /&gt;
&lt;br /&gt;
A MySQL server consists of ''databases'', each of which contains ''tables''.  Tables, in turn, consist of one or more ''fields'' (like columns), and the data is stored in one or more ''entries'' (like rows).  A field in a table can be designated as an ''index''; that is, something that can be used to look up the information in the database.  The set of tables, fields, and indices in your database is called your ''schema''.&lt;br /&gt;
&lt;br /&gt;
MySQL uses the '''Structured Query Language (SQL)''' for manipulating data.&lt;br /&gt;
&lt;br /&gt;
=== Storage Engines ===&lt;br /&gt;
&lt;br /&gt;
MySQL is a database server, but under the hood, it actually uses a '''storage engine''' to retrieve the data.  Two storage engines that are popular in the MySQL community are '''InnoDB''' and '''MyISAM'''.  MyISAM is slightly faster than InnoDB, and it specializes in database schemas that involve predominantly ''SELECT'' and ''INSERT'' queries (which you will learn about later).  However, MyISAM lacks InnoDB's power in making relations between tables, and MyISAM also does not support InnoDB's database transactions.  [http://www.akadia.com/services/mysql_survival.html Click here for more information regarding the differences between MyISAM and InnoDB.]&lt;br /&gt;
&lt;br /&gt;
In CSE330, we will be using InnoDB for our primary MySQL storage engine because of its support for foreign key constraints.  However, in your personal applications down the road, feel free to use either InnoDB or MyISAM.&lt;br /&gt;
&lt;br /&gt;
== Installing and Configuring MySQL ==&lt;br /&gt;
&lt;br /&gt;
To use MySQL, you need the MySQL Server package.  Because we will be interacting with MySQL primarily from PHP scripts, we will also need the associated PHP libraries. In '''yum (RHEL)''', you need the packages '''mysql56-server''' and '''php70-mysqlnd''' and '''php70-mcrypt''' and '''php70-mbstring'''&lt;br /&gt;
&lt;br /&gt;
If you need a refresher on how to install software packages in Linux, re-read [[Linux#Repository-Based Package Managers|the Linux guide]].&lt;br /&gt;
&lt;br /&gt;
Remember to restart Apache after installing any packages relating to your web server!&lt;br /&gt;
&lt;br /&gt;
Run these commands to start the server and the client automatically on startup:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ sudo /sbin/chkconfig --add mysqld&lt;br /&gt;
$ sudo /sbin/chkconfig mysqld on&lt;br /&gt;
$ sudo /sbin/service mysqld start&lt;br /&gt;
$ &lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Run the following command to set the MySQL root user password:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ mysqladmin -u root password&lt;br /&gt;
New password: &lt;br /&gt;
Confirm new password: &lt;br /&gt;
$ &lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
When it asks, type the new password, press Enter, and then type the new password again.  You cannot see what you are typing because a password is supposed to be secret.  If the shell displayed the password to you while you were typing it, it would be forever saved in ''~/.bash_history''!&lt;br /&gt;
&lt;br /&gt;
== Using MySQL from the Command Line ==&lt;br /&gt;
&lt;br /&gt;
To interface with MySQL from the command line, use the &amp;lt;code&amp;gt;mysql&amp;lt;/code&amp;gt; command.  The syntax is:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ mysql -u USERNAME -p DATABASENAME&lt;br /&gt;
Welcome to the MySQL monitor. ...&lt;br /&gt;
&lt;br /&gt;
mysql&amp;gt; &lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You will be prompted for the password associated with USERNAME.&lt;br /&gt;
&lt;br /&gt;
== Managing Databases ==&lt;br /&gt;
&lt;br /&gt;
To create a database on your MySQL server, simply run the query:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;mysql&amp;quot;&amp;gt;&lt;br /&gt;
create database DATABASENAME;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You can delete a database using the query:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;mysql&amp;quot;&amp;gt;&lt;br /&gt;
drop database DATABASENAME;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
When you're at the MySQL prompt, use the following query to select a database to which to run select, insert, update, and delete queries:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;mysql&amp;quot;&amp;gt;&lt;br /&gt;
use DATABASENAME;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== MySQL User Management ==&lt;br /&gt;
&lt;br /&gt;
The first time you log into MySQL, you will need to use the root user, with the password that you specified earlier.  However, it is unwise to use the root user for everyday operations with your MySQL database.&lt;br /&gt;
&lt;br /&gt;
=== Creating a New User ===&lt;br /&gt;
&lt;br /&gt;
To create a new user named USERNAME with the password PASSWORD, run the following query inside MySQL:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;mysql&amp;quot;&amp;gt;&lt;br /&gt;
create user 'USERNAME'@'localhost' identified by 'PASSWORD';&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This will create USERNAME, but that user will not have privileges to access any databases.&lt;br /&gt;
&lt;br /&gt;
=== Granting Privileges ===&lt;br /&gt;
&lt;br /&gt;
MySQL provides the '''grant''' command to grant privileges to a user.  The syntax for assigning USERNAME some PRIVILEGES on a TABLE in a DATABASE is:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;mysql&amp;quot;&amp;gt;&lt;br /&gt;
grant PRIVILEGES on DATABASE.TABLE to USERNAME@'localhost';&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If you want to grant global privileges to a certain administrative user, run the query like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;mysql&amp;quot;&amp;gt;&lt;br /&gt;
grant all on *.* to USERNAME@'localhost' with grant option;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The ''with grant option'' enables this user to create other users and assign them permissions, like we are doing here.&lt;br /&gt;
&lt;br /&gt;
If you want to grant privileges to a certain user so that they can only manipulate data in a certain database (a wise idea for when you create a user to use in your PHP web application), run the query like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;mysql&amp;quot;&amp;gt;&lt;br /&gt;
grant select,insert,update,delete on DATABASE.* to USERNAME@'localhost';&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Whenever you change privileges, you also need to run the query &amp;lt;code&amp;gt;flush privileges;&amp;lt;/code&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;mysql&amp;quot;&amp;gt;&lt;br /&gt;
flush privileges;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== phpMyAdmin ==&lt;br /&gt;
&lt;br /&gt;
It is often cumbersome to SSH into your server every time you want to interact with your database.  A popular web-based window into your MySQL server is '''phpMyAdmin'''.&lt;br /&gt;
&lt;br /&gt;
=== Installing phpMyAdmin ===&lt;br /&gt;
&lt;br /&gt;
To add phpMyAdmin to apache's root server, you need to make your user apart of the apache group, and change the owner of the root directory to apache.&lt;br /&gt;
&lt;br /&gt;
To add your user to the apache group:&lt;br /&gt;
 $ sudo usermod -a -G apache YOUR_USERNAME&lt;br /&gt;
'''Note you may have to exit your server and ssh back in for this to take effect'''&lt;br /&gt;
&lt;br /&gt;
Change the owner of the www folders to your user, and the group apache&lt;br /&gt;
 $ sudo chown -R YOUR_USERNAME:apache /var/www&lt;br /&gt;
&lt;br /&gt;
'''Now that you can access the /var/www/html directory''' download phpMyAdmin to apache's root directory using '''wget''', and then extract it using '''tar -xzvf''':&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ cd /var/www/html&lt;br /&gt;
$ wget 'https://files.phpmyadmin.net/phpMyAdmin/4.9.4/phpMyAdmin-4.9.4-all-languages.tar.gz'&lt;br /&gt;
&lt;br /&gt;
$ ls&lt;br /&gt;
phpMyAdmin-4.9.4-all-languages.tar.gz&lt;br /&gt;
&lt;br /&gt;
$ mkdir phpmyadmin &amp;amp;&amp;amp; tar -xvzf phpMyAdmin-4.9.4-all-languages.tar.gz -C phpmyadmin --strip-components 1&lt;br /&gt;
&lt;br /&gt;
$ ls&lt;br /&gt;
phpmyadmin  phpMyAdmin-4.9.4-all-languages.tar.gz&lt;br /&gt;
&lt;br /&gt;
$ rm phpMyAdmin-4.9.4-all-languages.tar.gz&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Now, create a phpMyAdmin configuration file, which needs to be saved as '''config.inc.php'''.  The easiest way to do this is to copy the '''config.sample.inc.php''' file that is included with your download.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ cd /var/www/html/phpmyadmin&lt;br /&gt;
$ sudo cp config.sample.inc.php config.inc.php&lt;br /&gt;
$ &lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Now, open config.inc.php in your favorite text editor (if you forgot how, refer to [[Linux#File Editors|the Linux guide]]), and edit the following line, putting in something random for &amp;quot;mySecretHere&amp;quot;:&lt;br /&gt;
&lt;br /&gt;
 $cfg['blowfish_secret'] = 'mySecretHere';&lt;br /&gt;
&lt;br /&gt;
Finally, restart Apache, and you're good to go.  phpMyAdmin will be accessible via http://ec2-blah-blah.compute-1.amazonaws.com/phpmyadmin/&lt;br /&gt;
&lt;br /&gt;
===== Troubleshooting =====&lt;br /&gt;
&lt;br /&gt;
Older versions of the phpmyadmin package in apt required that you perform one additional step: let Apache know that phpMyAdmin was installed.  The new version does this automatically so long as you check the &amp;quot;apache&amp;quot; box in the first step of the instalation process.&lt;br /&gt;
&lt;br /&gt;
To manually hook up phpMyAdmin with Apache, run the following command to symlink ''phpmyadmin.conf'' into Apache's ''conf.d'' directory:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ sudo ln -s /etc/phpmyadmin/apache.conf /etc/apache2/conf.d/phpmyadmin.conf&lt;br /&gt;
$ sudo apache2ctl restart  # restart Apache&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Using phpMyAdmin ===&lt;br /&gt;
&lt;br /&gt;
Once phpMyAdmin is installed, you will see a login screen.  Log in using a non-root username and password you set up in the previous section.  Once inside, you will see a GUI for interacting with your MySQL database.&lt;br /&gt;
&lt;br /&gt;
Even with the GUI, it is often easier to run queries manually, especially when doing operations like creating a table.  To run a query manually, click either the &amp;quot;SQL&amp;quot; tab or the little icon in the toolbar on the upper-left-hand side of the screen that looks like a database cluster (it's third from the left).&lt;br /&gt;
&lt;br /&gt;
== MySQL Schema and State ==&lt;br /&gt;
&lt;br /&gt;
Read the [[MySQL Schema and State]] guide for more information.&lt;br /&gt;
&lt;br /&gt;
== Using MySQL in PHP ==&lt;br /&gt;
&lt;br /&gt;
Read the [[PHP and MySQL]] guide for more information.&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 3]]&lt;/div&gt;</summary>
		<author><name>Connor</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Amazon_Web_Services&amp;diff=2705</id>
		<title>Amazon Web Services</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Amazon_Web_Services&amp;diff=2705"/>
		<updated>2020-01-29T22:25:29Z</updated>

		<summary type="html">&lt;p&gt;Connor: /* Creating and Configuring your EC2 Instance */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Amazon Web Services provides a method to publish web sites on virtual machines in the &amp;quot;cloud.&amp;quot;  In CSE330, you will be using an EC2 instance to host your web site.&lt;br /&gt;
&lt;br /&gt;
Before reading this guide, you should be familiar with Linux and the various distributions of Linux.  Fore more information, refer to [[Linux#Linux Distributions|the Linux guide]].&lt;br /&gt;
&lt;br /&gt;
== Creating and Configuring your EC2 Instance ==&lt;br /&gt;
&lt;br /&gt;
{{RequiredInstructions|content=&lt;br /&gt;
&lt;br /&gt;
Follow these steps to get to the AWS Management Console:&lt;br /&gt;
&lt;br /&gt;
# Create an AWS account: http://aws.amazon.com/&lt;br /&gt;
# Sign up for the EC2 Web Service: http://aws.amazon.com/ec2/&lt;br /&gt;
# Log in to the AWS Management Console&lt;br /&gt;
&lt;br /&gt;
To create your new virtual machine, click '''Launch Instance'''.  Do the following to configure your instance:&lt;br /&gt;
&lt;br /&gt;
# Use the Classic Wizard.&lt;br /&gt;
# Please... Just please choose distribution of Linux labeled &amp;quot;Amazon Linux AMI&amp;quot;. Make sure to double check before selecting, as is the second option and selecting another distribution will cause problems later. For more information on distributions, refer to [[Linux#Linux Distributions|the Linux guide]].&lt;br /&gt;
[[File:Correct_instance_type.png|600px|center]]&lt;br /&gt;
# The default instance variables are all fine.  Click Continue until you get to the &amp;quot;Create Key Pair&amp;quot; screen.&lt;br /&gt;
# Create a new Key Pair.  Enter some name for it, and then click &amp;quot;Create &amp;amp; Download your Key Pair&amp;quot;.  '''Save your key somewhere secure.'''  In addition to using it to authenticate for this instance, you will be able to use the same key for additional instances.&lt;br /&gt;
# Create a new Security Group and connect it to your server.  The security groups you create determine whether a port is open or blocked for your server.&lt;br /&gt;
#* You need to open the SSH port on your server.  To do this, select &amp;quot;SSH&amp;quot; from the drop-down box, and then click &amp;quot;Add Rule.&amp;quot;&lt;br /&gt;
#: We will be opening more ports by modifying the security group at a later time.  Click Continue.&lt;br /&gt;
# You are now ready to launch your virtual server!  Click Launch.&lt;br /&gt;
&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
== Starting and Stopping your EC2 Instance ==&lt;br /&gt;
&lt;br /&gt;
You can start and stop your instance by right-clicking on the instance.  The options are down in the &amp;quot;Instance Lifecycle&amp;quot; section.&lt;br /&gt;
&lt;br /&gt;
=== Amazon EC2 Gives You One Free Micro Instance ===&lt;br /&gt;
&lt;br /&gt;
It is free to keep '''''one''''' micro instance running at all times.  Keeping your instance running around the clock will make your life easier, because then you won't need to always change your hostname in your SSH clients.&lt;br /&gt;
&lt;br /&gt;
For additional Micro instances, or for larger instances, you will be charged hourly for their use.  One non-free Micro instance costs about $14/month; a Small instance costs about $43/month.&lt;br /&gt;
&lt;br /&gt;
=== Terminate vs Stop ===&lt;br /&gt;
&lt;br /&gt;
Never &amp;quot;terminate&amp;quot; your instance, as this PERMANENTLY DELETES the instance! Any time you are done using the instance you should instead &amp;quot;stop&amp;quot; the instance and then when you are ready to resume work you should &amp;quot;start&amp;quot; the instance.&lt;br /&gt;
&lt;br /&gt;
'''Note:''' Frequently committing your work to your repository is a safety net in case something horrible happens to your instance.&lt;br /&gt;
&lt;br /&gt;
== Enabling Web Access to your EC2 Instance ==&lt;br /&gt;
&lt;br /&gt;
{{RequiredInstructions|content=&lt;br /&gt;
&lt;br /&gt;
Once you have configured [[Apache]] (which you will do later in this Module), you will need to open up your EC2 instance to web traffic.  (By default amazon blocks all traffic to our instance.)&lt;br /&gt;
&lt;br /&gt;
Go to the Security Groups under Network &amp;amp; Security on the EC2 webpage. Select your security group, click on the Inbound Tab. Add a new Custom TCP rule with a Port range of 80.  Leave the Source at 0.0.0.0/0 (for all traffic). Click Add Rule, and then click Apply Rule Change.&lt;br /&gt;
&lt;br /&gt;
To make sure things are working, create a file, like '''hello.txt''', in your web server root.  Give it some content (might I suggest &amp;quot;Hello, world!&amp;quot;). The web server root is at /var/www/html&lt;br /&gt;
&lt;br /&gt;
For more information on editing files on the command line, refer to [[Linux#File Editors|the Linux guide]].&lt;br /&gt;
&lt;br /&gt;
You should now be able to visit your server load up the file using your web browser!  Example Link: http://ec2-xxx-xxx-xxx-xx.compute-1.amazonaws.com/hello.txt&lt;br /&gt;
&lt;br /&gt;
NOTE:depending on the city in which your server is located, your link might look like:&lt;br /&gt;
&lt;br /&gt;
http://ec2-xxx-xxx-xxx-xxx.us-west-2.compute.amazonaws.com/hello.txt&lt;br /&gt;
&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 2]]&lt;/div&gt;</summary>
		<author><name>Connor</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=File:Correct_instance_type.png&amp;diff=2704</id>
		<title>File:Correct instance type.png</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=File:Correct_instance_type.png&amp;diff=2704"/>
		<updated>2020-01-29T22:24:42Z</updated>

		<summary type="html">&lt;p&gt;Connor: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;/div&gt;</summary>
		<author><name>Connor</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=VS_Code&amp;diff=2703</id>
		<title>VS Code</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=VS_Code&amp;diff=2703"/>
		<updated>2020-01-29T19:04:05Z</updated>

		<summary type="html">&lt;p&gt;Connor: /* Testing Everything Locally */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Getting Started With Each Module ==&lt;br /&gt;
&lt;br /&gt;
* Create Github repo using the CSE 330 repo creator  (Check Piazza for the link)&lt;br /&gt;
* Navigate to the created repo in Github&lt;br /&gt;
* Clone the repo via https to a dedicated folder on your computer&lt;br /&gt;
&lt;br /&gt;
[[File:File-Structure.png|400px|center]]&lt;br /&gt;
&lt;br /&gt;
* In VS Code, File &amp;gt; Open the Spring2019-module1-individual-STUDENTID '''folder''' that you cloned to your computer&lt;br /&gt;
&lt;br /&gt;
If you followed the above steps correctly, the folder's Git should be configured to your Github repository!  I highly recommend creating your Github repo, cloning the folder to a designated spot, and keeping all modules separated for the semester as shown in the image above.&lt;br /&gt;
&lt;br /&gt;
== Module 1 -- Using the Git Integration ==&lt;br /&gt;
'''Note: If you're using Windows, you may need to install Git on your machine first. https://git-scm.com/download/win . You can check if you have Git running by typing git --version in your terminal'''&lt;br /&gt;
&lt;br /&gt;
* First, open the File Explorer tab on the left, and right click to create a new file, birthday.html&lt;br /&gt;
[[File:New-file.png|400px|center]]&lt;br /&gt;
* Ensure VS Code has it marked as an html file (see the file type next to the smiley face)&lt;br /&gt;
* Type '''doc''' followed by enter, and allow VS Code to generate a basic HTML file for you (use VS Code to your advantage! It can do a lot of your coding for you).&lt;br /&gt;
* Save the file, you should see a popup next to the Version Control symbol on the left. VS Code has detected that your project is different than what it is in your remote Github repo.&lt;br /&gt;
* To commit, simply type a message in the box and click the check mark above it.  To push to your Github repo, click the 3 dots next to the check mark and select 'push'&lt;br /&gt;
* Note this is also where you can pull from your remote.&lt;br /&gt;
&lt;br /&gt;
==== Bonus - Module 1 ====&lt;br /&gt;
* If you like your text editor to look pretty, you can go to the Extensions tab and search for different themes. (Check out the Material theme!)&lt;br /&gt;
* You can view your settings by clicking CMD + , (Mac) or Ctrl + , (Windows).  Search for Theme and choose one that works for you!&lt;br /&gt;
&lt;br /&gt;
== Module 2 == &lt;br /&gt;
=== SFTP Integration (Shipping files to your server) ===&lt;br /&gt;
# Open the Extensions tab and search for 'sftp'. Download the first one.&lt;br /&gt;
# To use commands in VS Code, type '''Cmd + Shift + P''' (Mac), or '''Ctrl + Shift + P''' on windows. &lt;br /&gt;
#Type SFTP and open the sftp config command. &lt;br /&gt;
&lt;br /&gt;
Your config.json file should look like the following:&lt;br /&gt;
  {&lt;br /&gt;
    &amp;quot;protocol&amp;quot;: &amp;quot;sftp&amp;quot;,&lt;br /&gt;
    &amp;quot;host&amp;quot;: &amp;quot;YOUR.EC2.DNS&amp;quot;,&lt;br /&gt;
    &amp;quot;port&amp;quot;: 22,&lt;br /&gt;
    &amp;quot;username&amp;quot;: &amp;quot;YOUR USERNAME&amp;quot;,&lt;br /&gt;
    &amp;quot;privateKeyPath&amp;quot;: &amp;quot;/path/to/your/id_rsa&amp;quot;,&lt;br /&gt;
    &amp;quot;remotePath&amp;quot;: &amp;quot;/home/YOUR USERNAME/public_html/module2&amp;quot;,&lt;br /&gt;
    &amp;quot;uploadOnSave&amp;quot;: true&lt;br /&gt;
  }&lt;br /&gt;
- Note the uploadOnSave field is optional, but can be nice!&lt;br /&gt;
- Check the VS Code output for errors in your config.&lt;br /&gt;
&lt;br /&gt;
Additionally: You should notice an SFTP tab on the side of VS Code. Here, you can view the file structure on your server.&lt;br /&gt;
&lt;br /&gt;
=== Testing Everything Locally ===&lt;br /&gt;
If you get the SFTP integration working well, you don't need to set up a local php server.  If you can't get the above working, however, we highly recommend coding all of your projects locally, and only uploading them to your ec2 instance when complete.&lt;br /&gt;
&lt;br /&gt;
'''To run PHP locally'''&lt;br /&gt;
&lt;br /&gt;
'''Windows'''&lt;br /&gt;
# Download WAMP http://www.wampserver.com/en/download-wampserver-64bits/&lt;br /&gt;
# Place your project repositories in Wamp's www/ directory, and navigate to http://localhost in your browser.  You should see your projects listed here, run php files, and use phpmyadmin.&lt;br /&gt;
&lt;br /&gt;
'''Mac'''&lt;br /&gt;
# Download Homebrew. Homebrew is a great package manager for OSx and we will be using it in future modules. &lt;br /&gt;
# Type the following in your terminal and follow instructions&lt;br /&gt;
 /usr/bin/ruby -e &amp;quot;$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)&amp;quot;&lt;br /&gt;
# In your terminal, type '''php -v'''. If your version is less than 7, update with brew. '''brew install php'''&lt;br /&gt;
# In VS Code, search for the extension '''Php Server'''. After installing, use VS Code's command pallette with CMD+Shift+P , search for PHP, and select start server.  You should be able to view your project in your localhost&lt;/div&gt;</summary>
		<author><name>Connor</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Node.JS&amp;diff=2697</id>
		<title>Node.JS</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Node.JS&amp;diff=2697"/>
		<updated>2019-12-31T19:41:50Z</updated>

		<summary type="html">&lt;p&gt;Connor: /* Your First Node.js Application: Hello World */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;AJAX is a useful technology for web applications that need to pull periodic updates from your server.  But what do you do when you have thousands of clients all requesting data that changes real-time?  A PHP+AJAX approach could choke without a lot of effort on your part.  It is situations like these that Node.js comes to the rescue. Node.js is a web framework, made in JavaScript, that's become extremely popular over the last few years.&lt;br /&gt;
&lt;br /&gt;
In general, JavaScript frameworks are very trendy right now; it can be hard to keep up with the new cool thing. In fact, there's a joke website https://dayssincelastjavascriptframework.com/, that &amp;quot;tracks&amp;quot; how long it's been since a new framework has come out.&lt;br /&gt;
&lt;br /&gt;
== Non-Blocking I/O ==&lt;br /&gt;
&lt;br /&gt;
You dabbled in the concept of non-blocking I/O when you implemented AJAX in the previous JavaScript module.  Node.js uses this execution model at its core.&lt;br /&gt;
&lt;br /&gt;
The core idea is the use of '''''anonymous functions''''' as ''callbacks'' for processing the results of intensive operations.  Consider the pseudo-code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// Blocking I/O Pseudo-Code&lt;br /&gt;
&lt;br /&gt;
var data = database.query(&amp;quot;select * from news&amp;quot;);&lt;br /&gt;
print data[0].title;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above pseudo-code queries a database, saves the result of the query in a variable named ''data'', and then prints out the first title in ''data''.  The problem arises when multiple clients all want to access the server at the same time.  ''In a blocking I/O model, a client needs to wait until all other clients are finished before it can start its process.''  With intensive operations and thousands of clients, this can easily crash your server!&lt;br /&gt;
&lt;br /&gt;
The solution is to use ''non-blocking I/O''.  Consider this revised pseudo-code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// Non-Blocking I/O Pseudo-Code&lt;br /&gt;
&lt;br /&gt;
database.query(&amp;quot;select * from news&amp;quot;, function(data){&lt;br /&gt;
	print data[0].title;&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The revised pseudo-code achieves the same end result as the first version.  However, ''it allows other clients to perform tasks while this process is waiting for the database to be queried!''  The code occurs in two parts: first, we start the query.  Second, ''when the query is complete'', our '''anonymous callback function''' is executed.  In Node.js, callback functions are usually passed one or more parameters.&lt;br /&gt;
&lt;br /&gt;
Better yet, with non-blocking I/O, you have no concurrency issues, because everything runs in just one thread.  Nifty!&lt;br /&gt;
&lt;br /&gt;
== Installing Node.js ==&lt;br /&gt;
&lt;br /&gt;
Run the following commands to install Node and NPM:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ curl --silent --location https://rpm.nodesource.com/setup_12.x | sudo bash -&lt;br /&gt;
$ sudo yum install -y nodejs&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;!-- The unofficial instructions for installing Node.js can be found here: https://gist.github.com/isaacs/579814&lt;br /&gt;
&lt;br /&gt;
There are several choices, but my favorite is probably ''use-nave-no-shell.sh''.&lt;br /&gt;
&lt;br /&gt;
The instructions at the above link have a couple bugs.  If you run this sequence of commands, Node and NPM will install correctly:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ mkdir ~/.nave&lt;br /&gt;
$ cd ~/.nave&lt;br /&gt;
$ wget http://github.com/isaacs/nave/raw/master/nave.sh&lt;br /&gt;
$ sudo ln -s $PWD/nave.sh /usr/local/bin/nave&lt;br /&gt;
$ chmod a+x nave.sh&lt;br /&gt;
$ sudo chown -R $USER:$USER /usr/local&lt;br /&gt;
$ nave usemain stable&lt;br /&gt;
$ curl -L https://www.npmjs.org/install.sh | sh&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Your First Node.js Application: Hello World ==&lt;br /&gt;
&lt;br /&gt;
Let's try running the example application given on the front page of nodejs.org:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
const http = require('http');&lt;br /&gt;
http.createServer(function (req, res) {&lt;br /&gt;
	res.writeHead(200, {&lt;br /&gt;
		'Content-Type': 'text/plain'&lt;br /&gt;
	});&lt;br /&gt;
	res.end('Hello World\n');&lt;br /&gt;
}).listen(3456);&lt;br /&gt;
console.log('Server running at http://localhost:3456/');&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Paste the example into a file named `hello.js`, and then run it by calling `node hello.js`.  You should now be able to see your Hello World by visiting your server at port 3456!  (Press ^C to stop the application.)  '''Note:''' If you're running the code from your EC2 instance, you will need to open port 3456.&lt;br /&gt;
&lt;br /&gt;
Let's walk through each line in the above example.&lt;br /&gt;
&lt;br /&gt;
* &amp;lt;code&amp;gt;var http = require('http');&amp;lt;/code&amp;gt; enables us to use Node's built-in HTTP server.  We've been spoiled that languages like PHP automatically load all of the libraries that we need.  However, '''''most functionality in Node.js is NOT loaded by default.'''''  When you want to use any non-fundamental feature of Node, you need to ''require'' it into a variable, as this example does with the HTTP package.  You should be familiar with this concept when you needed to use ArrayList and other specialty packages in Java in CSE 132.&lt;br /&gt;
* &amp;lt;code&amp;gt;http.createServer(function (req, res) { ... }).listen(3456);&amp;lt;/code&amp;gt; uses the HTTP server API to listen for HTTP connections on port 3456.  The anonymous callback function will be called whenever a connection is made.&lt;br /&gt;
* &amp;lt;code&amp;gt;res.writeHead(200, { 'Content-Type': 'text/plain' });&amp;lt;/code&amp;gt; specifies the Content-Type header to be &amp;quot;text/plain&amp;quot;.&lt;br /&gt;
* &amp;lt;code&amp;gt;res.end('Hello World\n');&amp;lt;/code&amp;gt; writes &amp;quot;Hello World&amp;quot; to the response.&lt;br /&gt;
&lt;br /&gt;
Note the use of non-blocking I/O, even in this one little example.  ''Whenever a connection is made, the callback function will be called and passed parameters associated with that connection.''&lt;br /&gt;
&lt;br /&gt;
== A Static File Server Using Node.js ==&lt;br /&gt;
&lt;br /&gt;
Node.js does not automatically serve up static files in the way that an Apache/PHP does.  We need to either use an extension that handles this for us, like Express, or we need to write our own code to make a simple static file server.  The latter option is really not all that difficult, and it gives good insight into how a static file server works.&lt;br /&gt;
&lt;br /&gt;
=== Installing Packages ===&lt;br /&gt;
&lt;br /&gt;
In order for the example code below to work, you need to install the ''mime'' package.  To do this, '''cd to the working directory where you will save your Node.js JavaScript file''' and run:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;$ npm install mime&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
''npm'' is the package manager for Node.js.  Unlike all of the package managers we've used up to this point, ''npm'' installs dependencies locally, ''not'' globally.  This means that you can have two different projects using different versions of the same package.  ''npm'' will create a ''node_modules'' directory in the CWD and will install the packages into it.&lt;br /&gt;
&lt;br /&gt;
'''Note:''' When using npm to install local dependencies, '''''do not use sudo'''''.  It will screw up your file permissions.&lt;br /&gt;
&lt;br /&gt;
=== Static Fileserver Code ===&lt;br /&gt;
&lt;br /&gt;
The following code will make an HTTP server on port 3456 that serves up all static files in &amp;lt;STATIC DIRECTORY NAME&amp;gt; relative to app.js.&lt;br /&gt;
&lt;br /&gt;
'''Make an attempt to understand this code.'''  It's important that you are comfortable with the non-blocking nature, as well as how we handle file I/O. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// Require the functionality we need to use:&lt;br /&gt;
var http = require('http'),&lt;br /&gt;
	url = require('url'),&lt;br /&gt;
	path = require('path'),&lt;br /&gt;
	mime = require('mime'),&lt;br /&gt;
	path = require('path'),&lt;br /&gt;
	fs = require('fs');&lt;br /&gt;
&lt;br /&gt;
// Make a simple fileserver for all of our static content.&lt;br /&gt;
// Everything underneath &amp;lt;STATIC DIRECTORY NAME&amp;gt; will be served.&lt;br /&gt;
var app = http.createServer(function(req, resp){&lt;br /&gt;
	var filename = path.join(__dirname, &amp;quot;&amp;lt;STATIC DIRECTORY NAME&amp;gt;&amp;quot;, url.parse(req.url).pathname);&lt;br /&gt;
	(fs.exists || path.exists)(filename, function(exists){&lt;br /&gt;
		if (exists) {&lt;br /&gt;
			fs.readFile(filename, function(err, data){&lt;br /&gt;
				if (err) {&lt;br /&gt;
					// File exists but is not readable (permissions issue?)&lt;br /&gt;
					resp.writeHead(500, {&lt;br /&gt;
						&amp;quot;Content-Type&amp;quot;: &amp;quot;text/plain&amp;quot;&lt;br /&gt;
					});&lt;br /&gt;
					resp.write(&amp;quot;Internal server error: could not read file&amp;quot;);&lt;br /&gt;
					resp.end();&lt;br /&gt;
					return;&lt;br /&gt;
				}&lt;br /&gt;
				&lt;br /&gt;
				// File exists and is readable&lt;br /&gt;
				var mimetype = mime.getType(filename);&lt;br /&gt;
				resp.writeHead(200, {&lt;br /&gt;
					&amp;quot;Content-Type&amp;quot;: mimetype&lt;br /&gt;
				});&lt;br /&gt;
				resp.write(data);&lt;br /&gt;
				resp.end();&lt;br /&gt;
				return;&lt;br /&gt;
			});&lt;br /&gt;
		}else{&lt;br /&gt;
			// File does not exist&lt;br /&gt;
			resp.writeHead(404, {&lt;br /&gt;
				&amp;quot;Content-Type&amp;quot;: &amp;quot;text/plain&amp;quot;&lt;br /&gt;
			});&lt;br /&gt;
			resp.write(&amp;quot;Requested file not found: &amp;quot;+filename);&lt;br /&gt;
			resp.end();&lt;br /&gt;
			return;&lt;br /&gt;
		}&lt;br /&gt;
	});&lt;br /&gt;
});&lt;br /&gt;
app.listen(3456);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Port 3456 ===&lt;br /&gt;
&lt;br /&gt;
We are running our server on port 3456 as opposed to the default web server port, which of course is 80.  We therefore need to open our Node.js application like this:&lt;br /&gt;
&lt;br /&gt;
http://ec2-xx-xx-xx-xx.compute-1.amazonaws.com:3456/path.extension&lt;br /&gt;
&lt;br /&gt;
However, this won't work on the first time.  ''Why?'' (Try to figure this out on your own before reading the next paragraph.)&lt;br /&gt;
&lt;br /&gt;
We need to open port 3456 on our Amazon EC2 instance.  Remember when you opened port 80 way back in Module 2?  We need to do the same sort of procedure again now.&lt;br /&gt;
&lt;br /&gt;
# Log into your EC2 management console&lt;br /&gt;
# Go to &amp;quot;Security Groups&amp;quot;&lt;br /&gt;
# Select your security group from Module 2&lt;br /&gt;
# Under &amp;quot;Inbound&amp;quot;, create a custom TCP rule for port 3456, and apply your changes.&lt;br /&gt;
&lt;br /&gt;
== Node.js Security ==&lt;br /&gt;
&lt;br /&gt;
Just because we're writing in JavaScript doesn't mean that we can forget about the security practices you've been learning in the last three months of CSE 330.  XSS is still a problem, as is the use of ''eval'', CSRF attacks, and so on.&lt;br /&gt;
&lt;br /&gt;
The two links below have good information about security vulnerabilities specific to Node.js that you should think about when crafting your application.&lt;br /&gt;
&lt;br /&gt;
# Book from PragProg ($24, 2015): https://pragprog.com/book/kdnodesec/secure-your-node-js-web-application&lt;br /&gt;
# Slideshow from a Switzerland Conference on Application Security (2012): http://www.slideshare.net/ASF-WS/asfws-2012-nodejs-security-old-vulnerabilities-in-new-dresses-par-sven-vetsch&lt;br /&gt;
&lt;br /&gt;
== Node.js Conventions ==&lt;br /&gt;
&lt;br /&gt;
There ought to be a standard way to save metadata about your app, right?  Well, ''npm'' introduces a straightforward way to do this in the form of a ''package.json'' file.&lt;br /&gt;
&lt;br /&gt;
To make your ''npm'' file with a step-by-step prompt, run in your project root directory:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ npm init&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
One nifty feature of ''package.json'' is the way it automatically handles dependencies.  For example, you can put the following lines in your ''package.json'':&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
  &amp;quot;dependencies&amp;quot;: {&lt;br /&gt;
    &amp;quot;mime&amp;quot;: &amp;quot;~1.6.0&amp;quot;,&lt;br /&gt;
    &amp;quot;socket.io&amp;quot;: &amp;quot;~0.9.16&amp;quot;&lt;br /&gt;
  },&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Then, back on the command line, when you run&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ npm install&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
it automatically installs the dependencies for you!  No more headaches of trying to figure out which modules you need to install; all that information is saved for you in your code base.&lt;br /&gt;
&lt;br /&gt;
'''Tip:''' Once you set up your ''package.json'' file, you can automatically add a dependency to it by using the ''--save'' argument on ''npm install'': &amp;lt;code&amp;gt;npm install --save socket.io&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 7]]&lt;/div&gt;</summary>
		<author><name>Connor</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Amazon_Web_Services&amp;diff=2696</id>
		<title>Amazon Web Services</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Amazon_Web_Services&amp;diff=2696"/>
		<updated>2019-12-28T20:36:07Z</updated>

		<summary type="html">&lt;p&gt;Connor: /* Creating and Configuring your EC2 Instance */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Amazon Web Services provides a method to publish web sites on virtual machines in the &amp;quot;cloud.&amp;quot;  In CSE330, you will be using an EC2 instance to host your web site.&lt;br /&gt;
&lt;br /&gt;
Before reading this guide, you should be familiar with Linux and the various distributions of Linux.  Fore more information, refer to [[Linux#Linux Distributions|the Linux guide]].&lt;br /&gt;
&lt;br /&gt;
== Creating and Configuring your EC2 Instance ==&lt;br /&gt;
&lt;br /&gt;
{{RequiredInstructions|content=&lt;br /&gt;
&lt;br /&gt;
Follow these steps to get to the AWS Management Console:&lt;br /&gt;
&lt;br /&gt;
# Create an AWS account: http://aws.amazon.com/&lt;br /&gt;
# Sign up for the EC2 Web Service: http://aws.amazon.com/ec2/&lt;br /&gt;
# Log in to the AWS Management Console&lt;br /&gt;
&lt;br /&gt;
To create your new virtual machine, click '''Launch Instance'''.  Do the following to configure your instance:&lt;br /&gt;
&lt;br /&gt;
# Use the Classic Wizard.&lt;br /&gt;
# Please... Just please choose distribution of Linux labeled &amp;quot;Amazon Linux AMI&amp;quot;. Make sure to double check before selecting, as it recently has been showing up as the second option and selecting another distribution can cause problems later. For more information on distributions, refer to [[Linux#Linux Distributions|the Linux guide]].&lt;br /&gt;
[[File:Aws-ami.png|600px|center]]&lt;br /&gt;
# The default instance variables are all fine.  Click Continue until you get to the &amp;quot;Create Key Pair&amp;quot; screen.&lt;br /&gt;
# Create a new Key Pair.  Enter some name for it, and then click &amp;quot;Create &amp;amp; Download your Key Pair&amp;quot;.  '''Save your key somewhere secure.'''  In addition to using it to authenticate for this instance, you will be able to use the same key for additional instances.&lt;br /&gt;
# Create a new Security Group and connect it to your server.  The security groups you create determine whether a port is open or blocked for your server.&lt;br /&gt;
#* You need to open the SSH port on your server.  To do this, select &amp;quot;SSH&amp;quot; from the drop-down box, and then click &amp;quot;Add Rule.&amp;quot;&lt;br /&gt;
#: We will be opening more ports by modifying the security group at a later time.  Click Continue.&lt;br /&gt;
# You are now ready to launch your virtual server!  Click Launch.&lt;br /&gt;
&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
== Starting and Stopping your EC2 Instance ==&lt;br /&gt;
&lt;br /&gt;
You can start and stop your instance by right-clicking on the instance.  The options are down in the &amp;quot;Instance Lifecycle&amp;quot; section.&lt;br /&gt;
&lt;br /&gt;
=== Amazon EC2 Gives You One Free Micro Instance ===&lt;br /&gt;
&lt;br /&gt;
It is free to keep '''''one''''' micro instance running at all times.  Keeping your instance running around the clock will make your life easier, because then you won't need to always change your hostname in your SSH clients.&lt;br /&gt;
&lt;br /&gt;
For additional Micro instances, or for larger instances, you will be charged hourly for their use.  One non-free Micro instance costs about $14/month; a Small instance costs about $43/month.&lt;br /&gt;
&lt;br /&gt;
=== Terminate vs Stop ===&lt;br /&gt;
&lt;br /&gt;
Never &amp;quot;terminate&amp;quot; your instance, as this PERMANENTLY DELETES the instance! Any time you are done using the instance you should instead &amp;quot;stop&amp;quot; the instance and then when you are ready to resume work you should &amp;quot;start&amp;quot; the instance.&lt;br /&gt;
&lt;br /&gt;
'''Note:''' Frequently committing your work to your repository is a safety net in case something horrible happens to your instance.&lt;br /&gt;
&lt;br /&gt;
== Enabling Web Access to your EC2 Instance ==&lt;br /&gt;
&lt;br /&gt;
{{RequiredInstructions|content=&lt;br /&gt;
&lt;br /&gt;
Once you have configured [[Apache]] (which you will do later in this Module), you will need to open up your EC2 instance to web traffic.  (By default amazon blocks all traffic to our instance.)&lt;br /&gt;
&lt;br /&gt;
Go to the Security Groups under Network &amp;amp; Security on the EC2 webpage. Select your security group, click on the Inbound Tab. Add a new Custom TCP rule with a Port range of 80.  Leave the Source at 0.0.0.0/0 (for all traffic). Click Add Rule, and then click Apply Rule Change.&lt;br /&gt;
&lt;br /&gt;
To make sure things are working, create a file, like '''hello.txt''', in your web server root.  Give it some content (might I suggest &amp;quot;Hello, world!&amp;quot;). The web server root is at /var/www/html&lt;br /&gt;
&lt;br /&gt;
For more information on editing files on the command line, refer to [[Linux#File Editors|the Linux guide]].&lt;br /&gt;
&lt;br /&gt;
You should now be able to visit your server load up the file using your web browser!  Example Link: http://ec2-xxx-xxx-xxx-xx.compute-1.amazonaws.com/hello.txt&lt;br /&gt;
&lt;br /&gt;
NOTE:depending on the city in which your server is located, your link might look like:&lt;br /&gt;
&lt;br /&gt;
http://ec2-xxx-xxx-xxx-xxx.us-west-2.compute.amazonaws.com/hello.txt&lt;br /&gt;
&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 2]]&lt;/div&gt;</summary>
		<author><name>Connor</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=AJAX_and_JSON&amp;diff=2691</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=2691"/>
		<updated>2019-10-20T03:17:07Z</updated>

		<summary type="html">&lt;p&gt;Connor: /* 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;
'''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;
=== Javascript Fetch API ===&lt;br /&gt;
&lt;br /&gt;
While creating an xhr object works, it's messy and hard to cleanly organize javascript's asynchronous nature.&lt;br /&gt;
&lt;br /&gt;
Javascript has a fetch api that you should be using.&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, create a fetch object with method &amp;quot;GET&amp;quot;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
fetch('/path/to/php/file', {&lt;br /&gt;
    method: &amp;quot;GET&amp;quot;&lt;br /&gt;
})&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You can build your url to include GET variables if you want to send data.&lt;br /&gt;
ex: '/path/to/php/file?x='hi'&lt;br /&gt;
&lt;br /&gt;
==== POST Data ====&lt;br /&gt;
&lt;br /&gt;
To send POST data, create a fetch object with method &amp;quot;POST&amp;quot;.  You need to create an object of the data you want to send.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
const data = { x: 'hi', y: 'hello' };&lt;br /&gt;
fetch('/path/to/php/file', {&lt;br /&gt;
    method: &amp;quot;POST&amp;quot;,&lt;br /&gt;
    body: JSON.stringify(data)&lt;br /&gt;
})&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Listening for a Response ===&lt;br /&gt;
&lt;br /&gt;
When expecting a response from your php script, javascript's fetch api has a clean promise-based method of handling this.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
const pathToPhpFile = 'test.php';&lt;br /&gt;
const data = { x: 'hi', y: 'hello' };&lt;br /&gt;
fetch(pathToPhpFile, {&lt;br /&gt;
    method: &amp;quot;POST&amp;quot;,&lt;br /&gt;
    body: JSON.stringify(data)&lt;br /&gt;
  })&lt;br /&gt;
  .then(res =&amp;gt; res.json())&lt;br /&gt;
  .then(response =&amp;gt; console.log('Success:', JSON.stringify(response)))&lt;br /&gt;
  .catch(error =&amp;gt; console.error('Error:',error))&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You'll notice unfamiliar syntax here with the .then() methods attached.&lt;br /&gt;
These are attaching event listeners to the end of your fetch request, and will trigger a function when your php script returns a response.&lt;br /&gt;
&lt;br /&gt;
You should '''always''' have a catch block at the end, in case an error occurs in your response. In the near future, Javascript will ignore any requests that do not include a .catch() block.&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;
Please note the difference in accessing POST data.&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;
//Because you are posting the data via fetch(), php has to retrieve it elsewhere.&lt;br /&gt;
$json_str = file_get_contents('php://input');&lt;br /&gt;
//This will store the data into an associative array&lt;br /&gt;
$json_obj = json_decode($json_str, true);&lt;br /&gt;
&lt;br /&gt;
//Variables can be accessed as such:&lt;br /&gt;
$username = $json_obj['username'];&lt;br /&gt;
$password = $json_obj['password'];&lt;br /&gt;
//This is equivalent to what you previously did with $_POST['username'] and $_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;
            method: 'POST',&lt;br /&gt;
            body: JSON.stringify(data),&lt;br /&gt;
            headers: { 'content-type': 'application/json' }&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;
        .catch(err =&amp;gt; console.error(err));&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;
== 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>Connor</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Module_5&amp;diff=2690</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=2690"/>
		<updated>2019-10-19T22:06:42Z</updated>

		<summary type="html">&lt;p&gt;Connor: /* 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 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;
#* '''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;
&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 or warnings 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 in total.&lt;br /&gt;
&lt;br /&gt;
'''Assignments (including code) must be committed to Github 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 individual and group portion running on your instance in the respective README.md, you will receive a 0 for the missing portion&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 (7 points)&lt;br /&gt;
#** Refreshing the page does not log a user out (3 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 adding/editing/deleting 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;
#* '''''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>Connor</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Module_5&amp;diff=2689</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=2689"/>
		<updated>2019-10-19T22:06:03Z</updated>

		<summary type="html">&lt;p&gt;Connor: /* 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 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;
#* '''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;
&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 or warnings 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 in total.&lt;br /&gt;
&lt;br /&gt;
'''Assignments (including code) must be committed to Github 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 individual and group portion running on your instance in the respective README.md, you will receive a 0 for the missing portion&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 (7 points)&lt;br /&gt;
#** Refreshing the page does not log a user out (3 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 performing any server altering functions that can only be done by a logged in user (i.e. not login/signup) (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;
#* '''''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>Connor</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=JavaScript&amp;diff=2688</id>
		<title>JavaScript</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=JavaScript&amp;diff=2688"/>
		<updated>2019-10-11T19:35:17Z</updated>

		<summary type="html">&lt;p&gt;Connor: /* Variables and Scope */&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;
'''Note: We should NOT see any variables initialized with var in your code. Some might appear in the linked examples, since those are from older versions of the language so please replace those with let and const in your mind'''&lt;br /&gt;
Var creates ambiguity to anyone reading your code and is becoming deprecated in JavaScript.&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;
====Arrow Functions====&lt;br /&gt;
The latest versions of JavaScript have introduced arrow functions.  They provide a cleaner syntax for writing functions, and maintain scope when using classes.&lt;br /&gt;
&lt;br /&gt;
The general syntax is: &lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
(param1, param2, ... , paramN) =&amp;gt; { statements }&lt;br /&gt;
&lt;br /&gt;
//removing the brackets around { statements } is equivalent to&lt;br /&gt;
{ return statements; }&lt;br /&gt;
&lt;br /&gt;
//No parameters should be 2 empty parentheses as such: &lt;br /&gt;
() =&amp;gt; { statements }&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The example above could be written as follows:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
const sayHello = (name) =&amp;gt; alert(&amp;quot;Hello, &amp;quot;+name);&lt;br /&gt;
sayHello(&amp;quot;Todd&amp;quot;);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Arrow functions can be particularly useful when you're looking to contain function logic within cleanly and compactly. For example, iterating over an array and making updates to each item of the array.&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
let arr = [1,2,3,4,5];&lt;br /&gt;
let newArr = arr.map(number =&amp;gt; number*5); //newArr is an array containing [5,10,15,20,25]&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>Connor</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=PHP&amp;diff=2687</id>
		<title>PHP</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=PHP&amp;diff=2687"/>
		<updated>2019-09-30T15:12:36Z</updated>

		<summary type="html">&lt;p&gt;Connor: /* Sending a File to the Browser */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;PHP is an open-source language used widely for writing server-side code for web servers.  PHP is a good starting point for web developers, as it is straightforward to learn and yet powerful at the same time.  Indeed, some of the internet's most popular web sites (including Facebook and Wikipedia) are written using PHP as their language of choice!  This article introduces the syntax of PHP and how to make a basic PHP web application.&lt;br /&gt;
&lt;br /&gt;
{{XKCD&lt;br /&gt;
|name=mac_pc&lt;br /&gt;
|id=934&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
== What is PHP? ==&lt;br /&gt;
&lt;br /&gt;
PHP is a server-side scripting language widely used in web development.  PHP is what turns your web site from a static fileserver into a dynamic web application.&lt;br /&gt;
&lt;br /&gt;
By default, Apache only knows how to serve static HTML pages to the client.  You can write as many HTML pages as you want, which is fine for basic web sites.  But if you want to have users post to a forum, or process credit card transactions, or make your own online calendar, a server-side language like PHP is what you need.&lt;br /&gt;
&lt;br /&gt;
=== Document Generation Language ===&lt;br /&gt;
&lt;br /&gt;
If PHP's original core purpose had to be described in three words, it would be this: '''document generation language'''.  Unlike languages including Java, Ruby, Python, and Perl, which consist of classes in a strict program layout, PHP code is most often embedded inside a template document.  When the PHP interpreter runs, it &amp;quot;fills in the gaps&amp;quot; and generates a finished product document.&lt;br /&gt;
&lt;br /&gt;
This isn't to say that PHP can ''only'' be a document generating language, because this is certainly not true.  However, for the purposes of Module 2, it is safe to think of it this way when you are learning the concepts behind a web server.&lt;br /&gt;
&lt;br /&gt;
==== MIME Types ====&lt;br /&gt;
&lt;br /&gt;
By default, PHP generates HTML documents.  (Recall that an HTML document is simply a block of text consisting of markup conforming to the HTML standard.)&lt;br /&gt;
&lt;br /&gt;
However, PHP does not need to generate HTML documents.  It can also generate images, PDFs, or any other type of document.  Each of these document types has its own unique markup language.  The markup language used by a certain document is defined by its ''MIME Type''.&lt;br /&gt;
&lt;br /&gt;
The HTML MIME Type is '''text/html'''.  Other MIME Types include '''image/jpeg''', '''image/png''', and '''application/xml'''.&lt;br /&gt;
&lt;br /&gt;
To change the MIME Type of the document generated by PHP, use the statement:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;php&amp;quot;&amp;gt;&lt;br /&gt;
header(&amp;quot;Content-Type: image/jpeg&amp;quot;);&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Since PHP generates HTML documents by default, you can think of there being an implicit &amp;lt;code&amp;gt;header(&amp;quot;Content-Type: text/html&amp;quot;);&amp;lt;/code&amp;gt; at the top of every PHP script.&lt;br /&gt;
&lt;br /&gt;
=== PHP and Apache ===&lt;br /&gt;
&lt;br /&gt;
When you request a PHP file over Apache, the file is ''not'' sent verbatim.  Instead, it is first sent through the PHP interpreter.  Here is an oversimplified schematic of the process:&lt;br /&gt;
&lt;br /&gt;
[[File:PHP-Apache_Flowchart.png]]&lt;br /&gt;
&lt;br /&gt;
In summary, here are some points to keep in mind.&lt;br /&gt;
&lt;br /&gt;
# A PHP file on your server is not an HTML document.  It is a PHP script.&lt;br /&gt;
# PHP generates documents.  By default, it generates HTML documents.&lt;br /&gt;
# PHP can generate other document types by changing the MIME Type in the Content-Type HTTP Header.&lt;br /&gt;
# Apache runs the PHP interpreter on your PHP script before transmitting it to the browser.  The content that is generated after the PHP interpreter runs is expected to match the MIME type: by default, an HTML document.&lt;br /&gt;
# The W3C Validator checks for valid markup in an HTML document.  Everywhere that PHP generates an HTML document, that HTML document should be valid.&lt;br /&gt;
&lt;br /&gt;
== Installing PHP ==&lt;br /&gt;
&lt;br /&gt;
{{RequiredInstructions|content=&lt;br /&gt;
&lt;br /&gt;
To install PHP 7, you need both the PHP interpreter and the Apache module that runs PHP code. Run the following command to install both&lt;br /&gt;
  sudo yum install -y php70&lt;br /&gt;
&lt;br /&gt;
Once you install the required packages, [[Web Server Configuration#Restarting Apache and Testing|restart Apache]] for the changes to take effect.&lt;br /&gt;
&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
== PHP Configurations ==&lt;br /&gt;
&lt;br /&gt;
{{RequiredInstructions|content=&lt;br /&gt;
&lt;br /&gt;
The PHP configuration file is called ''php.ini''.  In RHEL, it is located at ''/etc/php.ini''.&lt;br /&gt;
&lt;br /&gt;
The configuration file is largely self-documenting as to what the different options mean.  There is one value in particular that we want to change for the purposes of CSE330.  Open php.ini in your favorite text editor, find the '''display_errors''' option, and set it to '''On''':&lt;br /&gt;
&lt;br /&gt;
 display_errors = On&lt;br /&gt;
&lt;br /&gt;
You will need to restart Apache for any php.ini changes to take effect.&lt;br /&gt;
&lt;br /&gt;
'''Note:''' You can turn errors on or off for a certain PHP script by using the '''error_reporting()''' and/or '''ini_set()''' functions.&lt;br /&gt;
&lt;br /&gt;
'''Note:''' If you tell PHP to log its errors, they will be stored in the Apache error log file, at ''/var/log/httpd/error_log''.&lt;br /&gt;
&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
== Your First PHP Script ==&lt;br /&gt;
&lt;br /&gt;
By default, all files that have the *.php extension will be interpreted as containing PHP code.  &lt;br /&gt;
All files with PHP need to be saved as '.php'; not '.html'.&lt;br /&gt;
Here is the most basic 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;
phpinfo();&lt;br /&gt;
?&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Save that code into a file named phpinfo.php, and save it in your web server directory (/var/www/html/).  Load it up in your browser like this: ''http://ec2-blah-blah.compute-1.amazonaws.com/phpinfo.php''&lt;br /&gt;
&lt;br /&gt;
If you see something like this, your PHP installation is working!&lt;br /&gt;
&lt;br /&gt;
[[Image:Php_info.png]]&lt;br /&gt;
&lt;br /&gt;
Look at the source code of that page.  Notice that even though there were only three lines of code in our PHP file, PHP filled it up with hundreds of lines of HTML!&lt;br /&gt;
&lt;br /&gt;
Your own PHP scripts will probably look something more like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;php&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;&lt;br /&gt;
	&amp;lt;title&amp;gt;My First PHP Script&amp;lt;/title&amp;gt;&lt;br /&gt;
&amp;lt;/head&amp;gt;&lt;br /&gt;
&amp;lt;body&amp;gt;&lt;br /&gt;
&amp;lt;?php&lt;br /&gt;
echo &amp;quot;\t&amp;lt;p&amp;gt;Hello World!&amp;lt;/p&amp;gt;\n&amp;quot;;&lt;br /&gt;
?&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;
The above code will send the following HTML to the browser:&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;&lt;br /&gt;
	&amp;lt;title&amp;gt;My First PHP Script&amp;lt;/title&amp;gt;&lt;br /&gt;
&amp;lt;/head&amp;gt;&lt;br /&gt;
&amp;lt;body&amp;gt;&lt;br /&gt;
	&amp;lt;p&amp;gt;Hello World!&amp;lt;/p&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;
Here's the take-home message of this section.  To run PHP code, enclose it in &amp;lt;code&amp;gt;&amp;lt;?php  ?&amp;gt;&amp;lt;/code&amp;gt; tags; HTML code can be used in a PHP file (although not inside the PHP code block!); and just a few lines of code can generate an arbitrary amount of HTML.&lt;br /&gt;
&lt;br /&gt;
== PHP Language Components ==&lt;br /&gt;
&lt;br /&gt;
PHP is a programming language much like others you have learned: it has variables, arrays, functions, objects etc.  However, the syntax for PHP and the way PHP handles variables may be new to you.  This section gives an overview of PHP the language.&lt;br /&gt;
&lt;br /&gt;
=== Variables ===&lt;br /&gt;
&lt;br /&gt;
All variables start with the currency '''$''' symbol.  The '''$''' is necessary for both setting and accessing.&lt;br /&gt;
&lt;br /&gt;
PHP is a weak-typed language; that is, you can set any type of value to a variable (string, array, number, etc), and PHP will accept it, even if that variable previously contained a different data type.  In some ways this is convenient, but in others it can lead to hard-to-detect bugs, so be careful.&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;
$i = 5;  # Set the integer 5 to the variable $i&lt;br /&gt;
$msg = &amp;quot;Hello World&amp;quot;;  # Set the string Hello World to the variable $msg&lt;br /&gt;
?&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Notice that all lines in PHP necessarily end with a semicolon.  If you forget a semicolon, the PHP will fail to parse!&lt;br /&gt;
&lt;br /&gt;
=== Strings ===&lt;br /&gt;
&lt;br /&gt;
Strings in PHP can be either single-quoted or double-quoted.  Single-quoted strings are always taken literally; double-quoted strings allow for additional elements.&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;
$a = &amp;quot;Apple&amp;quot;;&lt;br /&gt;
$b = &amp;quot;Banana&amp;quot;;&lt;br /&gt;
&lt;br /&gt;
$fruits_double = &amp;quot;$a\n$b&amp;quot;;   # $fruits_double now contains the string Apple (line break) Banana&lt;br /&gt;
$fruits_single = '$a\n$b';   # $fruits_single now contains the string $a\n$b&lt;br /&gt;
?&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If you want to use special characters in a double-quoted strings, escape them using the backslash operator:&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;
$a = &amp;quot;Apple&amp;quot;;&lt;br /&gt;
$b = &amp;quot;Banana&amp;quot;;&lt;br /&gt;
&lt;br /&gt;
$fruits = &amp;quot;\$a\\n$b&amp;quot;;   # $fruits now contains the string $a\nBanana&lt;br /&gt;
?&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You can concatenate multiple strings together using the concatenation operator, which in php is a period:&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;
$c = &amp;quot;Cherry&amp;quot;;&lt;br /&gt;
$g = &amp;quot;Grapefruit&amp;quot;;&lt;br /&gt;
&lt;br /&gt;
$fruits = $c.&amp;quot;\n&amp;quot;.$g;   # $fruits contains the string Cherry (line break) Grapefruit&lt;br /&gt;
?&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Arrays ===&lt;br /&gt;
&lt;br /&gt;
Declaring arrays is very simple in 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;
&lt;br /&gt;
$fruits = array(&amp;quot;Apple&amp;quot;, &amp;quot;Banana&amp;quot;, &amp;quot;Cherry&amp;quot;, &amp;quot;Grapefruit&amp;quot;);   # $arr now contains an array with 4 items&lt;br /&gt;
&lt;br /&gt;
echo $fruits[1];   # displays Banana&lt;br /&gt;
&lt;br /&gt;
echo count($fruits);   # displays 4&lt;br /&gt;
&lt;br /&gt;
array_shift($fruits);   # remove the first element of the array&lt;br /&gt;
&lt;br /&gt;
echo $fruits[1];   # displays Cherry&lt;br /&gt;
&lt;br /&gt;
echo count($fruits);   # displays 3&lt;br /&gt;
&lt;br /&gt;
?&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note: '''echo''' outputs a string to the browser.  We will see more ways to output data [[#Outputting Data|later in this guide]].&lt;br /&gt;
&lt;br /&gt;
PHP also supports ''associative arrays''.  Associative arrays are arrays whose keys are strings rather than numbers; in some languages, they are called Dictionaries.&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;
$fruits[&amp;quot;a&amp;quot;] = &amp;quot;Apple&amp;quot;;&lt;br /&gt;
$fruits[&amp;quot;b&amp;quot;] = &amp;quot;Banana&amp;quot;;&lt;br /&gt;
$fruits[&amp;quot;c&amp;quot;] = &amp;quot;Cherry&amp;quot;;&lt;br /&gt;
$fruits[&amp;quot;g&amp;quot;] = &amp;quot;Grapefruit&amp;quot;;&lt;br /&gt;
&lt;br /&gt;
echo $fruits[&amp;quot;c&amp;quot;];   # displays Cherry&lt;br /&gt;
&lt;br /&gt;
$keys = array_keys($fruits);   # get an array containing indexed values of the fruits' keys&lt;br /&gt;
&lt;br /&gt;
echo $keys[3];   # displays g&lt;br /&gt;
&lt;br /&gt;
?&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Conditional Statements ===&lt;br /&gt;
&lt;br /&gt;
Conditional statements work similarly to how they do in other languages.&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;
$grade = 85;&lt;br /&gt;
&lt;br /&gt;
if ($grade &amp;lt; 60) {&lt;br /&gt;
	echo &amp;quot;F&amp;quot;;&lt;br /&gt;
} elseif ($grade &amp;lt; 70) {&lt;br /&gt;
	echo &amp;quot;D&amp;quot;;&lt;br /&gt;
} elseif ($grade &amp;lt; 80) {&lt;br /&gt;
	echo &amp;quot;C&amp;quot;;&lt;br /&gt;
} elseif ($grade &amp;lt; 90) {&lt;br /&gt;
	echo &amp;quot;B&amp;quot;;&lt;br /&gt;
} else {&lt;br /&gt;
	echo &amp;quot;A&amp;quot;;&lt;br /&gt;
}&lt;br /&gt;
?&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
PHP also supports switch statements, which are convenient for simplifying long if/elseif/else blocks:&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;
$food = &amp;quot;Apple&amp;quot;;&lt;br /&gt;
&lt;br /&gt;
switch ($food) {&lt;br /&gt;
&lt;br /&gt;
case &amp;quot;Apple&amp;quot;:&lt;br /&gt;
case &amp;quot;Banana&amp;quot;:&lt;br /&gt;
case &amp;quot;Cherry&amp;quot;:&lt;br /&gt;
case &amp;quot;Grapefruit&amp;quot;:&lt;br /&gt;
	echo &amp;quot;You must like fruit!&amp;quot;;&lt;br /&gt;
	break;&lt;br /&gt;
case &amp;quot;Broccoli&amp;quot;:&lt;br /&gt;
case &amp;quot;Spinach&amp;quot;:&lt;br /&gt;
	echo &amp;quot;You must like vegetables!&amp;quot;;&lt;br /&gt;
	break;&lt;br /&gt;
default:&lt;br /&gt;
	echo &amp;quot;You don't like fruits or vegetables!&amp;quot;;&lt;br /&gt;
	break;&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
?&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Loops ===&lt;br /&gt;
&lt;br /&gt;
PHP supports several different kinds of loops, including while, for, and foreach:&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;
$mystring = &amp;quot;&amp;quot;;&lt;br /&gt;
$i = 0;&lt;br /&gt;
while ($i &amp;lt; 5) {&lt;br /&gt;
	$mystring .= &amp;quot;Blah&amp;quot;;&lt;br /&gt;
	$i++;&lt;br /&gt;
}&lt;br /&gt;
echo $mystring;   # displays BlahBlahBlahBlahBlah&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
$myarray = array(&amp;quot;Apple&amp;quot;, &amp;quot;Banana&amp;quot;, &amp;quot;Cherry&amp;quot;, &amp;quot;Grapefruit&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
# The following two loops are functionally equivalent.&lt;br /&gt;
&lt;br /&gt;
$mystring = &amp;quot;&amp;quot;;&lt;br /&gt;
for($i=0; $i&amp;lt;count($myarray); $i++){&lt;br /&gt;
	$mystring .= $i.&amp;quot;: &amp;quot;.$myarray[$i].&amp;quot;, &amp;quot;;&lt;br /&gt;
}&lt;br /&gt;
echo $mystring;   # displays 0: Apple, 1: Banana, 2: Cherry, 3: Grapefruit&lt;br /&gt;
&lt;br /&gt;
$mystring = &amp;quot;&amp;quot;;&lt;br /&gt;
foreach($myarray as $key =&amp;gt; $value){&lt;br /&gt;
	$mystring .= $key.&amp;quot;: &amp;quot;.$value;&lt;br /&gt;
}&lt;br /&gt;
echo $mystring;   #displays 0: Apple, 1: Banana, 2: Cherry, 3: Grapefruit&lt;br /&gt;
&lt;br /&gt;
?&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Functions ===&lt;br /&gt;
&lt;br /&gt;
Just like with all modern programming languages, you can define your own functions with 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;
&lt;br /&gt;
function add($x, $y){&lt;br /&gt;
	return $x + $y;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
echo add(3, 5);   # displays 8&lt;br /&gt;
&lt;br /&gt;
?&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
A neat shortcut for PHP is that you can specify default parameter values directly in the argument list:&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;
function sayHello($name=&amp;quot;John Doe&amp;quot;){&lt;br /&gt;
	return &amp;quot;Hello, $name... how do you do?&amp;quot;;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
echo sayHello(&amp;quot;Todd&amp;quot;);   # displays Hello, Todd... how do you do?&lt;br /&gt;
echo sayHello();   # displays Hello, John Doe... how do you do?&lt;br /&gt;
&lt;br /&gt;
?&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Object-Oriented Programming ===&lt;br /&gt;
&lt;br /&gt;
PHP5 supports object-oriented programming, and many new libraries come as classes rather than simple functions.  Here is an example class definition:&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;
class Food {&lt;br /&gt;
	protected $name;&lt;br /&gt;
	&lt;br /&gt;
	function __construct($name){&lt;br /&gt;
		$this-&amp;gt;name = $name;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	static function getDefinition(){&lt;br /&gt;
		return &amp;quot;Food is nourishment for carbon-based lifeforms.&amp;quot;;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	function formatName(){&lt;br /&gt;
		return &amp;quot;Gotta love to eat &amp;quot; . $this-&amp;gt;name;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
class Fruit extends Food {&lt;br /&gt;
	function formatName(){&lt;br /&gt;
		return Food::formatName() . &amp;quot; (fruit)&amp;quot;;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
$fruit = new Fruit(&amp;quot;Cherry&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
echo $fruit-&amp;gt;formatName() . &amp;quot;\n&amp;quot;;   # displays: Gotta love to eat Cherry (fruit)&lt;br /&gt;
&lt;br /&gt;
echo Fruit::getDefinition() . &amp;quot;\n&amp;quot;;   # displays: Food is nourishment for carbon-based lifeforms.&lt;br /&gt;
&lt;br /&gt;
?&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Things to notice:&lt;br /&gt;
&lt;br /&gt;
* All methods in a class must be preceded by the function keyword.&lt;br /&gt;
* Static methods require the '''static''' keyword&lt;br /&gt;
* Instance methods can refer to the current instance through the implicit variable '''$this'''&lt;br /&gt;
* To access properties and methods from an instance, use an arrow: '''$instance-&amp;gt;property'''&lt;br /&gt;
* To access static properties and methods from a class, use two colons: '''ClassName::StaticPropertyOrMethod'''&lt;br /&gt;
* Instances of classes are defined using the syntax '''$instance = new ClassName();''' like in Java&lt;br /&gt;
&lt;br /&gt;
== Outputting Data ==&lt;br /&gt;
&lt;br /&gt;
What's the point of a web language if we can't output data?  The most basic method for outputting data is using either the '''echo''' or '''print''' statement:&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;
echo &amp;quot;Hello World&amp;quot;;   # outputs Hello World to the browser&lt;br /&gt;
?&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You often find yourself wanting to print all information associated with a variable for debugging purposes.  PHP provides the handy '''var_dump''' function for that:&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;
var_dump($myvar);&lt;br /&gt;
?&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Content Type ===&lt;br /&gt;
&lt;br /&gt;
PHP is just a factory for generating documents.  We've so far seen it create HTML documents, but it can just as easily create images, PDFs, or any other type of interpreted file format.  Each of these files formats has a '''MIME Type''' associated with it.  To specify a MIME type for a page served over HTTP, the &amp;lt;code&amp;gt;Content-Type&amp;lt;/code&amp;gt; header must be set.&lt;br /&gt;
&lt;br /&gt;
This brings up an important point.  '''Every PHP document has an implicit &amp;lt;code&amp;gt;Content-Type: text/html&amp;lt;/code&amp;gt; header.'''  This means that by default, PHP will generate HTML documents.  '''The MIME type for a document can be changed using the header() function:'''&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;
header(&amp;quot;Content-Type: text/plain&amp;quot;);&lt;br /&gt;
echo time();&lt;br /&gt;
?&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above example creates a plain text file containing the current timestamp (number of seconds since January 1, 1970).&lt;br /&gt;
&lt;br /&gt;
For another application of the Content-Type header, see [[#Sending a File to the Browser]]&lt;br /&gt;
&lt;br /&gt;
=== sprintf() ===&lt;br /&gt;
&lt;br /&gt;
Code in PHP that outputs information can get very ugly.  Consider, for example, the following snippet:&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;
$medals = array(&lt;br /&gt;
	&amp;quot;United States&amp;quot; =&amp;gt; array(46, 29, 29),&lt;br /&gt;
	&amp;quot;China&amp;quot; =&amp;gt; array(38, 27, 23),&lt;br /&gt;
	&amp;quot;Russia&amp;quot; =&amp;gt; array(24, 26, 32)&lt;br /&gt;
);&lt;br /&gt;
?&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;table&amp;gt;&lt;br /&gt;
	&amp;lt;tr&amp;gt;&lt;br /&gt;
		&amp;lt;th&amp;gt;Country&amp;lt;/th&amp;gt;&lt;br /&gt;
		&amp;lt;th&amp;gt;Gold Medals&amp;lt;/th&amp;gt;&lt;br /&gt;
		&amp;lt;th&amp;gt;Silver Medals&amp;lt;/th&amp;gt;&lt;br /&gt;
		&amp;lt;th&amp;gt;Bronze Medals&amp;lt;/th&amp;gt;&lt;br /&gt;
	&amp;lt;/tr&amp;gt;&lt;br /&gt;
&amp;lt;?php&lt;br /&gt;
foreach($medals as $country =&amp;gt; $counts){&lt;br /&gt;
	echo &amp;quot;\t&amp;lt;tr&amp;gt;\n\t\t&amp;lt;td&amp;gt;&amp;quot;.htmlentities($country).&amp;quot;&amp;lt;/td&amp;gt;\n\t\t&amp;lt;td&amp;gt;&amp;quot;.htmlentities($counts[0]).&amp;quot;&amp;lt;/td&amp;gt;\n\t\t&amp;lt;td&amp;gt;&amp;quot;.htmlentities($counts[1]).&amp;quot;&amp;lt;/td&amp;gt;\n\t\t&amp;lt;td&amp;gt;&amp;quot;.htmlentities($counts[2]).&amp;quot;&amp;lt;/td&amp;gt;\n\t&amp;lt;/tr&amp;gt;\n&amp;quot;;&lt;br /&gt;
}&lt;br /&gt;
?&amp;gt;&lt;br /&gt;
&amp;lt;/table&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This code will generate 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;table&amp;gt;&lt;br /&gt;
	&amp;lt;tr&amp;gt;&lt;br /&gt;
		&amp;lt;th&amp;gt;Country&amp;lt;/th&amp;gt;&lt;br /&gt;
		&amp;lt;th&amp;gt;Gold Medals&amp;lt;/th&amp;gt;&lt;br /&gt;
		&amp;lt;th&amp;gt;Silver Medals&amp;lt;/th&amp;gt;&lt;br /&gt;
		&amp;lt;th&amp;gt;Bronze Medals&amp;lt;/th&amp;gt;&lt;br /&gt;
	&amp;lt;/tr&amp;gt;&lt;br /&gt;
	&amp;lt;tr&amp;gt;&lt;br /&gt;
		&amp;lt;td&amp;gt;United States&amp;lt;/td&amp;gt;&lt;br /&gt;
		&amp;lt;td&amp;gt;46&amp;lt;/td&amp;gt;&lt;br /&gt;
		&amp;lt;td&amp;gt;29&amp;lt;/td&amp;gt;&lt;br /&gt;
		&amp;lt;td&amp;gt;29&amp;lt;/td&amp;gt;&lt;br /&gt;
	&amp;lt;/tr&amp;gt;&lt;br /&gt;
	&amp;lt;tr&amp;gt;&lt;br /&gt;
		&amp;lt;td&amp;gt;China&amp;lt;/td&amp;gt;&lt;br /&gt;
		&amp;lt;td&amp;gt;38&amp;lt;/td&amp;gt;&lt;br /&gt;
		&amp;lt;td&amp;gt;27&amp;lt;/td&amp;gt;&lt;br /&gt;
		&amp;lt;td&amp;gt;23&amp;lt;/td&amp;gt;&lt;br /&gt;
	&amp;lt;/tr&amp;gt;&lt;br /&gt;
	&amp;lt;tr&amp;gt;&lt;br /&gt;
		&amp;lt;td&amp;gt;Russia&amp;lt;/td&amp;gt;&lt;br /&gt;
		&amp;lt;td&amp;gt;24&amp;lt;/td&amp;gt;&lt;br /&gt;
		&amp;lt;td&amp;gt;26&amp;lt;/td&amp;gt;&lt;br /&gt;
		&amp;lt;td&amp;gt;32&amp;lt;/td&amp;gt;&lt;br /&gt;
	&amp;lt;/tr&amp;gt;&lt;br /&gt;
&amp;lt;/table&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It's not very clear, though, that this is what the PHP code is going to generate.  In particular, the ''echo'' line inside the ''foreach'' loop is 196 jumbled characters!&lt;br /&gt;
&lt;br /&gt;
'''sprintf()''' is a nifty PHP function (with roots in C) that allows us to clean up that code.  We get the same output as above if we use the following PHP instead:&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;
$medals = array(&lt;br /&gt;
	&amp;quot;United States&amp;quot; =&amp;gt; array(46, 29, 29),&lt;br /&gt;
	&amp;quot;China&amp;quot; =&amp;gt; array(38, 27, 23),&lt;br /&gt;
	&amp;quot;Russia&amp;quot; =&amp;gt; array(24, 26, 32)&lt;br /&gt;
);&lt;br /&gt;
?&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;table&amp;gt;&lt;br /&gt;
	&amp;lt;tr&amp;gt;&lt;br /&gt;
		&amp;lt;th&amp;gt;Country&amp;lt;/th&amp;gt;&lt;br /&gt;
		&amp;lt;th&amp;gt;Gold Medals&amp;lt;/th&amp;gt;&lt;br /&gt;
		&amp;lt;th&amp;gt;Silver Medals&amp;lt;/th&amp;gt;&lt;br /&gt;
		&amp;lt;th&amp;gt;Bronze Medals&amp;lt;/th&amp;gt;&lt;br /&gt;
	&amp;lt;/tr&amp;gt;&lt;br /&gt;
&amp;lt;?php&lt;br /&gt;
foreach($medals as $country =&amp;gt; $counts){&lt;br /&gt;
	echo sprintf(&amp;quot;\t&amp;lt;tr&amp;gt;\n\t\t&amp;lt;td&amp;gt;%s&amp;lt;/td&amp;gt;\n\t\t&amp;lt;td&amp;gt;%d&amp;lt;/td&amp;gt;\n\t\t&amp;lt;td&amp;gt;%d&amp;lt;/td&amp;gt;\n\t\t&amp;lt;td&amp;gt;%d&amp;lt;/td&amp;gt;\n\t&amp;lt;/tr&amp;gt;\n&amp;quot;,&lt;br /&gt;
		htmlentities($country),&lt;br /&gt;
		$counts[0],&lt;br /&gt;
		$counts[1],&lt;br /&gt;
		$counts[2]&lt;br /&gt;
	);&lt;br /&gt;
}&lt;br /&gt;
?&amp;gt;&lt;br /&gt;
&amp;lt;/table&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above code is more straightforward and self-explanatory than the first example, and it is also easier to edit and maintain.&lt;br /&gt;
&lt;br /&gt;
Here's how '''sprintf()''' works.  The first argument is a ''format string''.  A format string can contain ''conversion specifications'' for additional data that will be inserted into the format string.  The most common conversion specifications are:&lt;br /&gt;
&lt;br /&gt;
* '''%s''' for a string&lt;br /&gt;
* '''%d''' for a signed integer&lt;br /&gt;
* '''%u''' for an unsigned integer&lt;br /&gt;
* '''%f''' for a floating-point number&lt;br /&gt;
** '''%.2f''' for a floating-point number with 2 decimal places&lt;br /&gt;
* '''%%''' for a literal percentage sign&lt;br /&gt;
&lt;br /&gt;
For more detail on sprintf formats, refer to [http://us.php.net/sprintf the PHP documentation].&lt;br /&gt;
&lt;br /&gt;
The remaining arguments are the data that are inserted into each of the conversion specifications.  In the example above, there are four conversion specifications ('''%s''', '''%d''', '''%d''', and '''%d'''), so '''sprintf()''' takes 4 additional arguments after the format string.&lt;br /&gt;
&lt;br /&gt;
Note that we still need to sanitize string output (using '''htmlentities()''' ) when we are using '''sprintf()'''.  However, since our format string specifies integers for the remaining three arguments, '''sprintf()''' will take care of type casting, so we no longer need to worry about sanitizing the integers.&lt;br /&gt;
&lt;br /&gt;
An additional tip: '''printf()''' is a shortcut for '''echo sprintf()'''.  That is, the following lines are functionally equivalent:&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;
$n = 12345.678;&lt;br /&gt;
printf(&amp;quot;%.2f\n&amp;quot;, $n); // prints 12345.68&lt;br /&gt;
echo sprintf(&amp;quot;%.2f\n&amp;quot;, $n); // also prints 12345.68&lt;br /&gt;
?&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Passing Variables ==&lt;br /&gt;
&lt;br /&gt;
Input values can be passed to a script either through the URL request line or through data submitted by a form. Built in arrays $_GET['var'] and $_POST['var'] return the value of ''var'' depending on the access method. As we will see in the next section, values can also be passed through session variables. Finally, you can use cookies to store and retrieve values. &lt;br /&gt;
&lt;br /&gt;
Note that upon submitting a form, the page specified in the form tag's action attribute is loaded (with variables sent via post or get).&lt;br /&gt;
&lt;br /&gt;
=== GET: Passing Variables via URL ===&lt;br /&gt;
&lt;br /&gt;
If you want to pass values in a URL, the format is &amp;lt;nowiki&amp;gt;''http://example.com/yourphpfile.php?var1=value1&amp;amp;var2=value2.....''&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
PHP saves URL variables in the associative array '''$_GET'''.&lt;br /&gt;
&lt;br /&gt;
For example, the following PHP document would print a hello message according to a name given in the URL.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;php&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE html&amp;gt;&lt;br /&gt;
&amp;lt;head&amp;gt;&amp;lt;title&amp;gt;Hello World&amp;lt;/title&amp;gt;&amp;lt;/head&amp;gt;&lt;br /&gt;
&amp;lt;body&amp;gt;&lt;br /&gt;
&amp;lt;?php&lt;br /&gt;
$name = $_GET['name'];&lt;br /&gt;
&lt;br /&gt;
printf(&amp;quot;&amp;lt;p&amp;gt;Hello, %s; how do you do?&amp;lt;/p&amp;gt;\n&amp;quot;,&lt;br /&gt;
	htmlentities($name)&lt;br /&gt;
);&lt;br /&gt;
?&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;
If you access the URL like this: ''greeting.php?name=Alice'', it will show ''Hello, Alice; how do you do?''&lt;br /&gt;
&lt;br /&gt;
'''Note:''' Before we output the name, we pass it through '''htmlentities()''', which sanitizes it for output to the HTML document.  This is necessary because if we displayed the name verbatim from the URL, the name could be ''anything'': that includes malicious code that could be run on a victim's computer!  You will learn more about this type of cyberattack, called '''Cross-Site Scripting''', in Module 4.  For now, just know that whenever you display anything to the end user, you need to pass it through '''htmlentities()'''.&lt;br /&gt;
&lt;br /&gt;
=== POST: Passing Variables via Form ===&lt;br /&gt;
&lt;br /&gt;
Another method for passing variables from page to page is by sending it via POST variables.  Like with GET, POST variables are saved in an associative array, this time named '''$_POST'''.&lt;br /&gt;
&lt;br /&gt;
Consider the following form:&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;head&amp;gt;&amp;lt;title&amp;gt;Hello World&amp;lt;/title&amp;gt;&amp;lt;/head&amp;gt;&lt;br /&gt;
&amp;lt;body&amp;gt;&lt;br /&gt;
&amp;lt;form action=&amp;quot;info.php&amp;quot; method=&amp;quot;POST&amp;quot;&amp;gt;&lt;br /&gt;
	&amp;lt;p&amp;gt;&lt;br /&gt;
		&amp;lt;label for=&amp;quot;firstnameinput&amp;quot;&amp;gt;First Name:&amp;lt;/label&amp;gt;&lt;br /&gt;
		&amp;lt;input type=&amp;quot;text&amp;quot; name=&amp;quot;firstname&amp;quot; id=&amp;quot;firstnameinput&amp;quot; /&amp;gt;&lt;br /&gt;
	&amp;lt;/p&amp;gt;&lt;br /&gt;
	&amp;lt;p&amp;gt;&lt;br /&gt;
		&amp;lt;label for=&amp;quot;lastnameinput&amp;quot;&amp;gt;Last Name:&amp;lt;/label&amp;gt;&lt;br /&gt;
		&amp;lt;input type=&amp;quot;text&amp;quot; name=&amp;quot;lastname&amp;quot; id=&amp;quot;lastnameinput&amp;quot; /&amp;gt;&lt;br /&gt;
	&amp;lt;/p&amp;gt;&lt;br /&gt;
	&amp;lt;p&amp;gt;&lt;br /&gt;
		&amp;lt;label for=&amp;quot;birthyearinput&amp;quot;&amp;gt;Birth Year:&amp;lt;/label&amp;gt;&lt;br /&gt;
		&amp;lt;input type=&amp;quot;number&amp;quot; name=&amp;quot;birthyear&amp;quot; id=&amp;quot;birthyearinput&amp;quot; /&amp;gt;&lt;br /&gt;
	&amp;lt;/p&amp;gt;&lt;br /&gt;
	&amp;lt;p&amp;gt;&lt;br /&gt;
		&amp;lt;strong&amp;gt;Gender:&amp;lt;/strong&amp;gt;&lt;br /&gt;
		&amp;lt;input type=&amp;quot;radio&amp;quot; name=&amp;quot;gender&amp;quot; value=&amp;quot;male&amp;quot; id=&amp;quot;maleinput&amp;quot; /&amp;gt; &amp;lt;label for=&amp;quot;maleinput&amp;quot;&amp;gt;Male&amp;lt;/label&amp;gt; &amp;amp;nbsp;&lt;br /&gt;
		&amp;lt;input type=&amp;quot;radio&amp;quot; name=&amp;quot;gender&amp;quot; value=&amp;quot;female&amp;quot; id=&amp;quot;femaleinput&amp;quot; /&amp;gt; &amp;lt;label for=&amp;quot;femaleinput&amp;quot;&amp;gt;Female&amp;lt;/label&amp;gt;&lt;br /&gt;
	&amp;lt;/p&amp;gt;&lt;br /&gt;
	&amp;lt;p&amp;gt;&lt;br /&gt;
		&amp;lt;input type=&amp;quot;submit&amp;quot; value=&amp;quot;Send&amp;quot; /&amp;gt;&lt;br /&gt;
		&amp;lt;input type=&amp;quot;reset&amp;quot; /&amp;gt;&lt;br /&gt;
	&amp;lt;/p&amp;gt;&lt;br /&gt;
&amp;lt;/form&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;
For more information on the HTML markup in the above example, refer to [[HTML and CSS|the HTML and CSS guide]].&lt;br /&gt;
&lt;br /&gt;
This submits a form with POST data to '''info.php'''.  Inside '''info.php''', the provided values will be available in the associative $_POST array under the keys ''firstname'', ''lastname'', ''birthyear'', and ''gender''.&lt;br /&gt;
&lt;br /&gt;
To display the submitted input on a target page, '''info.php''' could contain:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;php&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE html&amp;gt;&lt;br /&gt;
&amp;lt;head&amp;gt;&amp;lt;title&amp;gt;Person Information&amp;lt;/title&amp;gt;&amp;lt;/head&amp;gt;&lt;br /&gt;
&amp;lt;body&amp;gt;&lt;br /&gt;
&amp;lt;?php&lt;br /&gt;
$first = $_POST['firstname'];&lt;br /&gt;
$last = $_POST['lastname'];&lt;br /&gt;
$birthyear = (int) $_POST['birthyear'];&lt;br /&gt;
$gender = $_POST['gender'];&lt;br /&gt;
$age = 2012 - $birthyear;&lt;br /&gt;
&lt;br /&gt;
printf(&amp;quot;&amp;lt;p&amp;gt;Hello, %s %s!  You were born in %d, so you are %d years old.  You are %s.&amp;lt;/p&amp;gt;\n&amp;quot;,&lt;br /&gt;
	htmlentities($first),&lt;br /&gt;
	htmlentities($last),&lt;br /&gt;
	$birthyear,&lt;br /&gt;
	$age,&lt;br /&gt;
	htmlentities($gender)&lt;br /&gt;
);&lt;br /&gt;
?&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;
'''Note:''' It is ''very'' important that you always sanitize strings that you output to the browser using '''htmlentities()''' or a similar function.  If you don't, your site will be vulnerable to all sorts of malware.  For more information, refer to the [[Web Application Security, Part 1|Web Application Security]] guide.&lt;br /&gt;
&lt;br /&gt;
For further help with using HTML forms with PHP, we recommend [http://www.tizag.com/phpT/forms.php this tutorial].&lt;br /&gt;
&lt;br /&gt;
=== Self-Submitting Forms ===&lt;br /&gt;
&lt;br /&gt;
Oftentimes we don't want to pass form values to a different page, but rather to the same page as contains the form so that we can process the information and display output on that same page.  To do this, you can simply omit the '''action''' parameter from the form.  Alternatively, you can use a PHP environment variable like $_SERVER['PHP_SELF'].&lt;br /&gt;
&lt;br /&gt;
The following example simply takes the data input from a form and, via POST variables, echoes it back to the user as bold text on the same page:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;php&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;Bold Printer&amp;lt;/title&amp;gt;&amp;lt;/head&amp;gt;&lt;br /&gt;
&amp;lt;body&amp;gt;&lt;br /&gt;
&amp;lt;form action=&amp;quot;&amp;lt;?php echo htmlentities($_SERVER['PHP_SELF']); ?&amp;gt;&amp;quot; method=&amp;quot;POST&amp;quot;&amp;gt;&lt;br /&gt;
	&amp;lt;p&amp;gt;&lt;br /&gt;
		&amp;lt;label for=&amp;quot;name&amp;quot;&amp;gt;Name:&amp;lt;/label&amp;gt;&lt;br /&gt;
		&amp;lt;input type=&amp;quot;text&amp;quot; name=&amp;quot;name&amp;quot; id=&amp;quot;name&amp;quot; /&amp;gt;&lt;br /&gt;
	&amp;lt;/p&amp;gt;&lt;br /&gt;
	&amp;lt;p&amp;gt;&lt;br /&gt;
		&amp;lt;input type=&amp;quot;submit&amp;quot; value=&amp;quot;Print in Bold&amp;quot; /&amp;gt;&lt;br /&gt;
	&amp;lt;/p&amp;gt;&lt;br /&gt;
&amp;lt;/form&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;?php&lt;br /&gt;
if(isset($_POST['name'])){&lt;br /&gt;
	printf(&amp;quot;&amp;lt;p&amp;gt;&amp;lt;strong&amp;gt;%s&amp;lt;/strong&amp;gt;&amp;lt;/p&amp;gt;\n&amp;quot;,&lt;br /&gt;
		htmlentities($_POST['name'])&lt;br /&gt;
	);&lt;br /&gt;
}&lt;br /&gt;
?&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;
== Sessions ==&lt;br /&gt;
&lt;br /&gt;
If you need to keep track of information associated with a user between page loads, you should use a ''session''.  Sessions are excellent for keeping track of the currently-logged-in user, for example.&lt;br /&gt;
&lt;br /&gt;
PHP makes session management dirt simple.  Whenever you need to use session variables, simply call '''session_start()'''.  Then, you may interact with the $_SESSION associative array, and PHP will take care of accessing and saving all session variables for you!&lt;br /&gt;
&lt;br /&gt;
For example, the following page will display a number, and then double that number on each page reload:&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;
session_start();&lt;br /&gt;
 &lt;br /&gt;
$oldnum = (int) @$_SESSION['inc_num'];&lt;br /&gt;
if($oldnum&amp;lt;1) $oldnum=1;&lt;br /&gt;
$newnum = $oldnum*2;&lt;br /&gt;
 &lt;br /&gt;
echo $newnum;&lt;br /&gt;
$_SESSION['inc_num'] = $newnum;&lt;br /&gt;
?&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Sessions also work across different pages, as long as they are on the same web server.&lt;br /&gt;
&lt;br /&gt;
'''Tip:''' To log out a user, you can call '''session_destroy()''' after '''session_start()''' on the logout page.&lt;br /&gt;
&lt;br /&gt;
== Other PHP Tips ==&lt;br /&gt;
&lt;br /&gt;
=== Redirecting to a Different Page ===&lt;br /&gt;
&lt;br /&gt;
If you want to redirect the user to a different page, you need to send a '''Location''' header.  For example, a page containing only this code would redirect the user to the ''login.php'' file:&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;
header(&amp;quot;Location: login.php&amp;quot;);&lt;br /&gt;
exit;   // we call exit here so that the script will stop executing before the connection is broken&lt;br /&gt;
?&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It is often useful to perform redirects after you perform server-side operations.&lt;br /&gt;
&lt;br /&gt;
'''Important:''' You should generally not leave a user sitting on a page that has POST data, because if they refresh the page, their POST data will be submitted again, causing your server to perform an action twice.  Rather, you should perform the operation, and then redirect them to another page that does not contain POST data in the header.&lt;br /&gt;
&lt;br /&gt;
=== Reading a File Line-by-Line ===&lt;br /&gt;
&lt;br /&gt;
If you want to read a file line-by-line, open a file handler using '''fopen()''', use '''fgets()''' to read lines until you've reached the end, and then close the file using '''fclose()'''.&lt;br /&gt;
&lt;br /&gt;
The following example reads '''file_with_lines.txt''' and outputs its content in an unordered list, where each list item is a line in the file:&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;
$h = fopen(&amp;quot;file_with_lines.txt&amp;quot;, &amp;quot;r&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
$linenum = 1;&lt;br /&gt;
echo &amp;quot;&amp;lt;ul&amp;gt;\n&amp;quot;;&lt;br /&gt;
while( !feof($h) ){&lt;br /&gt;
	printf(&amp;quot;\t&amp;lt;li&amp;gt;Line %d: %s&amp;lt;/li&amp;gt;\n&amp;quot;,&lt;br /&gt;
		$linenum++,&lt;br /&gt;
		fgets($h)&lt;br /&gt;
	);&lt;br /&gt;
}&lt;br /&gt;
echo &amp;quot;&amp;lt;/ul&amp;gt;\n&amp;quot;;&lt;br /&gt;
&lt;br /&gt;
fclose($h);&lt;br /&gt;
?&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Note:''' Most files in Linux end with an empty line, so the very last iteration of the above loop will output an empty bullet point.&lt;br /&gt;
&lt;br /&gt;
'''Note:''' The function '''fgets()''' reads the contents of a line ''in addition to the line feed at the end of the line''.  If you want to compare a string to the line that was read by '''fgets()''', you need to pass the value returned by '''fgets()''' to a function like '''[http://php.net/trim trim()]'''.&lt;br /&gt;
&lt;br /&gt;
'''Note:''' If you want to read an entire file, PHP provides the '''file_get_contents()''' function, which is basically a shortcut for '''fopen()''', '''fread()''', and '''fclose()'''.  ('''fread()''' is similar to '''fgets()''', except it reads the entire file instead of just one line.)&lt;br /&gt;
&lt;br /&gt;
=== Sending a File to the Browser ===&lt;br /&gt;
&lt;br /&gt;
Another useful function to know is the '''readfile''' function. It takes a file on the webserver's file system and sends it to the web browser. A simple example is given below, but note that you'll probably need to specify addition header fields in order to have the web browser download the file correctly.&lt;br /&gt;
&lt;br /&gt;
The following example loads a file associated with a certain username and displays it.&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;
session_start();&lt;br /&gt;
&lt;br /&gt;
$filename = $_GET['file'];&lt;br /&gt;
&lt;br /&gt;
// We need to make sure that the filename is in a valid format; if it's not, display an error and leave the script.&lt;br /&gt;
// To perform the check, we will use a regular expression.&lt;br /&gt;
if( !preg_match('/^[\w_\.\-]+$/', $filename) ){&lt;br /&gt;
	echo &amp;quot;Invalid filename&amp;quot;;&lt;br /&gt;
	exit;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
// Get the username and make sure that it is alphanumeric with limited other characters.&lt;br /&gt;
// You shouldn't allow usernames with unusual characters anyway, but it's always best to perform a sanity check&lt;br /&gt;
// since we will be concatenating the string to load files from the filesystem.&lt;br /&gt;
$username = $_SESSION['username'];&lt;br /&gt;
if( !preg_match('/^[\w_\-]+$/', $username) ){&lt;br /&gt;
	echo &amp;quot;Invalid username&amp;quot;;&lt;br /&gt;
	exit;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
$full_path = sprintf(&amp;quot;/srv/uploads/%s/%s&amp;quot;, $username, $filename);&lt;br /&gt;
&lt;br /&gt;
// Now we need to get the MIME type (e.g., image/jpeg).  PHP provides a neat little interface to do this called finfo.&lt;br /&gt;
$finfo = new finfo(FILEINFO_MIME_TYPE);&lt;br /&gt;
$mime = $finfo-&amp;gt;file($full_path);&lt;br /&gt;
&lt;br /&gt;
// Finally, set the Content-Type header to the MIME type of the file, and display the file.&lt;br /&gt;
header(&amp;quot;Content-Type: &amp;quot;.$mime);&lt;br /&gt;
header('content-disposition: inline; filename=&amp;quot;'.$filename.'&amp;quot;;');&lt;br /&gt;
readfile($full_path);&lt;br /&gt;
&lt;br /&gt;
?&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Uploading a File ===&lt;br /&gt;
&lt;br /&gt;
Uploading files is similar to submitting data in forms.  For starters, you need a form that submits to your uploading script:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;form enctype=&amp;quot;multipart/form-data&amp;quot; action=&amp;quot;uploader.php&amp;quot; method=&amp;quot;POST&amp;quot;&amp;gt;&lt;br /&gt;
	&amp;lt;p&amp;gt;&lt;br /&gt;
		&amp;lt;input type=&amp;quot;hidden&amp;quot; name=&amp;quot;MAX_FILE_SIZE&amp;quot; value=&amp;quot;20000000&amp;quot; /&amp;gt;&lt;br /&gt;
		&amp;lt;label for=&amp;quot;uploadfile_input&amp;quot;&amp;gt;Choose a file to upload:&amp;lt;/label&amp;gt; &amp;lt;input name=&amp;quot;uploadedfile&amp;quot; type=&amp;quot;file&amp;quot; id=&amp;quot;uploadfile_input&amp;quot; /&amp;gt;&lt;br /&gt;
	&amp;lt;/p&amp;gt;&lt;br /&gt;
	&amp;lt;p&amp;gt;&lt;br /&gt;
		&amp;lt;input type=&amp;quot;submit&amp;quot; value=&amp;quot;Upload File&amp;quot; /&amp;gt;&lt;br /&gt;
	&amp;lt;/p&amp;gt;&lt;br /&gt;
&amp;lt;/form&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note that we need to specify &amp;lt;code&amp;gt;enctype=&amp;quot;multipart/form-data&amp;quot;&amp;lt;/code&amp;gt; on the form.  This is to enable files to be uploaded and recognized by PHP.&lt;br /&gt;
&lt;br /&gt;
PHP puts all files submitted with a form into the '''$_FILES''' superglobal array.  Each entry in the $_FILES array contains the following information:&lt;br /&gt;
&lt;br /&gt;
* '''$_FILES['uploadedfile']['name']''' is the original name of the file on the client's machine&lt;br /&gt;
* '''$_FILES['uploadedfile']['type']''' is the MIME type of the file according to the browser (don't take it for granted)&lt;br /&gt;
* '''$_FILES['uploadedfile']['size']''' is the size, in bytes, of the uploaded file&lt;br /&gt;
* '''$_FILES['uploadedfile']['tmp_name']''' is the temporary location on your filesystem where Apache saved the uploaded file&lt;br /&gt;
* '''$_FILES['uploadedfile']['error']''' is the error code associated with the file upload (if applicable)&lt;br /&gt;
&lt;br /&gt;
To upload the file submitted by the form above in a user's special folder, we could use the following PHP 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;
session_start();&lt;br /&gt;
&lt;br /&gt;
// Get the filename and make sure it is valid&lt;br /&gt;
$filename = basename($_FILES['uploadedfile']['name']);&lt;br /&gt;
if( !preg_match('/^[\w_\.\-]+$/', $filename) ){&lt;br /&gt;
	echo &amp;quot;Invalid filename&amp;quot;;&lt;br /&gt;
	exit;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
// Get the username and make sure it is valid&lt;br /&gt;
$username = $_SESSION['username'];&lt;br /&gt;
if( !preg_match('/^[\w_\-]+$/', $username) ){&lt;br /&gt;
	echo &amp;quot;Invalid username&amp;quot;;&lt;br /&gt;
	exit;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
$full_path = sprintf(&amp;quot;/srv/uploads/%s/%s&amp;quot;, $username, $filename);&lt;br /&gt;
&lt;br /&gt;
if( move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $full_path) ){&lt;br /&gt;
	header(&amp;quot;Location: upload_success.html&amp;quot;);&lt;br /&gt;
	exit;&lt;br /&gt;
}else{&lt;br /&gt;
	header(&amp;quot;Location: upload_failure.html&amp;quot;);&lt;br /&gt;
	exit;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
?&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Note:''' A lot of the code above is the same as the code in the file download example.  In your project, you should save the logic of generating the file path (in a function) in a third file that you include into the upload and download scripts.&lt;br /&gt;
&lt;br /&gt;
'''Note:''' By default, PHP will not allow a file upload of more than 2 MB.  SitePoint has an excellent tutorial for how to increase this limit: http://www.sitepoint.com/upload-large-files-in-php/&lt;br /&gt;
&lt;br /&gt;
== PEAR ==&lt;br /&gt;
&lt;br /&gt;
The PHP Extension and Application Repository, or '''PEAR''', is a package manager that enables you to install classes and/or extensions to PHP.  In other words, it is a yum/apt for PHP.  You can think of PEAR as PHP's analog of ''gem'' in Ruby or ''pip'' in Python.&lt;br /&gt;
&lt;br /&gt;
=== Configuration ===&lt;br /&gt;
&lt;br /&gt;
PEAR is available through both the yum and apt repositories under the package name '''php-pear'''.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ sudo yum install php7-pear  # in RHEL&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Installing PHP Extensions ===&lt;br /&gt;
&lt;br /&gt;
Using PEAR to install PHP extensions is just as easy as yum, apt, gem, and pip.  Just run '''sudo pear install xxx'''.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ sudo pear install Archive_Tar&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Go here for a list of available packages in PEAR: http://pear.php.net/packages.php&lt;br /&gt;
&lt;br /&gt;
=== Using PHP Extensions ===&lt;br /&gt;
&lt;br /&gt;
To make use an extension installed in PEAR, you must '''include''' or '''require''' it into the PHP file of interest.  For example, if you wanted to use the Archive_Tar class from the above example in a PHP file, you would do:&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 &amp;quot;Archive/Tar.php&amp;quot;;&lt;br /&gt;
&lt;br /&gt;
// your code here&lt;br /&gt;
?&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
By convention, the filepath you need to specify is the name of the PEAR package with underscores replaced with slashes and a .php extension at the end.  For example, the package ''Console_Getargs'' becomes &amp;lt;code&amp;gt;require &amp;quot;Console/Getargs.php&amp;quot;;&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== PECL ===&lt;br /&gt;
&lt;br /&gt;
The PHP Extension Community Library, or '''PECL''', is a repository for additional PHP extensions, the difference being that PECL extensions are written in compiled C code rather than PHP.&lt;br /&gt;
&lt;br /&gt;
PECL is installed automatically when you install PEAR from yum or apt-get.&lt;br /&gt;
&lt;br /&gt;
Installing an extension using PECL is almost identical to PEAR, except that you use '''pecl''' instead of '''pear''' on the command prompt:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ sudo pecl install imagick&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You do not need to '''require''' or '''include''' PECL extensions since they are already compiled into PHP.&lt;br /&gt;
&lt;br /&gt;
== PHP Reference ==&lt;br /&gt;
&lt;br /&gt;
If you ever have a question about PHP, first check the well-written documentation.  To skip immediately to the documentation on any function, simply visit &amp;lt;nowiki&amp;gt;http://php.net/&amp;lt;/nowiki&amp;gt;'''functionname'''.  For example: http://php.net/var_dump&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 2]]&lt;/div&gt;</summary>
		<author><name>Connor</name></author>
		
	</entry>
</feed>