A Practical Introduction to Python Programming

Total Page:16

File Type:pdf, Size:1020Kb

A Practical Introduction to Python Programming A Practical Introduction to Python Programming Brian Heinold Department of Mathematics and Computer Science Mount St. Mary’s University ii ©2012 Brian Heinold Licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported Li- cense Contents I Basics1 1 Getting Started 3 1.1 Installing Python..............................................3 1.2 IDLE......................................................3 1.3 A first program...............................................4 1.4 Typing things in...............................................5 1.5 Getting input.................................................6 1.6 Printing....................................................6 1.7 Variables...................................................7 1.8 Exercises...................................................9 2 For loops 11 2.1 Examples................................................... 11 2.2 The loop variable.............................................. 13 2.3 The range function............................................ 13 2.4 A Trickier Example............................................. 14 2.5 Exercises................................................... 15 3 Numbers 19 3.1 Integers and Decimal Numbers.................................... 19 3.2 Math Operators............................................... 19 3.3 Order of operations............................................ 21 3.4 Random numbers............................................. 21 3.5 Math functions............................................... 21 3.6 Getting help from Python........................................ 22 3.7 Using the Shell as a Calculator..................................... 22 3.8 Exercises................................................... 23 4 If statements 27 4.1 A Simple Example............................................. 27 4.2 Conditional operators........................................... 28 4.3 Common Mistakes............................................. 28 4.4 elif ...................................................... 29 4.5 Exercises................................................... 30 iii iv CONTENTS 5 Miscellaneous Topics I 33 5.1 Counting................................................... 33 5.2 Summing................................................... 34 5.3 Swapping................................................... 35 5.4 Flag variables................................................ 36 5.5 Maxes and mins............................................... 36 5.6 Comments.................................................. 37 5.7 Simple debugging............................................. 37 5.8 Example programs............................................. 38 5.9 Exercises................................................... 40 6 Strings 43 6.1 Basics...................................................... 43 6.2 Concatenation and repetition...................................... 44 6.3 The in operator............................................... 44 6.4 Indexing.................................................... 45 6.5 Slices...................................................... 45 6.6 Changing individual characters of a string............................. 46 6.7 Looping.................................................... 46 6.8 String methods............................................... 47 6.9 Escape characters.............................................. 48 6.10 Examples................................................... 49 6.11 Exercises................................................... 51 7 Lists 57 7.1 Basics...................................................... 57 7.2 Similarities to strings........................................... 58 7.3 Built-in functions.............................................. 59 7.4 List methods................................................. 59 7.5 Miscellaneous................................................ 60 7.6 Examples................................................... 60 7.7 Exercises................................................... 62 8 More with Lists 65 8.1 Lists and the random module..................................... 65 8.2 split ..................................................... 66 8.3 join ...................................................... 67 8.4 List comprehensions............................................ 68 8.5 Using list comprehensions........................................ 69 8.6 Two-dimensional lists........................................... 70 8.7 Exercises................................................... 72 CONTENTS v 9 While loops 75 9.1 Examples................................................... 75 9.2 Infinite loops................................................. 78 9.3 The break statement........................................... 78 9.4 The else statement............................................. 79 9.5 The guessing game, more nicely done................................ 80 9.6 Exercises................................................... 83 10 Miscellaneous Topics II 87 10.1 str, int, float, and list ..................................... 87 10.2 Booleans.................................................... 89 10.3 Shortcuts................................................... 90 10.4 Short-circuiting............................................... 91 10.5 Continuation................................................. 91 10.6 pass ...................................................... 91 10.7 String formatting.............................................. 92 10.8 Nested loops................................................. 93 10.9 Exercises................................................... 95 11 Dictionaries 99 11.1 Basics...................................................... 99 11.2 Dictionary examples............................................ 100 11.3 Working with dictionaries........................................ 101 11.4 Counting words............................................... 102 11.5 Exercises................................................... 104 12 Text Files 109 12.1 Reading from files............................................. 109 12.2 Writing to files................................................ 110 12.3 Examples................................................... 110 12.4 Wordplay................................................... 111 12.5 Exercises................................................... 113 13 Functions 119 13.1 Basics...................................................... 119 13.2 Arguments.................................................. 120 13.3 Returning values.............................................. 121 13.4 Default arguments and keyword arguments............................ 122 13.5 Local variables............................................... 123 13.6 Exercises................................................... 125 14 Object-Oriented Programming 129 14.1 Python is objected-oriented....................................... 129 14.2 Creating your own classes........................................ 130 14.3 Inheritance.................................................. 132 14.4 A playing-card example......................................... 133 vi CONTENTS 14.5 A Tic-tac-toe example........................................... 136 14.6 Further topics................................................ 138 14.7 Exercises................................................... 138 II Graphics 141 15 GUI Programming with Tkinter 143 15.1 Basics...................................................... 143 15.2 Labels..................................................... 144 15.3 grid ...................................................... 145 15.4 Entry boxes.................................................. 146 15.5 Buttons.................................................... 146 15.6 Global variables............................................... 148 15.7 Tic-tac-toe................................................... 149 16 GUI Programming II 155 16.1 Frames..................................................... 155 16.2 Colors..................................................... 156 16.3 Images..................................................... 157 16.4 Canvases................................................... 158 16.5 Check buttons and Radio buttons................................... 159 16.6 Text widget................................................. 160 16.7 Scale widget................................................ 161 16.8 GUI Events.................................................. 162 16.9 Event examples............................................... 164 17 GUI Programming III 169 17.1 Title bar.................................................... 169 17.2 Disabling things............................................... 169 17.3 Getting the state of a widget....................................... 169 17.4 Message boxes................................................ 170 17.5 Destroying things.............................................. 171 17.6 Updating................................................... 171 17.7 Dialogs.................................................... 172 17.8 Menu bars.................................................. 174 17.9 New windows................................................ 174 17.10pack ...................................................... 175 17.11StringVar ................................................. 175 17.12More with GUIs............................................... 176 18 Further Graphical Programming 177 18.1 Python 2 vs Python 3..........................................
Recommended publications
  • Fill Your Boots: Enhanced Embedded Bootloader Exploits Via Fault Injection and Binary Analysis
    IACR Transactions on Cryptographic Hardware and Embedded Systems ISSN 2569-2925, Vol. 2021, No. 1, pp. 56–81. DOI:10.46586/tches.v2021.i1.56-81 Fill your Boots: Enhanced Embedded Bootloader Exploits via Fault Injection and Binary Analysis Jan Van den Herrewegen1, David Oswald1, Flavio D. Garcia1 and Qais Temeiza2 1 School of Computer Science, University of Birmingham, UK, {jxv572,d.f.oswald,f.garcia}@cs.bham.ac.uk 2 Independent Researcher, [email protected] Abstract. The bootloader of an embedded microcontroller is responsible for guarding the device’s internal (flash) memory, enforcing read/write protection mechanisms. Fault injection techniques such as voltage or clock glitching have been proven successful in bypassing such protection for specific microcontrollers, but this often requires expensive equipment and/or exhaustive search of the fault parameters. When multiple glitches are required (e.g., when countermeasures are in place) this search becomes of exponential complexity and thus infeasible. Another challenge which makes embedded bootloaders notoriously hard to analyse is their lack of debugging capabilities. This paper proposes a grey-box approach that leverages binary analysis and advanced software exploitation techniques combined with voltage glitching to develop a powerful attack methodology against embedded bootloaders. We showcase our techniques with three real-world microcontrollers as case studies: 1) we combine static and on-chip dynamic analysis to enable a Return-Oriented Programming exploit on the bootloader of the NXP LPC microcontrollers; 2) we leverage on-chip dynamic analysis on the bootloader of the popular STM8 microcontrollers to constrain the glitch parameter search, achieving the first fully-documented multi-glitch attack on a real-world target; 3) we apply symbolic execution to precisely aim voltage glitches at target instructions based on the execution path in the bootloader of the Renesas 78K0 automotive microcontroller.
    [Show full text]
  • Fortran 90 Overview
    1 Fortran 90 Overview J.E. Akin, Copyright 1998 This overview of Fortran 90 (F90) features is presented as a series of tables that illustrate the syntax and abilities of F90. Frequently comparisons are made to similar features in the C++ and F77 languages and to the Matlab environment. These tables show that F90 has significant improvements over F77 and matches or exceeds newer software capabilities found in C++ and Matlab for dynamic memory management, user defined data structures, matrix operations, operator definition and overloading, intrinsics for vector and parallel pro- cessors and the basic requirements for object-oriented programming. They are intended to serve as a condensed quick reference guide for programming in F90 and for understanding programs developed by others. List of Tables 1 Comment syntax . 4 2 Intrinsic data types of variables . 4 3 Arithmetic operators . 4 4 Relational operators (arithmetic and logical) . 5 5 Precedence pecking order . 5 6 Colon Operator Syntax and its Applications . 5 7 Mathematical functions . 6 8 Flow Control Statements . 7 9 Basic loop constructs . 7 10 IF Constructs . 8 11 Nested IF Constructs . 8 12 Logical IF-ELSE Constructs . 8 13 Logical IF-ELSE-IF Constructs . 8 14 Case Selection Constructs . 9 15 F90 Optional Logic Block Names . 9 16 GO TO Break-out of Nested Loops . 9 17 Skip a Single Loop Cycle . 10 18 Abort a Single Loop . 10 19 F90 DOs Named for Control . 10 20 Looping While a Condition is True . 11 21 Function definitions . 11 22 Arguments and return values of subprograms . 12 23 Defining and referring to global variables .
    [Show full text]
  • Quick Overview: Complex Numbers
    Quick Overview: Complex Numbers February 23, 2012 1 Initial Definitions Definition 1 The complex number z is defined as: z = a + bi (1) p where a, b are real numbers and i = −1. Remarks about the definition: • Engineers typically use j instead of i. • Examples of complex numbers: p 5 + 2i; 3 − 2i; 3; −5i • Powers of i: i2 = −1 i3 = −i i4 = 1 i5 = i i6 = −1 i7 = −i . • All real numbers are also complex (by taking b = 0). 2 Visualizing Complex Numbers A complex number is defined by it's two real numbers. If we have z = a + bi, then: Definition 2 The real part of a + bi is a, Re(z) = Re(a + bi) = a The imaginary part of a + bi is b, Im(z) = Im(a + bi) = b 1 Im(z) 4i 3i z = a + bi 2i r b 1i θ Re(z) a −1i Figure 1: Visualizing z = a + bi in the complex plane. Shown are the modulus (or length) r and the argument (or angle) θ. To visualize a complex number, we use the complex plane C, where the horizontal (or x-) axis is for the real part, and the vertical axis is for the imaginary part. That is, a + bi is plotted as the point (a; b). In Figure 1, we can see that it is also possible to represent the point a + bi, or (a; b) in polar form, by computing its modulus (or size), and angle (or argument): p r = jzj = a2 + b2 θ = arg(z) We have to be a bit careful defining φ, since there are many ways to write φ (and we could add multiples of 2π as well).
    [Show full text]
  • Fortran Math Special Functions Library
    IMSL® Fortran Math Special Functions Library Version 2021.0 Copyright 1970-2021 Rogue Wave Software, Inc., a Perforce company. Visual Numerics, IMSL, and PV-WAVE are registered trademarks of Rogue Wave Software, Inc., a Perforce company. IMPORTANT NOTICE: Information contained in this documentation is subject to change without notice. Use of this docu- ment is subject to the terms and conditions of a Rogue Wave Software License Agreement, including, without limitation, the Limited Warranty and Limitation of Liability. ACKNOWLEDGMENTS Use of the Documentation and implementation of any of its processes or techniques are the sole responsibility of the client, and Perforce Soft- ware, Inc., assumes no responsibility and will not be liable for any errors, omissions, damage, or loss that might result from any use or misuse of the Documentation PERFORCE SOFTWARE, INC. MAKES NO REPRESENTATION ABOUT THE SUITABILITY OF THE DOCUMENTATION. THE DOCU- MENTATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. PERFORCE SOFTWARE, INC. HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS WITH REGARD TO THE DOCUMENTATION, WHETHER EXPRESS, IMPLIED, STATUTORY, OR OTHERWISE, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PAR- TICULAR PURPOSE, OR NONINFRINGEMENT. IN NO EVENT SHALL PERFORCE SOFTWARE, INC. BE LIABLE, WHETHER IN CONTRACT, TORT, OR OTHERWISE, FOR ANY SPECIAL, CONSEQUENTIAL, INDIRECT, PUNITIVE, OR EXEMPLARY DAMAGES IN CONNECTION WITH THE USE OF THE DOCUMENTATION. The Documentation is subject to change at any time without notice. IMSL https://www.imsl.com/ Contents Introduction The IMSL Fortran Numerical Libraries . 1 Getting Started . 2 Finding the Right Routine . 3 Organization of the Documentation . 4 Naming Conventions .
    [Show full text]
  • Free Remote Agile E-Book
    Table of Contents 1. Welcome to a new kind of Agile 2. Establishing Ground Rules 3. Stop Dreading Meetings: The Webcam Revolution 4. The Virtual Office Setup 5. Case Study: Stack Exchange’s Hybrid Team 6. Building and Nurturing Your Remote Team 7. Best Email Practices 8. Case Study: RES Software’s Three Remote Offices 9. Agile Can Thrive With Remote Teams 10. Let Us Know How We Can Help! Welcome to a new kind of Agile The current charter of most distributed company leaders is to create an online workspace (...) supported by a set of tools and self- organizing behaviors.(...)With a strong vision, clear articulation of priorities, and strongly nurturing culture as part of your company DNA, you have a clear path to success on your distributed Agile team." - Amanda Ross, Director of Marketing & Agile Practices at Sococo It’s been called a framework, a philosophy, a methodology - research Agile and you’ll find that so many people define it with so many different words that you'd be forgiven for thinking it’s some sort of mystical practice involving tarot cards and looking at the stars. But it’s actually a major shift in the way people work, and it’s been happening for over a decade - whatever you choose to call it, if you are in the IT business, Agile is likely part of the way you work. If it’s not, the time to start is now. Companies and teams worldwide have used it to deliver better products in record time with maximum efficiency and minimum burnout.
    [Show full text]
  • Glitch Studies Manifesto
    [email protected]. Amsterdam/Cologne, 2009/2010 http://rosa-menkman.blogspot.com The dominant, continuing search for a noiseless channel has been, and will always be no more than a regrettable, ill-fated dogma. Even though the constant search for complete transparency brings newer, ‘better’ media, every one of these new and improved techniques will always have their own fingerprints of imperfection. While most people experience these fingerprints as negative (and sometimes even as accidents) I emphasize the positive consequences of these imperfections by showing the new opportunities they facilitate. In the beginning there was only noise. Then the artist moved from the grain of celluloid to the magnetic distortion and scanning lines of the cathode ray tube. he wandered the planes of phosphor burn-in, rubbed away dead pixels and now makes performance art based on the cracking of LCD screens. The elitist discourse of the upgrade is a dogma widely pursued by the naive victims of a persistent upgrade culture. The consumer only has to dial #1-800 to stay on top of the technological curve, the waves of both euphoria and disappointment. It has become normal that in the future the consumer will pay less for a device that can do more. The user has to realize that improving is nothing more than a proprietary protocol, a deluded consumer myth about progression towards a holy grail of perfection. Dispute the operating templates of creative practice by fighting genres and expectations! I feel stuck in the membranes of knowledge, governed by social conventions and acceptances. As an artist I strive to reposition these membranes; I do not feel locked into one medium or between contradictions like real vs.
    [Show full text]
  • IEEE Standard 754 for Binary Floating-Point Arithmetic
    Work in Progress: Lecture Notes on the Status of IEEE 754 October 1, 1997 3:36 am Lecture Notes on the Status of IEEE Standard 754 for Binary Floating-Point Arithmetic Prof. W. Kahan Elect. Eng. & Computer Science University of California Berkeley CA 94720-1776 Introduction: Twenty years ago anarchy threatened floating-point arithmetic. Over a dozen commercially significant arithmetics boasted diverse wordsizes, precisions, rounding procedures and over/underflow behaviors, and more were in the works. “Portable” software intended to reconcile that numerical diversity had become unbearably costly to develop. Thirteen years ago, when IEEE 754 became official, major microprocessor manufacturers had already adopted it despite the challenge it posed to implementors. With unprecedented altruism, hardware designers had risen to its challenge in the belief that they would ease and encourage a vast burgeoning of numerical software. They did succeed to a considerable extent. Anyway, rounding anomalies that preoccupied all of us in the 1970s afflict only CRAY X-MPs — J90s now. Now atrophy threatens features of IEEE 754 caught in a vicious circle: Those features lack support in programming languages and compilers, so those features are mishandled and/or practically unusable, so those features are little known and less in demand, and so those features lack support in programming languages and compilers. To help break that circle, those features are discussed in these notes under the following headings: Representable Numbers, Normal and Subnormal, Infinite
    [Show full text]
  • (Pdf) of from Push/Enter to Eval/Apply by Program Transformation
    From Push/Enter to Eval/Apply by Program Transformation MaciejPir´og JeremyGibbons Department of Computer Science University of Oxford [email protected] [email protected] Push/enter and eval/apply are two calling conventions used in implementations of functional lan- guages. In this paper, we explore the following observation: when considering functions with mul- tiple arguments, the stack under the push/enter and eval/apply conventions behaves similarly to two particular implementations of the list datatype: the regular cons-list and a form of lists with lazy concatenation respectively. Along the lines of Danvy et al.’s functional correspondence between def- initional interpreters and abstract machines, we use this observation to transform an abstract machine that implements push/enter into an abstract machine that implements eval/apply. We show that our method is flexible enough to transform the push/enter Spineless Tagless G-machine (which is the semantic core of the GHC Haskell compiler) into its eval/apply variant. 1 Introduction There are two standard calling conventions used to efficiently compile curried multi-argument functions in higher-order languages: push/enter (PE) and eval/apply (EA). With the PE convention, the caller pushes the arguments on the stack, and jumps to the function body. It is the responsibility of the function to find its arguments, when they are needed, on the stack. With the EA convention, the caller first evaluates the function to a normal form, from which it can read the number and kinds of arguments the function expects, and then it calls the function body with the right arguments.
    [Show full text]
  • Stepping Ocaml
    Stepping OCaml TsukinoFurukawa YouyouCong KenichiAsai Ochanomizu University Tokyo, Japan {furukawa.tsukino, so.yuyu, asai}@is.ocha.ac.jp Steppers, which display all the reduction steps of a given program, are a novice-friendly tool for un- derstanding program behavior. Unfortunately, steppers are not as popular as they ought to be; indeed, the tool is only available in the pedagogical languages of the DrRacket programming environment. We present a stepper for a practical fragment of OCaml. Similarly to the DrRacket stepper, we keep track of evaluation contexts in order to reconstruct the whole program at each reduction step. The difference is that we support effectful constructs, such as exception handling and printing primitives, allowing the stepper to assist a wider range of users. In this paper, we describe the implementationof the stepper, share the feedback from our students, and show an attempt at assessing the educational impact of our stepper. 1 Introduction Programmers spend a considerable amount of time and effort on debugging. In particular, novice pro- grammers may find this process extremely painful, since existing debuggers are usually not friendly enough to beginners. To use a debugger, we have to first learn what kinds of commands are available, and figure out which would be useful for the current purpose. It would be even harder to use the com- mand in a meaningful manner: for instance, to spot the source of an unexpected behavior, we must be able to find the right places to insert breakpoints, which requires some programming experience. Then, is there any debugging tool that is accessible to first-day programmers? In our view, the algebraic stepper [1] of DrRacket, a pedagogical programming environment for the Racket language, serves as such a tool.
    [Show full text]
  • A Fast-Start Method for Computing the Inverse Tangent
    A Fast-Start Method for Computing the Inverse Tangent Peter Markstein Hewlett-Packard Laboratories 1501 Page Mill Road Palo Alto, CA 94062, U.S.A. [email protected] Abstract duction method is handled out-of-loop because its use is rarely required.) In a search for an algorithm to compute atan(x) For short latency, it is often desirable to use many in- which has both low latency and few floating point in- structions. Different sequences may be optimal over var- structions, an interesting variant of familiar trigonom- ious subdomains of the function, and in each subdomain, etry formulas was discovered that allow the start of ar- instruction level parallelism, such as Estrin’s method of gument reduction to commence before any references to polynomial evaluation [3] reduces latency at the cost of tables stored in memory are needed. Low latency makes additional intermediate calculations. the method suitable for a closed subroutine, and few In searching for an inverse tangent algorithm, an un- floating point operations make the method advantageous usual method was discovered that permits a floating for a software-pipelined implementation. point argument reduction computation to begin at the first cycle, without first examining a table of values. While a table is used, the table access is overlapped with 1Introduction most of the argument reduction, helping to contain la- tency. The table is designed to allow a low degree odd Short latency and high throughput are two conflict- polynomial to complete the approximation. A new ap- ing goals in transcendental function evaluation algo- proach to the logarithm routine [1] which motivated this rithm design.
    [Show full text]
  • Making a Faster Curry with Extensional Types
    Making a Faster Curry with Extensional Types Paul Downen Simon Peyton Jones Zachary Sullivan Microsoft Research Zena M. Ariola Cambridge, UK University of Oregon [email protected] Eugene, Oregon, USA [email protected] [email protected] [email protected] Abstract 1 Introduction Curried functions apparently take one argument at a time, Consider these two function definitions: which is slow. So optimizing compilers for higher-order lan- guages invariably have some mechanism for working around f1 = λx: let z = h x x in λy:e y z currying by passing several arguments at once, as many as f = λx:λy: let z = h x x in e y z the function can handle, which is known as its arity. But 2 such mechanisms are often ad-hoc, and do not work at all in higher-order functions. We show how extensional, call- It is highly desirable for an optimizing compiler to η ex- by-name functions have the correct behavior for directly pand f1 into f2. The function f1 takes only a single argu- expressing the arity of curried functions. And these exten- ment before returning a heap-allocated function closure; sional functions can stand side-by-side with functions native then that closure must subsequently be called by passing the to practical programming languages, which do not use call- second argument. In contrast, f2 can take both arguments by-name evaluation. Integrating call-by-name with other at once, without constructing an intermediate closure, and evaluation strategies in the same intermediate language ex- this can make a huge difference to run-time performance in presses the arity of a function in its type and gives a princi- practice [Marlow and Peyton Jones 2004].
    [Show full text]
  • LIGO Detector Characterization Group Maintained by Josh Smith DCC# LIGO-G1500642 This Document: A
    Glitch classes seen in aLIGO so far (through end of O1) LIGO Detector Characterization Group Maintained by Josh Smith DCC# LIGO-G1500642 This document: A. lists the major glitch classes that have been seen in aLIGO so far, B. shows a few representative images, C.says which detectors have which glitches, and D.provides links to alog pages and wikis for more information 2 Table of Contents 1. LHO/LLO Blip glitches [NF] 9. Blue Mountains [NF] 2. LLO RF Beats [NF] 10. LHO End-Y 60Hz glitches [F] 3. LLO Koi fish (working title) [NF] 11. Saturating tidal control [F] 4. LHO end-Y scattered light [NF] 12.OMC L Scattered light [F] 5. LLO SRM scattered light [NF] 13.Hartmann Wavefront sensor malfunction [F] 6. LHO paired doves [NF] 14. LHO PRCL/SRCL glitches [F] 7. DAC glitches [PF] 15. LHO End-Y 50Hz air compressor 8. n*505Hz glitches [PF] glitches [F] [NF] = not fixed, [PF]= partially fixed, [F]=fixed 3 1. Blip glitches H1 Examples: https://ldas-jobs.ligo-wa.caltech.edu/~areeda/blip-omega.tar 4 Blip glitches documentation • Brief description: Class of common glitches in both detectors, with no known cause currently. The only weak lead is that saturated hardware injections cause glitches that look very similar, so perhaps these are saturations in the actuation chain that happen under normal conditions. • Relevant alogs: • LLO: • LHO: saturated injections look like blips? • Other documentation: Some blip times and scans link 5 2. RF Beats Examples: https://ldas-jobs.ligo.caltech.edu/~areeda/josh-20150828.tgz 6 RF Beats documentation • Brief description: These are beats of two or more RF oscillators that sweep quickly through the audio range.
    [Show full text]