Python Basics - University Of Colorado Colorado Springs

1y ago
2.36 MB
49 Pages
Last View : 11d ago
Last Download : 4m ago
Upload by : Gideon Hoey

Python BasicsMarch 22, 2018ContentsIntroduction4Before NumpyThe Environment and Choices . . . . . . . . . . . . . . . . . . . . . .Launching the Jupyter Notebook . . . . . . . . . . . . . . . .Launching the IPython QT Console with the Canopy EditorLaunching the IPython QT Console From the Terminal . . .Launching the Native Python Console From the Terminal .Ending Your Session . . . . . . . . . . . . . . . . . . . . . . .Data Types and Simple Calculations . . . . . . . . . . . . . . . . . .Hello World . . . . . . . . . . . . . . . . . . . . . . . . . . . .float, complex, long, int, str, and boolean . . . . . . . . .Data Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . . . .Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Formatting Strings and Gathering User Input . . . . . . . . . . . . .Formatting Strings and Printing . . . . . . . . . . . . . . . .Gathering User Input . . . . . . . . . . . . . . . . . . . . . . .Flow Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .If, elif, and else . . . . . . . . . . . . . . . . . . . . . . . . . .For Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . .While Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . .The Statements break and continue . . . . . . . . . . . . . .Exceptions: try, except, and finally Blocks . . . . . . . . . . . . .Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Object Oriented Python: Writing a Class . . . . . . . . . . . . . . . .Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Writing a Simple Class . . . . . . . . . . . . . . . . . . . . . .1.44468999910171719202121212325262728293030313131

After NumpyNumPy Fundamentals . . . . . . . . . . . . . . . . . . .The N-Dimensional Array and Available TypesArray Creation . . . . . . . . . . . . . . . . . . .Working With Arrays . . . . . . . . . . . . . . .Graphics and More with Matplotlib333333353640Signals and Systems Tools and ExamplesThe Scipy Module scipy.signal . . . . .Using scikit-dsp-comm . . . . . . . . . .More Modules . . . . . . . . . . . . . . . .A Simple DSP Class Case Study . . . . . .The class Code Base . . . . . . . .Lowpass and Bandpass Examples.References.4040414242424749In [1]: %pylab inline#%matplotlib qt#from future import division # use so 1/2 0.5, etc.import sk dsp comm.sigsys as ssimport scipy.signal as signalfrom IPython.display import Image, SVGPopulating the interactive namespace from numpy and matplotlibIn [2]: %config InlineBackend.figure formats ['svg'] # SVG inline viewing#%config InlineBackend.figure formats ['pdf'] # render pdf figs for LaTeX2

In [34]: print('Hello World')Hello WorldIn [35]: 2*piOut[35]: 6.283185307179586In [36]: arange(0,1,.1)Out[36]: array([ 0. ,0.1,0.2,0.3,0.4,30.5,0.6,0.7,0.8,0.9])

IntroductionThis tutorial is structured around the idea that you want to get up and running with Python usingPyLab as quickly as possible. The first question I asked my myself before I started using PyLabwas why consider Python? What makes it a vialble alternative to other languages available for scientific and engineering computations and simulations? OK, everyone has favorites, and presentlyMATLAB is very popular in the signals and system community. Is there a need to change? Thisis a debate that lies outside the scope of this tutorial, but the ability to use open-source tools thatwork really, really well is very compelling.To answer the first question, why consider Python, I can say:1. The NumPy library2. combined with Matplotlib3. The SciPy library of modules, particularly signal, provides reasonable suppost for signalsand systems work. Additional libraries of modules are also availableBefore NumpyI have been saying a lot about using Python with Numpy as a means to do scientific and engineering analysis, simulation, and visualization. The fact of the matter is, Python is a good languagefor doing many other things outside the computational realm.Numpy plus Scipy are key elements to the attractiveness of using Python, but before gettingtoo carried away with the great scientific computing abiliies of the language, you should learnsome basics of the language. This way you will feel more comfortable at coding and debugging.Before exploring the core language, I will spend time going over the environment and variouschoices.The Environment and ChoicesHow you choose to work with Python is up to you. I do have some strong suggestions. Butfirst I want to review four options in order of most recommended to least recommended. Myrecommendations assume you are just starting out with Python, so I have a bias towards theJupyter notebook.The first thing you want to do is get a version of Python with scientific support included. Whenthis notebook was first created I was using Canopy, but now my preference is to use Anaconda.To learn more about the Jupyter notebook and its furture see Jupyter.Launching the Jupyter NotebookRegardless of the operating system, Windows, Mac OS, or Linux, you want to get a terminalwindow open. It is best if the terminal window is opened at the top level of your user account,so you will be able to navigate to any folder of interest. Note: In Windows 10x I recoimment theuse of powershell. This is done by clicking the file menu from the file manager and then selectingpowershell. It turns out with the notebook interface you can easily navigate to a location interestand then launch an existing notebook or create a new notebook.In [39]: Image('Python Basics files/LaunchNotebook2.png',width '90%')4

Out[39]:From the above you can see that the notebook is all set. Note that the first cell is only relevantif you intend to render your notebook to pdf using the LaTeX backend. This requires that you5

install Pandoc and then an appropriate install of the TeX/LaTeX type setting system. The PandocWeb Site provides details.The second cell issues commands to fine tune the configuration of the notebook. The first linemakes sure the workspace is populated with %pylab, which gives you full access to NumPy andMatplotlib without having to type the module name or namespace. Note: commands that beginwith % are known as IPython magics, which in general allow you to perform OS operations outsidethe default (see option four) Python console. The option inline directs all plots to show up right inthe notebook. If you prefer pop-up plots, enable the second line. The resolution of the embeddedpng plots can be controlled using the third line.The fifth line, if uncommented and run as a magic (put % at start) with change the rendermode from png to pdf. This will then result in a link to plots that opens them in a pdf viewer. ForLaTeX to pdf rendering, this will create crisp vector graphics. I recommend using this only whenyou get ready to export a notebook to pdf. You will have to use Run All from the Cell menu toconvert all graphics to pdf and then switch back later to again have regular inline plots.The two import lines just bring my ssd (Signals and Systems for Dummies module intothe workspace). Note: for this to be sucessful must be in the same folder as the notebookyou are working from. Once you import a module you can navigate to another location in your filesystem. By the way, IPython magics make general OS path manipulation a breeze. Some of thendon’t even require that you forst type %. You do need to know basic Linux/Unix OS commends. Ishow you a few examples below:In [4]: pwd # check your pathOut[4]: n Basics saved'In [5]: # Move up one level%cd ./Users/markwickert/Documents/Courses/TabletIn [3]: cs.synctex.gz*Python Basics.tex*Python Basics.toc*Python Basics files/Python Basics fig1.pdf*Python Basics fig1.png*Python Basics figs.graffle/If you are reading the present document in pdf format, you should consider downloading thenotebook version so you can follow along with interactive calculations and experiments, as youlearn Python Basics.Moving on to the QT console.Launching the IPython QT Console with the Canopy EditorThe second and third options are actually closely related. Both of these options have you workingat a commandline console, much like Octave or Matlab. All the features of IPython are available6

at the QT console. The environment is very very nice. This is how I got started with Python, asthe notebook interface was not fully released.OK, as the second choice for getting started with Python, I recommend the qtconsole in combination with the Canopy. To bring up this environment simply launch the Canopy app (Windows, Mac OS, or Linux), and then click the Editor button:In [13]: Image('Python Basics files/LaunchCanopyEditor.png',width '90%')Out[13]:From the above figure you can see the top window is a code editor with Python syntax highlighting and other features. This is an Enthought (makers of Canopy) product. They plan to someday have a debugger included with the editor.The lower window is the IPython console. By enabling the the Keep Directory Synced to Editoroption you can freely move around to import code modules from various locations and alwayshave the path in command console where you want it. By default when Canopy opens the editorit starts the qtconsole woth pylab. It also by default has all plots going to pop-up windows.The inline plots mode for the qtconsole is available, but not that great compared to the IPythonnotebook.7

Launching the IPython QT Console From the TerminalIf you prefer to use your own editor (many good choices out there) or if you are not using Canopy,you can always start the qtconsole from the terminal. For quick calculations, where I don’t care tohave documentation created, this is my favorite interface. As I said earlier, I think starting withthe notebook is best, and it documents your work, which can be very useful for assignments. Withthe qtconsole documentation is on your own. I wrote the Dummies book using this interface.As with the notebook, you want to open the terminal already pointing to the folder whereyour Python files of interest reside (yes you can always navigate using cd later). The next step(Windows, Mac OS, Linux) is shown below:In [15]: Image('Python Basics files/Launchqtconsole.png',width '90%')Out[15]:Note: The option --pylab is used to start up pylab as was done in earlier environments. Everything else you see in the above figure is very similar to the Canopy editor with qtconsole.8

Launching the Native Python Console From the TerminalIn the beginning there was and there still is, the basic Python intaractive console. For a Pythonbeginner, wanting to learn how to do scientific/engineering calculatins in Python, this is the leastdesireable way to go. Chances are you will have occasion to use this environment soon enough,so no rush right now. If you decide to play with an embedded Linux device Rasberry Pi or BeagleBone Black, and use Python to program it, this is where you will find yourself. Take this as goodnews, as Python has many uses.To launch the Python console start a terminal (command prompt) session as before and simplytype python:In [14]: Image('Python Basics files/LaunchPythonTerm.png',width '90%')Out[14]:Ending Your SessionNot mentioned up to this point, is how you end a Python session. In the notebook you use the File menu and select Close and Halt On both the qtconsole and the traditional Python console you type exit()Note: The () are required since exit() is a function that takes no arguments.Now its finally time to start discussing some language details.Data Types and Simple CalculationsHello WorldThe classic first program in any language is Hello World. In Python this is accomplished quitesimply via:In [85]: print('Hello Python World!')9

Hello Python World!As I roll through basics be aware that comments begin with # and multiline comments looklike"""A multiline commentThe second lineThe third line"""if I need access to a particular Python module I need to import it first:# Here I will import the SciPy signal processing module and# give it a short name of signalimport scipy.signal as signalMore of discussion of import and modules will occur later. Until I start talking about NumPyI will keep all he topics limited to what you can do with native Python. Note: If you need tocontiune a line you can use \ (backslash). You cannot break a string this way. You can also breaklines at commas.float, complex, long, int, str, and booleanThe Native Python data types are actually rather few. When Numpy is brought in this changes,but for now that is not the case.Float In signals and systems work the float type is actually is actually a double as found in theC language. This means it consumes 64 bits (8 bytes) of memory. A float is created by simplyincluding a decimal point in the number.In [71]: a 1.2b 4.603a*bOut[71]: 5.523599999999999To be sure you can use the built-in function type(). To compare several calculation I will stringtogether several calls to type() with parenthesis and commas in between. This way I can displaythe rults all on one line. Note: I have actually created a compount type known as a tuple. Moreon tuples later.In [87]: (type(a), type(2), type(2*a)) # note the upcasting to floatOut[87]: (float, int, float)In [88]: type((type(a), type(2), type(2*a))) # still have to explain tuplesOut[88]: tuple10

The native operations available with float types are given in the following table. The tableorder is from lowest to highest precedence.In [20]: SVG('Python Basics files/Operations table.svg')Out[20]:Native Type Standard Arithmetic OperatorsNameOperatorQuick Example 3 4.57.5 10 - 7.32.7 3.4 * 39.1132.94Addition Subtraction-Multiply*Division/Note one number must bea float in Python 2.7 45.2/89.10.5072951739618407Integer Division// In Python 3.3 or/In Python 2.7 (see note) 67//8 or 67/88Remainder%Note with numpy youtypically usemod(a,b) 13 % 85Exponentiation** 3**86561Note:In Python 2.7 Python 3.3 division behavior is available if you makeyour first import (be careful with this): from future import divisionA frustration with Python 2.7 (what I am currently using in this IPython notebook), is thatwhen do perform simple division such asx 6/7thinking you will form a float, you instead get and integer. In the example above you get 0. InPython 3.3 this is resolved. I am making a big deal about this because over and over again I gettripped up.So what can you do? In Python 2.7 I find it best to just remember to put a decimal point on oneof the two numbers when working with ratios of integers in math calculations. A hard conversionto float is possible using the native function float(), e.g.,x 6/7.# orx 6/float(7)The best option now is to use Python 3.6 or alternatively import the 3.x division rule intoPython 2.7 as follows:11

In [98]: from future import division(6/7,6//7) # display two results, again using a tupleOut[98]: (0.8571428571428571, 0)Note: It is strongly recommended that this import be placed before any other imports. Also,with this division change, when you really want integer division you need to use //. More on theint type coming up.Complex Another standard type to Python is complex. For signals and systems work, complexplays a significant role. The constant 1j gives you access to 1, and allows you to readily formcomplex quantities. In the following example I will again create a tuple just for the convenienceof displaying multiple results without using a formatted print statement.In [19]: z1 complex(1.,3) # z complex(x,y) builds a complex typez2 5. - 20j(z1 z2, z1 - z2, z1*z2, z1/z2)Out[19]: ((6-17j), (-4 23j), (65-5j), (-0.12941176470588237 0.08235294117647059j))The convenience of built-in complex arithmeic is very nice. I need to mention however, thatgetting access to functions beyond the operators listed in the table above, requires the import ofspecific code modules. The math and cmath bring in additional functions for float or real numbersand complex numbers respectively. Don’t get too excited about jumping in to use these modules.With NumPy, which will be talked about later, the use of math and cmath is taken care of for you.AN with NumPy you will have full vector/matrix support. I just mention it here so you know itdoes exist, and if for some strange case you don’t want to use NumPy, this is what you will havework with.Int and Long For integer math, indices, and loop counters, Python has the types int and long.The int type is a signed integer similar to int in the C language. The size of int depends uponthe machine you are running on. If you import the sys module you can find out more informationabout int for your machine:In [93]: import syssys.maxintOut[93]: 9223372036854775807On a 64-bit OS the maximum value should be like 264 1 1, accounting for the fact that onebit is needed for the sign and since zero is represented you have to stop one value short of 263 .The native math capability of Python goes one step further via the long type. The long typeoffers unlimited size! Furthermore if you are working with an int type and perform an operation that exceeds the maximum size, it will converted to a long integer for you. Loop countershowever, are bound to the maximum size on int. There are work arounds for this too.In [94]: x 34(type(x),x) # display two results, again using a tuple12

Out[94]: (int, 34)In [95]: y x**32(type(y),y) # display two results, again using a tupleOut[95]: (long, L)In [99]: 1-yOut[99]: 5LNotice in the above examples that long integers are displayed with L appended to the end.Other BasesIn computer engineering you often need to work with other bases.Bitwise Operations Along with the display of integers in other formats, Python also supports the bitwise operations shown in the following table.In [22]: SVG('Python Basics files/Bitwise table.svg')Out[22]:Native Bitwise Arithmetic OperatorsNameOperatorBitwise not Shift left Shift right Exclusive OR(XOR) AND&OR Quick Example 0x001 0x100254 sincehex( 0x001) -0x2 bin(0b0001 2)'0b100' or4 bin(0b11001 3)'0b11' or3bin(0b1010 0b1111)'0b101' or5 bin(0b101100 & 0xf)'0b1100' or12 bin(0b1000 0b0001)'0b1001' or9Note:If you search the Internet you will find little helper functions toallow you to represent hex values with proper sign extension.13

String String creation and manipulation in Python is a breeze. In signals and systems workstring manipulation often shows up when working with formatted printing, on the screen or in atext file, and in labels for plots.The ability to mix fixed text with formatted numbers, on the fly, is very handy when you haveto tabulate analysis and simulation results. Formatted print strings will discussed when I discussthe print() function. Presently the basic of type str are discussed.Formally a string in Python is a sequence of immutable characters. Immutable means the valuesof the string cannot be changed. You can easily create a new string from an existing string, andthis is where you can introduce changes you may desire.A string can be indicated using: (1) single quotes (2) double quotes, or (3) triple quotes to createa string block.xa 'Bat'xb "Bat"xc \"""Many bats flyingthrough the air."""In [124]: xa 'Bat'xb "Bat"xc \"""Many bats flyingthrough the air."""# Use a tuple to display some results(xa,type(xa),xb,xc)Out[124]: ('Bat', str, 'Bat', '\nMany bats flying \nthrough the air.\n')Note: The multi-line string has embedded line feed, \n, characters.Single and double quotes are interchangeable and are useful when you want to preserve quotesthat belong in a string, e.g.,In [108]: xd "It's a beautiful day"xdOut[108]: "It's a beautiful day"Don’t be afraid to experiment!String can be concatenated or added quite easily:In [114]: 'Hello,' ' ' 'what is your name?'Out[114]: 'Hello, what is your name?'14

The number of characters in a string can be found using the len() function, while individualcharacters can be accessed using brackets, e.g., xd[3].Indexing can be used to obtain substrings. The indices are integers which run from 0 tolen()-1. To generate substrings use brackets, i.e.,In [121]: len(xd)Out[121]: 20The table below sumarizes basic string manipulation, including the fun topic of slicing. Slicingreturns with native Python lists, tuples, and NumPy ndarrays.In [24]: SVG('Python Basics files/StringOperations.svg')Out[24]:15

Native string IndexingSlicing:Many formspossibleOperationQuick Examplexa xb ‘Hello’ ‘ ‘ ‘World’to concatenate‘Hello World’stringsx*n orn*xto replicate astring ntimesx[n]x[-1]the end valuex[-2]the secondfrom the endx[n:m]the substringfrom nto m-1x[:m]the substringfrom 0to m-1x[n:]the substringfrom nto theendx[n:-1]the substringfrom ntoend-1x[n:-2]the substringfrom ntoend-2x[n:m:k] ‘Bat’ * 3‘BatBatBat’ x ‘Bat’ x[1]‘a’ x[-1]t x ‘Bright colors’ x[1:6]‘right’ x[7:]‘colors’ x[:-1]‘Bright color’ x[::2]‘Bih oos’In the above the third argument is theoptional stride(the default, if notgiven is 1) factor which controls thestep size as you run from 0 to theend in this case, since only::isgiven.Note:Indexing and slicing will work the same way when wiring withPython listsand tuples, and the Numpyndarray.There are many functions for searching and modifying strings. Too many to cover here. If youfeel the need, do some searching on your own. As a specific example, consider breaking a stringdown into substrings and then put back together in a differnt form. Below I use find() to dosome simple string parsing to assit in the tear-apart:In [120]: xd[0:5] xd[xd.find('beau'):xd.find('day')-1]Out[120]: "It's beautiful"16

Boolean The boolean type has it place in making logical decisions in program flow. In Pythonthe boolean type holds either True (1) or False (0). You will see booleans in action when I discussprogram flow. Logical operation as used in program flow control return booleans. A few simpleexamples follow:In [161]: b1 Trueb1 1Out[161]: FalseIn [162]: 34 0 and 4 3Out[162]: FalseIn [163]: 34 0 or 4 3Out[163]: TrueData StructuresPython’s native data structures of interest here are lists, tuples, and briefly dictionaries. Allthree of these data structures are sequences that can be thought of as containers for Python objects.The most import object you will be using is the ndarray, which I have made mention of manytimes. Although note mentioned in the section on string, they are also sequences of characters.ListsSimply put, a list is a mutable (changable) sequence of objects. A list can be created using brackets:In [146]: l1 [1,'abc',23.4]l1Out[146]: [1, 'abc', 23.4]Indexing and slicing of lists works the same as with strings. In fact a list can hold strings asyou see in the above example.When I introduce for loops a little bit later, you will encounter a list object containing integers.With regard to for loops, the native function range(), is frequently used to create a list of integers.Consider the examples below:n1 range(start,stop,step) # [start,start step,start 2*step,.]n2 range(20) # [0,1,2,.,19]If start is omitted the sequence starts at 0. If step is omitted the step size is 1. Note step maybe negative.The fact that lists are mutable means I can writen1 range(10)n1[4] 20 # replace the 5th element with 20, not a problem17

In [169]: n1 range(10)n1Out[169]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]In [170]: n1[4] 20n1Out[170]: [0, 1, 2, 3, 20, 5, 6, 7, 8, 9]In [136]: (type(n1),len(n1))Out[136]: (list, 10)List can contain lists, and so on. Below I create n2 as a list of two lists made from subsequencesof the original n1.In [137]: n2 [n1[:5],n1[5:]]n2Out[137]: [[0, 1, 2, 3, 20], [5, 6, 7, 8, 9]]Indexing and slicing into n2 now requires two indices:In [144]: n2[1][:3]Out[144]: [5, 6, 7]There are methods (functions) associated with list objects. In engineering/scientific applicationsof Python you need to be aware of lists, but explicit use of lists beyond range() (or the memoryconserving xrange()) is minimal, as NumPy’s ndarray is more powerful. As a simple exampleconsider sort() which places the list elements in ascending order:In [171]: n3 sort(n1) # Note n1.sort() sorts in-placen3Out[171]: array([ 0,1,2,3,5,6,7,8,9, 20])List Comprehensions Indexing through lists and performing calculations is a frequent task,at least without NumPy. Python allows you to combine looping and list manipulation into list [function of index for index in range(n1,n2 1)]#or to list the values in the terminal immediately[function of index for index in range(n1,n2 1)]Below is a simple example that returns a list of numbers corresponding to 3 4n n2 for0 n 10.In [173]: [3 4*n n**2 for n in range(0,11)]Out[173]: [3, 8, 15, 24, 35, 48, 63, 80, 99, 120, 143]When you use list comprehensions you can write very terse Python code. I encourage you toexplore list comprehensions as you feel more comfortable with the language. With NumPy the listcomprehension still provides a convenient way to fill a list or array with values of interest, butagain NumPy has its own ways too, that most likely are even faster.18

TuplesA tuple is like a list, but it is immutable (not changable). Your first reaction to this might be ’whatgood is it if I can’t change it’. It turns out that the immuatabilty aspect is perfect for the needs ofengineering/scientific computing.Creating a tuple can be done using parenthesis much like you do with lists. One significant difference is that a single element tuple requires a comma so as not to be confused with theordinary use of parenthesis.In [147]: t1 (1,2,23.5,'abcd')t1Out[147]: (1, 2, 23.5, 'abcd')In [159]: t2 (27)t2 # This is not a one element tupleOut[159]: 27In [160]: t3 (34.5,) # the comma does it, its a one element tuplet3Out[160]: (34.5,)In [156]: type(t3)Out[156]: tupleTrying to change a value of a tuple element fails, as you can see from the following:In [151]: t1[1] --------------------------TypeErrorTraceback (most recent call last) ipython-input-151-4a896955a572 in module ()---- 1 t1[1] 56TypeError: 'tuple' object does not support item assignmentA typical use of the tuple is as a return from a function call. Each element of the tuple canbe an object such as a list or with NumPy an ndarray. You can then unpack the tuple into itsconstituent objects, say a frequency array and a frequency response array. Further analysis follows.Suppose you have a function that returns a tuple of two lists. List 1, denoted l1, containingnumbers and list 2, denoted l2, containing characters, you can unpack the tuple into two lists asfollows:19

In [152]: # First set up the scenario by artificially creating# a tuple containing two listsl composite ([0,1,2,3,4],['a','b','c','d','e'])# Break the tuple apartl1,l2 l compositeIn [153]: l1Out[153]: [0, 1, 2, 3, 4]In [154]: l2Out[154]: ['a', 'b', 'c', 'd', 'e']Tuples have functions, such as len(),DictionariesA dictionary is a mutable (changable) sequence of values that is addressable using a name/key. Thekey needs to be unique, but the value does not. Dictionaries like lists are mutable.The motivation for introducing dictionaries at this time is because some of the numerical algorithms in SciPy return dictionaries. If you should need to use one of these algorithms, then youwill need to know something about dictionaries.To create a dictionary using braces to create {key : value} pairs.In [180]: weekdays {'monday' : 1, 'tuesday' : 2, 'wednesday' : 3,'thursday' : 4, 'friday' : 5}type(weekdays)Out[180]: dictYou can now access the dictionary elements using the keys:In [177]: weekdays['wednesday']Out[177]: 3Dictionaries have a collection of associated functions. For example, you can list the keys usingthe keys() method:In [179]: weekdays.keys()Out[179]: ['tuesday', 'thursday', 'friday', 'wednesday', 'monday']If you have a dictionary but don’t know whats inside, you can list() it as tuples. The orderof the list is the hash ordering, which is an internal order scheme for fast retrieval.In [181]: weekdays.items()Out[181]: [('tuesday', 2),('thursday', 4),('friday', 5),('wednesday', 3),('monday', 1)]20

VariablesYou have already seen variables in action, but there are some fine points you need to know aboutthem. Variable names can contain characters, numbers, and underscores. Variables cannot beginwith a number.Since everything in Python is an object, all objects have an address. If you declare a structurevariable (say a list) it is given an address. If you later set the list variable name equal to the firstvariable you will not be creating a new object. Rather you create a new reference to the sameobject. Python does have a copy method for these instances when you really do want a copy.In [184]: a1 [0,23.4]a2 a1(a1,a2)Out[184]: ([0, 23.4], [0, 23.4])In [185]: a2[0] 56.8(a1,a2)Out[185]: ([56.8, 23.4], [56.8, 23.4])Notice in the a

Python Basics.ipynb* Python Basics.toc* Python Basics.log* Python Basics_files/ Python Basics.out* Python_Basics_fig1.pdf* Python Basics.pdf* Python_Basics_fig1.png* Python Basics.synctex.gz* Python_Basics_figs.graffle/ If you are reading the present document in pdf format, you should consider downloading the notebook version so you can follow .

Related Documents:

Python Programming for the Absolute Beginner Second Edition. CONTENTS CHAPTER 1 GETTING STARTED: THE GAME OVER PROGRAM 1 Examining the Game Over Program 2 Introducing Python 3 Python Is Easy to Use 3 Python Is Powerful 3 Python Is Object Oriented 4 Python Is a "Glue" Language 4 Python Runs Everywhere 4 Python Has a Strong Community 4 Python Is Free and Open Source 5 Setting Up Python on .

Python 2 versus Python 3 - the great debate Installing Python Setting up the Python interpreter About virtualenv Your first virtual environment Your friend, the console How you can run a Python program Running Python scripts Running the Python interactive shell Running Python as a service Running Python as a GUI application How is Python code .

Python is readable 5 Python is complete—"batteries included" 6 Python is cross-platform 6 Python is free 6 1.3 What Python doesn't do as well 7 Python is not the fastest language 7 Python doesn't have the most libraries 8 Python doesn't check variable types at compile time 8 1.4 Why learn Python 3? 8 1.5 Summary 9

site "Python 2.x is legacy, Python 3.x is the present and future of the language". In addition, "Python 3 eliminates many quirks that can unnecessarily trip up beginning programmers". However, note that Python 2 is currently still rather widely used. Python 2 and 3 are about 90% similar. Hence if you learn Python 3, you will likely

There are currently two versions of Python in use; Python 2 and Python 3. Python 3 is not backward compatible with Python 2. A lot of the imported modules were only available in Python 2 for quite some time, leading to a slow adoption of Python 3. However, this not really an issue anymore. Support for Python 2 will end in 2020.

A Python Book A Python Book: Beginning Python, Advanced Python, and Python Exercises Author: Dave Kuhlman Contact:

Mike Driscoll has been programming with Python for more than a decade. He has been writing about Python on his blog, The Mouse vs. The Python, for many years. Mike is the author of several Python books including Python 101, Python Interviews, and ReportLab: PDF Processing with Python. You can find Mike on Twitter or GitHub via his handle .

Tulang-tulang pembentuk rangka tubuh . 12 3. Tulang-tulang di regio manus tampak . Anatomi hewan ini yang dipelajari adalah anatomi tubuh hewan piara. Pelaksanaan perkuliahan dan praktikum anatomi hewan dilakukan setiap minggu sesuai jadwal dengan beban 3 sks (1-2) pada mahasiswa semester 1. Pelaksanaan meliputi tutorial, pretest, praktikum di laboratorium, pembuatan laporan, dan ujian .