Learning to Program with Python

Total Page:16

File Type:pdf, Size:1020Kb

Learning to Program with Python Learning to Program with Python An introduction to the Python programming language for those who haven’t programmed before Version 2020-01 Learning to program with Python 2 Licence This manual is © 2020, Steven Wingett & Simon Andrews. This manual is distributed under the creative commons Attribution-Non-Commercial-Share Alike 2.0 licence. This means that you are free: to copy, distribute, display, and perform the work to make derivative works Under the following conditions: Attribution. You must give the original author credit. Non-Commercial. You may not use this work for commercial purposes. Share Alike. If you alter, transform, or build upon this work, you may distribute the resulting work only under a licence identical to this one. Please note that: For any reuse or distribution, you must make clear to others the licence terms of this work. Any of these conditions can be waived if you get permission from the copyright holder. Nothing in this license impairs or restricts the author's moral rights. Full details of this licence can be found at http://creativecommons.org/licenses/by-nc-sa/2.0/uk/legalcode Learning to program with Python 3 Table of Contents Licence ................................................................................................................................................... 2 Table of Contents .................................................................................................................................. 3 Introduction ........................................................................................................................................... 6 Why learn Python? .............................................................................................................................. 6 What this course covers ...................................................................................................................... 6 Python 2 or Python 3? ......................................................................................................................... 7 A note about learning a programming language ................................................................................. 7 Chapter 1: getting started with Python ............................................................................................... 8 How to install Python ........................................................................................................................... 8 On Linux/Unix/MacOSX etc. ............................................................................................................ 8 On Windows ..................................................................................................................................... 8 What do I use to write Python code? ................................................................................................... 9 Thonny ............................................................................................................................................... 10 Hello World! and getting started with Python .................................................................................... 11 Chapter 2: data types and expressions ............................................................................................ 12 Integers (int) ...................................................................................................................................... 12 Floats ................................................................................................................................................. 13 Booleans (bool) ................................................................................................................................. 14 Strings (str) ........................................................................................................................................ 16 Operations on strings ..................................................................................................................... 17 Compound expressions ..................................................................................................................... 20 Chapter 3: names, functions and methods ...................................................................................... 21 Writing scripts using Thonny ............................................................................................................. 21 Names ............................................................................................................................................... 22 F-strings ............................................................................................................................................. 24 Functions ........................................................................................................................................... 25 Built-in functions ............................................................................................................................. 25 Functions and data types ............................................................................................................... 27 Creating Functions ......................................................................................................................... 28 Methods ............................................................................................................................................. 33 Chapter 4 – Collections ...................................................................................................................... 34 Sets.................................................................................................................................................... 34 Sequences ......................................................................................................................................... 36 Ranges ........................................................................................................................................... 36 Tuples ............................................................................................................................................ 37 Lists ................................................................................................................................................... 38 Mappings ........................................................................................................................................... 40 Dictionaries .................................................................................................................................... 40 Streams ............................................................................................................................................. 42 Learning to program with Python 4 Files ................................................................................................................................................ 42 Generators ..................................................................................................................................... 43 Copying Collections ........................................................................................................................... 43 Further points on manipulating collections with functions and methods ........................................... 45 The key parameter ......................................................................................................................... 45 Key expressions ............................................................................................................................. 45 Anonymous functions (the lambda function).................................................................................. 46 Chapter 5 – Conditionals, loops and iterations ............................................................................... 47 Conditionals ....................................................................................................................................... 47 Simple, one-alternative and multi-test conditionals ....................................................................... 47 Loops ................................................................................................................................................. 48 While Loops ................................................................................................................................... 48 Processing file input using a loop .................................................................................................. 50 Iterations ............................................................................................................................................ 50 Simple Iteration .............................................................................................................................. 50 Iterating over a file ......................................................................................................................... 51 Iterating over a dictionary............................................................................................................... 51 Enumerating iterations ................................................................................................................... 51 Iterating over ranges .....................................................................................................................
Recommended publications
  • SCIS Boardman Labs User Manual Version5
    SCIS Common Use Labs in Boardman Hall USER MANUAL Note: The instructions in this manual assume students walking into the labs are first-time users of the labs and are complete novices in using the machines. Table of Contents Page I. Access to Boardman Hall SCIS Labs for Computer Science and New Media Students A. Services Provided 2 B. Gaining Access to Lab Rooms and Computers 3 II. SCIS Common Use Lab (Room 138 Boardman) A. Services Provided 3 B. Use of iMacs on Tables 4 C. Use of Large Table Monitor for Sharing Among Table Group 4 D. Use of Overhead Projector 5 E. Use of Laser Printer (8 ½ by 11” Prints) 6 F. Use of Large Format Plotter 7 G. Software Available on Computers in Room 138 7 H. Equipment Available for Checkout from Room 138 Lab Monitors 8 III. Combined Focus Ring and Stillwater Labs (Rooms 127 and 129 Boardman) A. Services Provided 8 B. Use of iMacs on Tables 9 C. Use of Cybertron PC for AI and VR D. Use of … E. Software Available on Computers in Rooms 127 and 129 F. Equipment Checkout Procedure G. Equipment Available for Checkout from Rooms 127 and 129 Lab Monitors IV. SCIS Student Lounge and Project Work Room (Room 137 Boardman) A. Services Provided B. Use of Large Screen by Students APPENDICES Appendix A. Laptop Computer Recommendations for Computer Science Students Appendix B. Laptop Computer Recommendations for New Media Students Appendix C. Convenient Web Resources for Development of Computer Code Note: On SCIS web site all of the above topics will link to anchors at the same topics below.
    [Show full text]
  • Fira Code: Monospaced Font with Programming Ligatures
    Personal Open source Business Explore Pricing Blog Support This repository Sign in Sign up tonsky / FiraCode Watch 282 Star 9,014 Fork 255 Code Issues 74 Pull requests 1 Projects 0 Wiki Pulse Graphs Monospaced font with programming ligatures 145 commits 1 branch 15 releases 32 contributors OFL-1.1 master New pull request Find file Clone or download lf- committed with tonsky Add mintty to the ligatures-unsupported list (#284) Latest commit d7dbc2d 16 days ago distr Version 1.203 (added `__`, closes #120) a month ago showcases Version 1.203 (added `__`, closes #120) a month ago .gitignore - Removed `!!!` `???` `;;;` `&&&` `|||` `=~` (closes #167) `~~~` `%%%` 3 months ago FiraCode.glyphs Version 1.203 (added `__`, closes #120) a month ago LICENSE version 0.6 a year ago README.md Add mintty to the ligatures-unsupported list (#284) 16 days ago gen_calt.clj Removed `/**` `**/` and disabled ligatures for `/*/` `*/*` sequences … 2 months ago release.sh removed Retina weight from webfonts 3 months ago README.md Fira Code: monospaced font with programming ligatures Problem Programmers use a lot of symbols, often encoded with several characters. For the human brain, sequences like -> , <= or := are single logical tokens, even if they take two or three characters on the screen. Your eye spends a non-zero amount of energy to scan, parse and join multiple characters into a single logical one. Ideally, all programming languages should be designed with full-fledged Unicode symbols for operators, but that’s not the case yet. Solution Download v1.203 · How to install · News & updates Fira Code is an extension of the Fira Mono font containing a set of ligatures for common programming multi-character combinations.
    [Show full text]
  • Pycharm Reference Card.Pdf
    Default Keymap Default Keymap Default Keymap Editing Compile and Run Usage Search Ctrl + Space Basic code completion (the name of any class, method Alt + Shift + F10 Select configuration and run Alt + F7 / Ctrl + F7 Find usages / Find usages in file or variable) Alt + Shift + F9 Select configuration and debug Ctrl + Shift + F7 Highlight usages in file Ctrl + Alt + Space Class name completion (the name of any project class Shift + F10 Run Ctrl + Alt + F7 Show usages independently of current imports) Shift + F9 Debug Refactoring Ctrl + Shift + Enter Complete statement Ctrl + Shift + F10 Run context configuration from editor Ctrl + P Parameter info (within method call arguments) F5 Copy Debugging Ctrl + Q Quick documentation lookup F6 Move Shift + F1 External Doc F8 Step over Alt + Delete Safe Delete Ctrl + mouse over code Brief Info F7 Step into Shift + F6 Rename Ctrl + F1 Show descriptions of error or warning at caret Shift + F8 Step out Ctrl + F6 Change Signature Alt + Insert Generate code... Alt + F9 Run to cursor Ctrl + Alt + N Inline Ctrl + O Override methods Alt + F8 Evaluate expression Ctrl + Alt + M Extract Method Ctrl + Alt + T Surround with... Ctrl + Alt + F8 Quick evaluate expression Ctrl + Alt + V Introduce Variable Ctrl + / Comment/uncomment with line comment F9 Resume program Ctrl + Alt + F Introduce Field Ctrl + Shift + / Comment/uncomment with block comment Ctrl + F8 Toggle breakpoint Ctrl + Alt + C Introduce Constant Ctrl + W Select successively increasing code blocks Ctrl + Shift + F8 View breakpoints Ctrl + Alt + P Introduce
    [Show full text]
  • Syllabus Instructor
    Syllabus Instructor That's me! I am Eric Reed, and you can email me at [email protected] (mailto:[email protected]) . It's easiest for me if you ask questions through the private or public message center here in the course, and only use email if you have trouble logging in. I get a huge amount of email and there's a chance that a time critical question will get lost if you email me. Why do I get so much email? I am also the STEM Center (http://foothill.edu/stemcenter) director here at Foothill. Which, by the way, is a good place to know. More about that later. I teach both math and computer science. I hold an M.S. in math from CSU East Bay and an M.S. in computer science from Georgia Tech. Feel free to ask me about either one. What you really need to know is that I am glad you are here, and my goal is your success in this course. Office Hours You can find me online on Sundays from 10am­11am at foothill.edu/stemcenter/onlinecs We will hold two office hours on campus as well: Tuesday 11AM ­ Noon Room 4412 Friday 6pm­7pm Room 4601 You may always feel free to contact me for an appointment. Oh, what about this course? CS 3C is an advanced lower division computer programming course using the Python language. The truth is, the course is more about the computer science concepts than the language. We will learn about time complexity (Big­O notation), data structures like trees and hash tables, and topics related to algorithms like sorts and minimum spanning trees To succeed in this class, you need a solid understanding of Python structure and statements, and some experience with object oriented design.
    [Show full text]
  • Programming Environments
    Programming Environments Presenter: Steve Baskauf [email protected] CodeGraf landing page • vanderbi.lt/codegraf What is an environment? vanderbi.lt/codegraf Coding environment • The definition of "environment" is a bit murky • We can consider an environment to include: • the value of defined variables • functions available to be used in our code • knowledge about position in file directory structure and other computer-wide parameters Accessing via the shell • Python example • R example Integrated development environment (IDE) What is an integrated development environment (IDE)? • An IDE is a graphical user interface (GUI) for developing code • An IDE includes: • a code editor • a shell • An IDE might include: • tools for examining the environment • formatting help and syntax checking • mechanisms for debugging code • a package manager Thonny example • Thonny is a simple Python IDE Spyder IDE for Python RStudio IDE for R Literate programming with Jupyter notebooks Literate programming • Programming paradigm for making code understandable to humans • Mix text, images, links with code. • Implementable in a primitive fashion with comments (#) • Implementable in a robust way with Jupyter notebooks and R Markdown Example: Jupyter notebooks • Formerly known as "iPython notebooks" (.ipynb file extension) • Now usable with Python, R, and other programming languages • Runnable in a browser when connected to a server • Viewable in GitHub (but not runnable) Functions Functions argument parameter • A function defines a block of code. • We pass arguments into functions: • functionName(argument1, argument2, ...) • It’s good to name functions by what they do. returned Example: value my_latte = make_latte(beans, milk, water) • Functions can be: • built-in • defined by you in your code • defined by somebody else in a module Image: Nykamp DQ, “Function machine f.” From Math Insight.
    [Show full text]
  • Parallel Computing in Python
    2017 / 02 / Parallel Computing 09 in Python Reserved All Rights PRACE Winter School 2017 @ Tel-Aviv/Israel Mordechai Butrashvily All material is under 1 Few Words • I’m a graduate student @ Geophysics, Tel-Aviv University • Dealing with physics, geophysics & applied mathematics 2017 / 02 / • Parallel computing is essential in my work 09 • Participated in PRACE Summer of HPC 2013 • Don’t miss a chance to take part Reserved All Rights • Registration ends by 19/2 • Apply here: • https://summerofhpc.prace-ri.eu/apply 2 • You would enjoy it, and if not I’m here to complain… Why Are We Here? • Python is very popular, simple and intuitive • Increasing use in many fields of research & industry 2017 / • Open-source and free 02 / • Many toolboxes available in almost every field 09 • NumPy/SciPy are prerequisite for scientists • Replacement for MATLAB/Mathematica (to some extent) All Rights Reserved All Rights • Natural to ask if parallel computing can be simpler too • Indeed yes! • And also take advantage of existing C/Fortran code 3 (My) Audience Assumptions • Some may know python • But not much of its multiprocessing capabilities 2017 / 02 / • Some may know parallel computing 09 • But not quite familiar with python • Working in Linux environments Reserved All Rights • Not mandatory but highly advised • Knowing a descent programming language 4 (My) Workshop Goals • Don’t worry 2017 / • The workshop was designed for introductory purposes 02 / • First basic theory, then practical hands-on session 09 • Hands-on will be in different levels (3 as usual)
    [Show full text]
  • Scratch, Blocky & Co., Blocksysteme Zum Programmieren
    Notizen Lothar Griess • 26. Mai 2018 Scratch, Blocky & Co., Blocksysteme zum Programmieren Scratch-Alternativen, … https://wiki.scratch.mit.edu/wiki/Alternatives_to_Scratch HTML5 als Grundlage wär besser, die Zukunft von Flash ist unklar. Liste der Modifikationen ... https://scratch-dach.info/wiki/Liste_der_Modifikationen Enchanting (Scratch Modifikation) ... https://scratch-dach.info/wiki/Enchanting_(Scratch_Modifikation) Beetle Blocks ist wie Scratch oder BlocksCAD für 3D-Grafiken... https://scratch-dach.info/wiki/Beetle_Blocks Beetle Blocks GitHub Repository ... https://github.com/ericrosenbaum/BeetleBlocks Beetle Blocks (3D-Design), … http://beetleblocks.com/ Mod Share … z.B.: Supported Scratch-Modifications … https://wiki.scratch.mit.edu/wiki/Mod_Share Scratch … https://wiki.scratch.mit.edu/wiki/Scratch Snap … https://wiki.scratch.mit.edu/wiki/Snap_(Scratch_Modification) Bingo … https://wiki.scratch.mit.edu/wiki/Bingo_(Scratch_Modification) Panther … https://wiki.scratch.mit.edu/wiki/Panther_(Scratch_Modification) Insanity … https://wiki.scratch.mit.edu/wiki/Insanity_(Scratch_Modification) … weitere: Stack, Kitcat, Ghost, Streak • • • Blockly is used by hundreds of projects, most of them educational: ... https://developers.google.com/blockly/ Blockly, RoboBlockly, ... https://code.org/learn Google Education, 1 Stunde, ... https://hourofcode.com/blockly Got PCs with slow (or non-existent) internet access? Download the Blockly tutorials that were the precursor of the Code.org tutorials - a single 3MB ZIP file can be loaded onto any computer or used off a memory stick Blockly Games … https://blockly-games.appspot.com/ App Inventor … http://appinventor.mit.edu/explore/ Code (div.) … https://code.org/ Ozo Blockly (Mini-Roboter) - Ozobot Bit robot using the OzoBlockly editor. … http://ozoblockly.com/ micro:bit (Raspberrs Pi, MicroPython) … http://microbit.org/ BlocklyProp … www.parallax.com/product/program-blocklyprop wonder workshop (dash-Roboter) … www.makewonder.de Robertar, NEPO (div.) … https://lab.open-roberta.org// Made w/ Code (div.
    [Show full text]
  • Research Manual
    MOBILE FORENSICS APPLICATION Research Manual Student: Connor Scanlan – C00226867 Supervisor: James Egan Cybercrime & IT Security – CW_KCCYB_B Institute of Technology Carlow Table of Contents Abstract .................................................................................................. 3 Introduction ............................................................................................. 3 Research ................................................................................................. 4 The need for better Mobile Forensics tools ......................................................... 4 Use of mobile phones to store and transmit sensitive information ........................... 4 Online transactions .................................................................................. 5 Law Enforcement and Criminals ................................................................... 5 Mobile Data as Evidence ............................................................................... 6 Definition of Digital Evidence ...................................................................... 6 Principles of Electronic Evidence .................................................................. 6 Framework of Mobile Forensics....................................................................... 8 Mobile Forensics System Structure ................................................................ 8 Mobile Forensics Processes ......................................................................... 9 Mobile Data Collection
    [Show full text]
  • Instalación Wxpython Y Pyo En Thonny
    Instalaci´on wxPython y pyo en Thonny Inform´aticaIII ISM - UNL [email protected] updated: 29 ago 2018 ´Indice 1. Introducci´on 2 2. Instalaci´onen Windows 7/8.1/10 (32 y 64 bits) 3 2.1. Reconocer arquitectura del Sistema Operativo . .3 2.2. Instalar paquetes de MS Visual C++ . .3 2.3. Instalar wxPython con Thonny .........................................4 2.4. Instalar pyo en Thonny . .5 2.5. Instalaci´onde wxFormBuilder .........................................6 3. Instalaci´onen Linux (Ubuntu 16.04 64 bits) 8 3.1. Prerrequisitos . .8 3.2. Instalar wxPython en Thonny .........................................8 3.3. Instalar pyo en Thonny . 10 3.4. Instalaci´onde wxFormBuilder ......................................... 12 4. Instalaci´onen MacOSX (Sierra 10.12 - 64 bits) 13 4.1. Instalar wxPython con Thonny ......................................... 13 4.2. Instalar pyo con Thonny ............................................ 14 4.3. Instalaci´onde wxFormBuilder ......................................... 16 1. Introducci´on En este documento se intentar´adar los pasos para la instalaci´onde wxPython y pyo en la interfaz Thonny. wxPython (https://wxpython.org) es un conjunto de librer´ıasgr´aficaspara Python que permite la interacci´on entre el usuario y componentes GUI (Graphical User Interface) de manera tal que se pueda programar ventanas, botones, listas, menu´es,facilitando as´ıla interacci´onentre el usuario y los programas. Por otro lado, pyo (http://ajaxsoundstudio.com/software/pyo) es un m´odulode Python dise~nadopor Olivier Belanger (PhD en Composici´onElectroac´usticadel Ajax Sound Studio, de Montreal, Canad´a)para procesamiento digital de se~nales(o DSP - Digital Signal Processing) que se utilizar´apara sintetizar, filtrar y generar efectos de audio utilizando Python.
    [Show full text]
  • Python Intro #1
    Python Intro #1 Python is a popular programming language. It was created by Guido van Rossum, and released in 1991. It is used for: • web development (server-side), • software development, • mathematics, • system scripting. What can Python do? • Python can be used on a server to create web applications. • Python can be used alongside software to create workflows. • Python can connect to database systems. It can also read and modify files. • Python can be used to handle big data and perform complex mathematics. • Python can be used for rapid prototyping, or for production-ready software development. Why Python? • Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc). • Python has a simple syntax similar to the English language. • Python has syntax that allows developers to write programs with fewer lines than some other programming languages. • Python runs on an interpreter system, meaning that code can be executed as soon as it is written. This means that prototyping can be very quick. • Python can be treated in a procedural way, an object-orientated way or a functional way. Good to know • The most recent major version of Python is Python 3, which we shall be using in this tutorial. However, Python 2, although not being updated with anything other than security updates, is still quite popular. • In this tutorial Python will be written in a text editor. It is possible to write Python in an Integrated Development Environment, such as Thonny, Pycharm, Netbeans or Eclipse which are particularly useful when managing larger collections of Python files. • Python Syntax compared to other programming languages • Python was designed for readability, and has some similarities to the English language with influence from mathematics.
    [Show full text]
  • Python Programming
    Python Programming 1. Python 3 (v3.8.1) 2. Visual Studio Code (ext. Python, Code Runner) 3. Anaconda Distribution 4. PyCharm (The Python IDE for Professional Developers) Overview Python is an object-oriented programming language created by Guido Rossum in February 1991. It is ideally designed for rapid prototyping of complex applications. It has interfaces to many OS system calls and libraries and is extensible to C or C++. Many large companies use the Python programming language include NASA, Google, YouTube, BitTorrent, etc. Python is a general-purpose language. It has wide range of applications from Web Development (like: Django and Bottle), Scientific And Mathematical Computing (Orange, SymPy, NumPy) to Desktop Graphical User Interfaces (Pygame, Panda3D). The syntax of the language is clean and length of the code is relatively short. It's fun to work in Python because it allows you to think about the problem rather than focusing on the syntax. Python is the fastest growing programming language Most Wanted Programming Languages PYPL PopularitY of Programming Language Most Popular Programming Languages 1965 - 2019 Audience This lecture has been prepared for the beginners to help them understand the basic to advanced concepts related to Python Programming language. Class Prerequisites Before you start doing practice with various types of examples given in this reference, I'm making an assumption that you are already aware about what is a computer program and what is a computer programming language. Course Goals Python Programming course will prepare you for jobs and careers connected with widely understood software development, which includes not only creating the code itself as a junior developer, but also computer systems design and software testing.
    [Show full text]
  • Comparative Studies of Six Programming Languages
    Comparative Studies of Six Programming Languages Zakaria Alomari Oualid El Halimi Kaushik Sivaprasad Chitrang Pandit Concordia University Concordia University Concordia University Concordia University Montreal, Canada Montreal, Canada Montreal, Canada Montreal, Canada [email protected] [email protected] [email protected] [email protected] Abstract Comparison of programming languages is a common topic of discussion among software engineers. Multiple programming languages are designed, specified, and implemented every year in order to keep up with the changing programming paradigms, hardware evolution, etc. In this paper we present a comparative study between six programming languages: C++, PHP, C#, Java, Python, VB ; These languages are compared under the characteristics of reusability, reliability, portability, availability of compilers and tools, readability, efficiency, familiarity and expressiveness. 1. Introduction: Programming languages are fascinating and interesting field of study. Computer scientists tend to create new programming language. Thousand different languages have been created in the last few years. Some languages enjoy wide popularity and others introduce new features. Each language has its advantages and drawbacks. The present work provides a comparison of various properties, paradigms, and features used by a couple of popular programming languages: C++, PHP, C#, Java, Python, VB. With these variety of languages and their widespread use, software designer and programmers should to be aware
    [Show full text]