A Python Book

Total Page:16

File Type:pdf, Size:1020Kb

A Python Book A Python Book A Python Book: Beginning Python, Advanced Python, and Python Exercises Author: Dave Kuhlman Contact: [email protected] Address: http://www.davekuhlman.org Page 1 A Python Book Revision 1.3a Date December 15, 2013 Copyright Copyright (c) 2009 Dave Kuhlman. All Rights Reserved. This document is subject to the provisions of the Open Source MIT License http://www.opensource.org/licenses/mit-license.php. Abstract This document is a self-learning document for a course in Python programming. This course contains (1) a part for beginners, (2) a discussion of several advanced topics that are of interest to Python programmers, and (3) a Python workbook with lots of exercises. Page 2 A Python Book Contents 1 Part 1 -- Beginning Python...........................................................................................10 1.1 Introductions Etc...................................................................................................10 1.1.1 Resources.......................................................................................................11 1.1.2 A general description of Python....................................................................12 1.1.3 Interactive Python..........................................................................................15 1.2 Lexical matters......................................................................................................15 1.2.1 Lines..............................................................................................................15 1.2.2 Comments......................................................................................................16 1.2.3 Names and tokens..........................................................................................16 1.2.4 Blocks and indentation..................................................................................16 1.2.5 Doc strings.....................................................................................................17 1.2.6 Program structure..........................................................................................17 1.2.7 Operators.......................................................................................................18 1.2.8 Also see.........................................................................................................19 1.2.9 Code evaluation.............................................................................................19 1.3 Statements and inspection -- preliminaries...........................................................20 1.4 Built-in data-types.................................................................................................21 1.4.1 Numeric types................................................................................................21 1.4.2 Tuples and lists..............................................................................................21 1.4.3 Strings............................................................................................................24 1.4.3.1 The new string.format method...............................................................26 1.4.3.2 Unicode strings......................................................................................27 1.4.4 Dictionaries....................................................................................................29 1.4.5 Files...............................................................................................................32 1.4.6 Other built-in types........................................................................................35 1.4.6.1 The None value/type..............................................................................35 1.4.6.2 Boolean values.......................................................................................36 1.4.6.3 Sets and frozensets.................................................................................36 1.5 Functions and Classes -- A Preview......................................................................36 1.6 Statements.............................................................................................................37 1.6.1 Assignment statement....................................................................................37 1.6.2 import statement............................................................................................39 1.6.3 print statement...............................................................................................41 1.6.4 if: elif: else: statement...................................................................................43 1.6.5 for: statement.................................................................................................44 1.6.6 while: statement.............................................................................................48 Page 3 A Python Book 1.6.7 continue and break statements.......................................................................48 1.6.8 try: except: statement.....................................................................................49 1.6.9 raise statement...............................................................................................51 1.6.10 with: statement.............................................................................................52 1.6.10.1 Writing a context manager...................................................................52 1.6.10.2 Using the with: statement....................................................................53 1.6.11 del................................................................................................................54 1.6.12 case statement..............................................................................................55 1.7 Functions, Modules, Packages, and Debugging....................................................55 1.7.1 Functions.......................................................................................................55 1.7.1.1 The def statement...................................................................................55 1.7.1.2 Returning values....................................................................................55 1.7.1.3 Parameters..............................................................................................56 1.7.1.4 Arguments..............................................................................................56 1.7.1.5 Local variables.......................................................................................57 1.7.1.6 Other things to know about functions....................................................57 1.7.1.7 Global variables and the global statement.............................................58 1.7.1.8 Doc strings for functions.......................................................................60 1.7.1.9 Decorators for functions........................................................................60 1.7.2 lambda...........................................................................................................61 1.7.3 Iterators and generators.................................................................................62 1.7.4 Modules.........................................................................................................67 1.7.4.1 Doc strings for modules.........................................................................68 1.7.5 Packages........................................................................................................68 1.8 Classes...................................................................................................................69 1.8.1 A simple class................................................................................................69 1.8.2 Defining methods..........................................................................................70 1.8.3 The constructor..............................................................................................70 1.8.4 Member variables..........................................................................................70 1.8.5 Calling methods.............................................................................................71 1.8.6 Adding inheritance........................................................................................71 1.8.7 Class variables...............................................................................................72 1.8.8 Class methods and static methods.................................................................72 1.8.9 Properties.......................................................................................................74 1.8.10 Interfaces.....................................................................................................75 1.8.11 New-style classes.........................................................................................75 1.8.12 Doc strings for classes.................................................................................77 1.8.13 Private members..........................................................................................77 1.9 Special Tasks.........................................................................................................77 1.9.1 Debugging tools.............................................................................................77 Page 4 A Python Book 1.9.2 File input and output......................................................................................78
Recommended publications
  • Command-Line Sound Editing Wednesday, December 7, 2016
    21m.380 Music and Technology Recording Techniques & Audio Production Workshop: Command-line sound editing Wednesday, December 7, 2016 1 Student presentation (pa1) • 2 Subject evaluation 3 Group picture 4 Why edit sound on the command line? Figure 1. Graphical representation of sound • We are used to editing sound graphically. • But for many operations, we do not actually need to see the waveform! 4.1 Potential applications • • • • • • • • • • • • • • • • 1 of 11 21m.380 · Workshop: Command-line sound editing · Wed, 12/7/2016 4.2 Advantages • No visual belief system (what you hear is what you hear) • Faster (no need to load guis or waveforms) • Efficient batch-processing (applying editing sequence to multiple files) • Self-documenting (simply save an editing sequence to a script) • Imaginative (might give you different ideas of what’s possible) • Way cooler (let’s face it) © 4.3 Software packages On Debian-based gnu/Linux systems (e.g., Ubuntu), install any of the below packages via apt, e.g., sudo apt-get install mplayer. Program .deb package Function mplayer mplayer Play any media file Table 1. Command-line programs for sndfile-info sndfile-programs playing, converting, and editing me- Metadata retrieval dia files sndfile-convert sndfile-programs Bit depth conversion sndfile-resample samplerate-programs Resampling lame lame Mp3 encoder flac flac Flac encoder oggenc vorbis-tools Ogg Vorbis encoder ffmpeg ffmpeg Media conversion tool mencoder mencoder Media conversion tool sox sox Sound editor ecasound ecasound Sound editor 4.4 Real-world
    [Show full text]
  • The Use and Application of Open Source Integrated Library System in Academic Libraries in Nigeria: Koha Example
    University of Nebraska - Lincoln DigitalCommons@University of Nebraska - Lincoln Library Philosophy and Practice (e-journal) Libraries at University of Nebraska-Lincoln 2015 The seU and Application of Open Source Integrated Library System in Academic Libraries in Nigeria: Koha Example Emeka C. Uzomba Mr. Federal University,Oye-Ekiti, Ekiti State, [email protected] OLUWATOFUNMI JESUDUNNI OYEBOLA Mrs. Federal University Oye-Ekiti, Nigeria, [email protected] ANTHONY CHUKWUMA IZUCHUKWU Mr. University of Nigeria, Nsukka, [email protected] Follow this and additional works at: http://digitalcommons.unl.edu/libphilprac Part of the Educational Assessment, Evaluation, and Research Commons, and the Library and Information Science Commons Uzomba, Emeka C. Mr.; OYEBOLA, OLUWATOFUNMI JESUDUNNI Mrs.; and IZUCHUKWU, ANTHONY CHUKWUMA Mr., "The sU e and Application of Open Source Integrated Library System in Academic Libraries in Nigeria: Koha Example" (2015). Library Philosophy and Practice (e-journal). 1250. http://digitalcommons.unl.edu/libphilprac/1250 THE USE AND APPLICATION OF OPEN SOURCE INTEGRATED LIBRARY SYSTEM IN ACADEMIC LIBRARIES IN NIGERIA: KOHA EXAMPLE BY EMEKA CHRISTIAN UZOMBA Federal University Oye-Ekiti (Corresponding Author) Phone: +2348036996747 P.M.B.2273 Oye-Ekiti, Ekiti State, Nigeria. [email protected] , [email protected] , OLUWATOFUNMI JESUDUNNI OYEBOLA Federal University Oye-Ekiti (Co-Author) Phone: +2348030617819 P.M.B.2273 Oye-Ekiti, Ekiti State, Nigeria. [email protected] , [email protected] ANTHONY CHUKWUMA IZUCHUKWU Department of Library and Information Science, University of Nigeria, Nsukka (Co-Author) Phone: +2348067699821 [email protected] ABSTRACT This study examined the use of open source integrated library system in academic libraries in Nigeria, with the aim of highlighting the capabilities and potentials of open source software (Koha) and its practical importance to academic libraries across the globe.
    [Show full text]
  • Sound-HOWTO.Pdf
    The Linux Sound HOWTO Jeff Tranter [email protected] v1.22, 16 July 2001 Revision History Revision 1.22 2001−07−16 Revised by: jjt Relicensed under the GFDL. Revision 1.21 2001−05−11 Revised by: jjt This document describes sound support for Linux. It lists the supported sound hardware, describes how to configure the kernel drivers, and answers frequently asked questions. The intent is to bring new users up to speed more quickly and reduce the amount of traffic in the Usenet news groups and mailing lists. The Linux Sound HOWTO Table of Contents 1. Introduction.....................................................................................................................................................1 1.1. Acknowledgments.............................................................................................................................1 1.2. New versions of this document.........................................................................................................1 1.3. Feedback...........................................................................................................................................2 1.4. Distribution Policy............................................................................................................................2 2. Sound Card Technology.................................................................................................................................3 3. Supported Hardware......................................................................................................................................4
    [Show full text]
  • Open Source Library Management System Software: a Review
    World Academy of Science, Engineering and Technology International Journal of Computer and Systems Engineering Vol:5, No:5, 2011 Open Source Library Management System Software: A Review Sangsuree Vasupongayya, Kittisak Keawneam, Kittipong Sengloilaun, Patt Emmawat materials), cataloging (i.e., classifying and indexing of Abstract—Library management systems are commonly used in materials), circulation (i.e., lending and receiving of materials) all educational related institutes. Many commercial products are and serials management (i.e., managing magazine and available. However, many institutions may not be able to afford the newspaper information. The second component is an cost of using commercial products. Therefore, an alternative solution interlibrary load management system. Because a library may in such situations would be open source software. This paper is focusing on reviewing open source library management system not have a hold of all materials required, an interlibrary loan is packages currently available. The review will focus on the abilities to a way for its patron to request such materials from other perform four basic components which are traditional services, libraries. The last component is a system to manage electronic interlibrary load management, managing electronic materials and materials and digital media. basic common management system such as security, alert system and In addition to the above three main components, a library statistical reports. In addition, environment, basic requirement and management system software package must contain a supporting aspects of each open source package are also mentioned. commonly shared components such as a user account management feature, a security component, an alert system Keywords— open source, library management, review.
    [Show full text]
  • EMEP/MSC-W Model Unofficial User's Guide
    EMEP/MSC-W Model Unofficial User’s Guide Release rv4_36 https://github.com/metno/emep-ctm Sep 09, 2021 Contents: 1 Welcome to EMEP 1 1.1 Licenses and Caveats...........................................1 1.2 Computer Information..........................................2 1.3 Getting Started..............................................2 1.4 Model code................................................3 2 Input files 5 2.1 NetCDF files...............................................7 2.2 ASCII files................................................ 12 3 Output files 17 3.1 Output parameters NetCDF files..................................... 18 3.2 Emission outputs............................................. 20 3.3 Add your own fields........................................... 20 3.4 ASCII outputs: sites and sondes..................................... 21 4 Setting the input parameters 23 4.1 config_emep.nml .......................................... 23 4.2 Base run................................................. 24 4.3 Source Receptor (SR) Runs....................................... 25 4.4 Separate hourly outputs......................................... 26 4.5 Using and combining gridded emissions................................. 26 4.6 Nesting.................................................. 27 4.7 config: Europe or Global?........................................ 31 4.8 New emission format........................................... 32 4.9 Masks................................................... 34 4.10 Other less used options.........................................
    [Show full text]
  • RFP Response to Region 10 ESC
    An NEC Solution for Region 10 ESC Building and School Security Products and Services RFP #EQ-111519-04 January 17, 2020 Submitted By: Submitted To: Lainey Gordon Ms. Sue Hayes Vertical Practice – State and Local Chief Financial Officer Government Region 10 ESC Enterprise Technology Services (ETS) 400 East Spring Valley Rd. NEC Corporation of America Richardson, TX 75081 Cell: 469-315-3258 Office: 214-262-3711 Email: [email protected] www.necam.com 1 DISCLAIMER NEC Corporation of America (“NEC”) appreciates the opportunity to provide our response to Education Service Center, Region 10 (“Region 10 ESC”) for Building and School Security Products and Services. While NEC realizes that, under certain circumstances, the information contained within our response may be subject to disclosure, NEC respectfully requests that all customer contact information and sales numbers provided herein be considered proprietary and confidential, and as such, not be released for public review. Please notify Lainey Gordon at 214-262-3711 promptly upon your organization’s intent to do otherwise. NEC requests the opportunity to negotiate the final terms and conditions of sale should NEC be selected as a vendor for this engagement. NEC Corporation of America 3929 W John Carpenter Freeway Irving, TX 75063 http://www.necam.com Copyright 2020 NEC is a registered trademark of NEC Corporation of America, Inc. 2 Table of Contents EXECUTIVE SUMMARY ...................................................................................................................................
    [Show full text]
  • Sox Examples
    Signal Analysis Young Won Lim 2/17/18 Copyright (c) 2016 – 2018 Young W. Lim. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included in the section entitled "GNU Free Documentation License". Please send corrections (or suggestions) to [email protected]. This document was produced by using LibreOffice. Young Won Lim 2/17/18 Based on Signal Processing with Free Software : Practical Experiments F. Auger Audio Signal Young Won Lim Analysis (1A) 3 2/17/18 Sox Examples Audio Signal Young Won Lim Analysis (1A) 4 2/17/18 soxi soxi s1.mp3 soxi s1.mp3 > s1_info.txt Input File Channels Sample Rate Precision Duration File Siz Bit Rate Sample Encoding Audio Signal Young Won Lim Analysis (1A) 5 2/17/18 Generating signals using sox sox -n s1.mp3 synth 3.5 sine 440 sox -n s2.wav synth 90000s sine 660:1000 sox -n s3.mp3 synth 1:20 triangle 440 sox -n s4.mp3 synth 1:20 trapezium 440 sox -V4 -n s5.mp3 synth 6 square 440 0 0 40 sox -n s6.mp3 synth 5 noise Audio Signal Young Won Lim Analysis (1A) 6 2/17/18 stat Sox s1.mp3 -n stat Sox s1.mp3 -n stat > s1_info_stat.txt Samples read Length (seconds) Scaled by Maximum amplitude Minimum amplitude Midline amplitude Mean norm Mean amplitude RMS amplitude Maximum delta Minimum delta Mean delta RMS delta Rough frequency Volume adjustment Audio Signal Young Won
    [Show full text]
  • The Community Is the Infrastructure: a Short Discussion of the Petsc Community
    The Community is the Infrastructure: A Short Discussion of the PETSc Community Mark Adams1, Jed Brown2, Satish Balay3, Victor Eijkhout4, Jacob Faibussowitsch5, Fande Kong6, Matthew Knepley7, Scott Kruger8, Oana Marin3, Richard Tran Mills3, Todd Munson3, Patrick Sanan9, Barry F. Smith10, Hong Zhang11, Hong Zhang3, and Junchao Zhang3 1Lawrence Berkeley National Laboratory 2University of Colorado at Boulder 3Argonne National Laboratory 4The University of Texas at Austin 5University of Illinois at Urbana-Champaign 6Idaho National Laboratory 7University of New York at Buffalo 8Tech-X Corporation 9ETH Zurich 10Argonne Associate, Argonne National Laboratory 11Illinois Institute of Technology July 5, 2021 Abstract Hard and soft infrastructure work in tandem to accomplish a particular enterprise. Soft infras- tructure { the formal and informal culture, institutions, standards, practices, and procedures that support an enterprise { is often more important to human endeavors than hard infrastructure. For example, a highway system's hard infrastructure (e.g., the roads) could not satisfy its enterprise { effective transportation | without the corresponding soft infrastructure of regulations, policing, driver habits, maintenance crews, and so forth. The relative cost and importance of the different aspects of infrastructure evolves, particularly during the development stages, from planning, to construction, to commissioning, operation, maintenance, and upgrading. The design, development, support, and dissemination of computer software is an archetypal example of soft infrastructure, regularly being the tail that wags the dog of computer hardware (prototypical hard infrastructure). Quantifying soft infrastructure is more difficult than hard in- frastructure. Thus, it is often ignored or under-emphasized when analyzing or proposing changes to human-developed systems. In particular, government understanding and funding of scientific soft infrastructure lags well behind that of hard infrastructure (for example, experimental devices such as accelerators).
    [Show full text]
  • Name Synopsis Description Options
    SoXI(1) Sound eXchange SoXI(1) NAME SoXI − Sound eXchange Information, display sound file metadata SYNOPSIS soxi [−V[level]] [−T][−t|−r|−c|−s|−d|−D|−b|−B|−p|−e|−a] infile1 ... DESCRIPTION Displays information from the header of a givenaudio file or files. Supported audio file types are listed and described in soxformat(7). Note however, that soxi is intended for use only with audio files with a self- describing header. By default, as much information as is available is shown. An option may be giventoselect just a single piece of information (perhaps for use in a script or batch-file). OPTIONS −V Set verbosity.See sox(1) for details. −T Used with multiple files; changes the behaviour of −s, −d and −D to display the total across all givenfiles. Note that when used with −s with files with different sampling rates, this is of ques- tionable value. −t Showdetected file-type. −r Showsample-rate. −c Shownumber of channels. −s Shownumber of samples (0 if unavailable). −d Showduration in hours, minutes and seconds (0 if unavailable). Equivalent to number of samples divided by the sample-rate. −D Showduration in seconds (0 if unavailable). −b Shownumber of bits per sample (0 if not applicable). −B Showthe bitrate averaged overthe whole file (0 if unavailable). −p Showestimated sample precision in bits. −e Showthe name of the audio encoding. −a Showfile comments (annotations) if available. BUGS Please report anybugs found in this version of SoX to the mailing list ([email protected]). SEE ALSO sox(1), soxformat(7), libsox(3) The SoX web site at http://sox.sourceforge.net LICENSE Copyright 2008−2013 by Chris Bagwell and SoX Contributors.
    [Show full text]
  • Chapter 4 Editors and Debugging Systems
    Chapter 4 Editors and Debugging Systems This Chapter gives you… Text editors Interactive Debugging Systems 4.0 Introduction An Interactive text editor has become an important part of almost any computing environment. Text editor acts as a primary interface to the computer for all type of “knowledge workers” as they compose, organize, study, and manipulate computer-based information. An interactive debugging system provides programmers with facilities that aid in testing and debugging of programs. Many such systems are available during these days. Our discussion is broad in scope, giving the overview of interactive debugging systems – not specific to any particular existing system. 4.1 Text Editors An Interactive text editor has become an important part of almost any computing environment. Text editor acts as a primary interface to the computer for all type of “knowledge workers” as they compose, organize, study, and manipulate computer-based information. A text editor allows you to edit a text file (create, modify etc…). For example the Interactive text editors on Windows OS - Notepad, WordPad, Microsoft Word, and text editors on UNIX OS - vi, emacs, jed, pico. Normally, the common editing features associated with text editors are, Moving the cursor, Deleting, Replacing, Pasting, Searching, Searching and replacing, Saving and loading, and, Miscellaneous(e.g. quitting). 4.1.1 Overview of the editing process An interactive editor is a computer program that allows a user to create and revise a target document. Document includes objects such as computer diagrams, text, equations tables, diagrams, line art, and photographs. Here we restrict to text editors, where character strings are the primary elements of the target text.
    [Show full text]
  • Running Libraries on Postgresql I
    Running libraries on PostgreSQL i Running libraries on PostgreSQL Running libraries on PostgreSQL ii REVISION HISTORY NUMBER DATE DESCRIPTION NAME Running libraries on PostgreSQL iii Contents 1 License 1 2 Evergreen library system 1 3 Who is Dan Scott? 1 4 Evergreen library adoption (2011) 2 5 GPLS Pines 4 6 BC Sitka 5 7 King County Library System 6 8 Project Conifer 7 9 Library CONSTRAINTs 7 10 It’s not all bad 8 11 Horrible, horrible library data 8 12 Mike Rylander, Evergreen’s eeevil database genius9 13 Indexing library data the Evergreen way 10 14 Random access by field-subfield 10 15 Indexing title / author / subject / keyword 11 16 Adventures in text search: Evergreen 1.0 11 17 Adventures in text search: Evergreen 1.6 11 18 Adventures in text search: Evergreen 2.0 12 19 Adventures in text search: Evergreen 2.2 12 20 Bad news for text search 12 21 Outsource to Solr? 13 22 Functions / stored procedures 13 23 Active tables 13 Running libraries on PostgreSQL iv 24 Debian/Ubuntu packaging 14 25 Materialized views 14 26 Hstore 14 27 Connection pooling 14 28 Replication 15 29 Inheritance 15 30 Schema evolution 15 31 Upgrading PostgreSQL 15 32 Kudos to PostgreSQL 16 33 Help us with our mission 16 Running libraries on PostgreSQL 1 / 16 1 License This talk is licensed under a Creative Commons, Attribution, Share Alike license. Available from http://bzr.coffeecode.net/2012/PGCon/PostgreSQL_in_Libraries.html and horrible PDF Many of the generalizations contained in this presentation are based on a methodologically flawed, self-selecting survey of Evergreen library system administrators.
    [Show full text]
  • Co-Ordination of the Nuclear Reaction Data Centers
    XA9743324 Internotional Atomic Energy Agency INDC(NDS)-360 Distr. G,NC I N DC INTERNATIONAL NUCLEAR DATA COMMITTEE Co-ordination of the Nuclear Reaction Data Centers Report on an IAEA Advisory Group Meeting hosted by the U.S. National Nuclear Data Center on behalf of the U.S. Government Brookhaven, 3-7 June 1996 Edited by O. Schwerer and H.D. Lemmel November 1996 IAEA NUCLEAR DATA SECTION, WAGRAMERSTRASSE 5, A-1400 VIENNA Printed by the IAEA in Austria November 1996 INDC(NDS)-360 Distr. G,NC Co-ordination of the Nuclear Reaction Data Centers Report on an IAEA Advisory Group Meeting hosted by the U.S. National Nuclear Data Center on behalf of the U.S. Government Brookhaven, 3-7 June 1996 Abstract: This report summarizes the 1996 co-ordination meeting in Brookhaven, U.S.A., of the national and regional nuclear reaction data centers, convened by the IAEA at regular intervals. The main topics are - the international exchange of nuclear reaction data by means of the "EXFOR" system, and the further development of this system, the "CINDA" system as an international index and bibliography to neutron reaction data, the sharing of the workload for speedy and reliable nuclear data compilation and data center services, the exchange and documentation of evaluated data libraries in "ENDF" format, the rapid advances of online electronic information technologies, with the goal of rendering data center services to data users in IAEA Member States by means of computer retrievals, online services and printed materials. The scope of data covers microscopic cross-sections and related parameters of nuclear reactions induced by neutrons, charged-particles and photons.
    [Show full text]