A Quick Rundown of Python Essay

A Quick Rundown of Python BY jackals I got bored and decided to write an attempt at a bare-minimum Python tutorial for this class. I’m subscribed by email and pretty free today, so I’ll check back if anyone has any questions. I’m no Pro, but I’ve been coding in Python recreational for a couple years now (and I actually try to keep up with what actual pros are saying) so I have some idea what I’m doing. I did this assignment in a few hours, including at least 45 minutes of which was kludging my way around Unicode problems that I’m not used to dealing with because Python 3 wouldn’t have had them.

For knowledge levels, I’m aiming for “already knows a few things about programming”, but I’m actually trying to give a snowball’s chance to people who’ve only programmed from an DID, or run a bunch of MUTUAL code without ever touching a command line or similar. I wont explain things like what if or for meaner for the people who didn’t notice the class specified “some programming knowledge”. That said, anyone who’s in this class and hasn’t given up yet, I’m interested in any feedback (and hope the staff for this class notices as well).

We Will Write a Custom Essay Specifically
For You For Only $13.90/page!


order now

Same for people who want to yell at me and tell me I’m wrong. I also sometimes mention things without explaining them. Many of these things are “useful if you know what this meaner, but confusing if you don’t. ” If you understand only 80% of this you might get along Just fine with only that 80% for now. I try to link to documentation where relevant. You’ll notice I give almost no logic specific to the assignment; I’m Just trying to tell you exactly which parts of Python you need to know before trying to figure out what to do with it.

I skip over explaining stuff like print that you can figure out from context for the same reason. I often mention something and immediately say “don’t do this”. What I mean is, “this is generally a ad idea, but I think you should know it exists. Avoid it for now and look it up if you’re that curious. ” I’d normally wait a day and edit before posting something this massive, but we don’t have that kind of time. Sorry in advance for any errors. This Tutorial’s Conventions The code samples below are going to contain a combination of running programs and interactive typing in the Python shell.

If you see a line starting with $, that meaner “you should be at the command line and type this in if you want to see it run yourself”. If it starts with try it from within the Python shell (which you can get to y running “python” with no other options). If a code block starts with some_file_name. Pay, you can put all of the code in a file and save the file to try running it. If a code sample has no shown output or filename, then I’m Just explaining something without showing a full running example. I’ll try not to do this often. The Setup Python is easy enough to set up that I refuse to even look at the virtual machine.

If you prefer to use it, and you can get it up and running, then skip to the next section, but if you want help getting it set up, someone else will have to make that post. If you don’t already have it, go here and download Python 2. 7. 4 (or use your package manager if you both have one and know what that is). I like Python 3 better than Python 2, but Python 3 won’t work with the code in this class and 2. 7. 4 is the newest and best Python 2. If you don’t already know what your command line is, it’s time to get started. The provided examples from the class are in a Unix terminal.

The teachers are probably using Linux, but if you are on a Mac, you also have a Unix command line. Windows users don’t, but you go “Start->Run” and type “CM” to get a Windows command prompt. You can run the programs themselves in Windows Just fine as long as you stick to “python” and related commands, although the Unix native stuff like “Is” won’t work. You can get by without it for now, or you can install Syncing if you really want a Unix shell, or maybe some other nice person will make a detailed post about the Windows command prompt.

In both operating systems, the most important command is “CD” to change directories until you get to the one your program is in. If you can figure out “CD to my program directory, then python [file]” you can do enough to get through the first assignment. In all operating systems that I know of, the following all work: $ CD [full directory path] # go to full directory path $ CD / # go to top level directory $ CD directory # go to directory contained in the current directory If you want to see what’s in your current directory, you can use “Is” in Unix and “dir” in Windows.

Eighth Kit is kind of tricky to get used to and if you’ve never used source control before you’re not going to figure it out in the next day while also figuring out the assignment. You can try to run the code without using eighth for now; Just download the ZIP file from the project page and extract it wherever. It’s also fine to start using Kit later when you have more time to figure it out. Installing Packages Even this first assignment requires third-party modules, so you might as well get this out of the way.

The first thing I would recommend installing is pip, because pip makes it a lot easier to install other Python things. Get it here. Look for a binary installer $ pip install [module name] Download the archive, extract it wherever you want it installed, then $ python setup. Pay install in whatever directory has setup. Pay in it. For any remotely popular library, one of those things should work. Editing and Running Code Python comes with a programming environment called IDLE.

It hasn’t been updated since the dark ages, is slow, and has gross incompatibilities even with some code running only Python standard libraries. It’s awful. If you have a favorite plaintext editor, use that. If you don’t have a favorite or don’t know what that is, go download egged. To create a Python program, save it in a text file (it’s standard to end this file with . Pay). Then run it by typing this from your program directory: $ python my_program. Pay Syntax and Whiteface Python is highly unusual in that whiteface is syntactically significant.

If you’re used o a language with braces, it wouldn’t be far off to say that anything that would be enclosed in braces is now inline+indent instead. (As an aside, if you know how to replace tabs with spaces in your editor, do so; you don’t want invisible syntax errors). One corollary of significant indentation is that you can’t indent otherwise, or you’ll get Synthesizers. If you ever need an empty block, Python has pass, a no-pop keyword. You don’t need an empty block. I was very careful to mind my indentation here; all examples should be indented exactly as they are shown.

Finally, if you really want a one-line block, you can do this: f condition(x): do_something() Importing Outside Code If you need code from a library, you can use import: import math math. Sort(4) 2. 0 from math import Sort Sort(4) (from math import * also works. Don’t do that. ) If and Conditionals Python if statements take the form: if condition: # code here elf conditions: # optional # more code here else: # also optional # default code here There can be any number of life. There is no switch. If if/elf/else is too unwieldy, you probably want a dictionary.

There is no I l; you use the words and and or (there is no Xerox). The bitwise versions like & still exist. Test equality with n. There is an is keyword; don’t use it. You can easily test most collections for objects using the in keyword. For instance: True ‘dog’ in a False Python is pretty liberal about coercing things to Booleans; True and False are Just special names for 1 and O. Generally, containers are falls if empty and truths otherwise, and numbers are falls if O and truths otherwise. The special value None is falls.

Functions Functions are defined using the defy keyword: defy square(x): return x*x Note, by the way, the need for an explicit return statement. If you don’t have one, Python wont warn you; it returns None, a null value. If you get mysterious errors referring to Nonempty, this is one of the things to look for. Square(3) 9 square(x=5) 25 Python supports default arguments and variable numbers of arguments, though you don’t need them for this assignment. If you do decide to start playing with such things, read this first. Python functions are first-class objects.

Lists A list is essentially a dynamic array, and the literal syntax for it looks a lot like arrays in other languages: You can get any given element by index: print a[2] 3 By the way, Python zero-indexes everything: ring a[3] Traceable (most recent call last): File line 1, in Indexer: list index out of range There is also an easy syntax for slicing (ranges of indices): print all [2,3] You can also omit endpoints; empty slice argument default to the beginning and end of the list: all at:] [2,3], [1 That last one is a handy way to copy a list so you can mutate the copy without changing the original.

Can be particularly important if you’re passing lists to functions. There are two other data types similar to lists that are worth knowing if you write a lot of Python code: duple: Essentially an immutable list. They use papers instead of brackets like and you can basically treat them like lists as long as you don’t try to modify them. Table. They discard all duplicates, can only contain washable values, and make no effort to preserve the order of elements. Very fast because its restrictions allow it to be.

If none of that last part made sense, forget it for now. Just use lists. Dictionaries and SON For dictionaries, think "hash table” if you know what that meaner. A dictionary associates values to keys: >>>d = {1: ‘cat’, 2: ‘dog’, 7: [chicken’, ‘geese’]} ‘cat’ Note that you look things up by key, not value: d[[‘dog’]eyword: ‘dog’ This is also true in for loops, as you’ll see below. As seen above, if you try to get a key that doesn’t exist you will get a Keyword. There are several ways to handle this.

The most straightforward would be to Just check for the key first: if k in D: If you have a sensible default to fall back on, you could also use the . Get method: x = D. Get(k, default_value) You could also Just handle the exception: try: Y = X[k[k]xcept Keyword: # If you want to handle all of the above missing keys the same way Finally, the collections module has some dictionary variants that handle common cases like “a cautionary that always returns a default value for missing keys” and “a dictionary whose keys are things I’m counting”.

The first assignment uses something called SON, which stands for JavaScript Object Notation; it’s a common format for sending data to be readable by multiple Son library parses a SON string to a dictionary. So, for instance, the JavaScript object ‘{“Siege”: 4, “hungry”, true}’ would get parsed to {legs’: 4, ‘hungry’: True}. Yes, the translation is frequently that obvious because JavaScript objects are almost the same thing as Python dictionaries. This also meaner that you can Just look at the SON data room this assignment and tell what keys you’re supposed to be looking for by inspection.

Strings Strings are immutable. They can be indexed like lists. S = ‘dog’ ‘d’ Typesetter: ‘SST’ object does not support item assignment There is no char data type; a one-character string is still a string. Strings can be delimited by ‘ or “. All my examples use the former because I hate the Shift key. Triple quotes like ‘”l””” allow literal (well, more literal… Super-literal? ) strings that can even include things like enlists and other normally-escaped characters. Such strings are often used for documentation.

Python strings use backslash escaping, although note that if your string is surrounded with ‘ you don’t have to escape ” and vice-versa. If you know C-style string formatting (“%d” and such) you can do that. Python strings also have a . Format() method with its own syntax that I forget approximately every other week. The basic version where you Just need to stuff variable values in a string is pretty easy though: >>> print ‘l have 0 dogs! ‘. Format(3) I have 3 dogs! >>> print ‘You can also {1}, {2}, or {1} things with {O}! ‘. Aroma(‘indices’, ‘repeat’, ‘rearrange’) You can also repeat, rearrange, or repeat things with indices! Python 2 has serious difficulties with Unicode that I’m not going to get into because I don’t know that much about it and the class instructions already go into it better than I could. Looping Python while is extremely straightforward: while x Delete that lines function from the class code. It “uses up” the file object. The standard counting for loop (O, 1, 2… ) takes the form for I in range(N) (but use grange instead if N is large) The Python Shell and Why It’s Great You can get into the Python shell using $ python (with no filename). This lets you type in code and see the results immediately so you can quickly try things: for I in range(3): print I 2 Thanks to built-in documentation, the Python shell is actually a really cool way to get used to Python once you get past the most basic syntax.

For example, let’s say I don’t remember what I can do too list. So I initialize an empty list: Then I get list of as methods… Dir(a) [[‘_add format mill reduce seedtime class , ‘_GE nit delegate delimited contains , ‘_jitterbugs_’, ‘_getting_’, ‘_get doc hash tier _CEQ laid new rep It reversed backslashes mull reduce ex spoof arum estates ‘append’, ‘count’, ‘extend’, ‘index’, ‘insert’, ‘pop’, ‘remove’, ‘reverse’, ‘sort’]y the way, ignore the methods that start and end with underscores (_). Not Just for lists, but for everything. They’re for overloading and you should basically never call them directly.

Now, let’s say I’m not sure what “insert” does, so I Just ask: help(a. Insert) insert(.. ) So, instead of thumbing through documentation trying to find the exact parts you want, you can Just look stuff up as you start using it. You can also make it so that your programs stay in a python shell instead of immediately bailing out by adding a “-I” option. In other words: $ python -I off. Pay Will run off. Pay, then put you in a Python REPLY. And the best part is, Python remembers all the code it ran so you can check the values of variables this way!

So, for instance: bathroom. Pay x = a. Pop() $ python -I bathroom. Pay Notice that even though my program failed entirely, I’m in a working Python shell. So now I check what a is: [1[1,2]y the way, there is something that the sample homework does, but I haven’t been doing. This is extremely on purpose. The provided files are structured like this: defy main(): main program code if name main() main This construct has its good points in general, but in the context of this assignment I think it is wrong.

The reason you write code like the above is to make your code more “import safe” … That is, to write code that other people can import without immediately and automatically running it. This doesn’t matter to us because we are uploading these files one at a time without any guarantee that they’ll be able to see each other, so no one will ever import this code. And the downside of code like this is that it’s harder to interactively debug: horsepower’s. Pay

x

Hi!
I'm Laurie!

Would you like to get a custom essay? How about receiving a customized one?

Check it out