1. BASICS OF PYTHON. JHU Physics & Astronomy Python Workshop Lecturer: Mubdi Rahman

Similar documents
Computational Mathematics with Python

Computational Mathematics with Python

Computational Mathematics with Python

Introduction to Python

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

Simulation Tools. Python for MATLAB Users I. Claus Führer. Automn Claus Führer Simulation Tools Automn / 65

Exercise 1: Python Language Basics

Exercise 4 Learning Python language fundamentals

CSCE 110 Programming I Basics of Python: Variables, Expressions, and Input/Output

University of Hull Department of Computer Science. Wrestling with Python Week 01 Playing with Python

Introduction to Python

Introduction to Python

Introduction to Python

Unix Shell Scripts. Contents. 1 Introduction. Norman Matloff. July 30, Introduction 1. 2 Invoking Shell Scripts 2

Exercise 0. Although Python(x,y) comes already with a great variety of scientic Python packages, we might have to install additional dependencies:

Objects and classes. Objects and classes. Jarkko Toivonen (CS Department) Programming in Python 1

NLP Programming Tutorial 0 - Programming Basics

Outline Basic concepts of Python language

Welcome to Introduction to programming in Python

Crash Dive into Python

Python Basics. S.R. Doty. August 27, Preliminaries What is Python? Installation and documentation... 4

Python Lists and Loops

Python Loops and String Manipulation

CS 1133, LAB 2: FUNCTIONS AND TESTING

Learn Perl by Example - Perl Handbook for Beginners - Basics of Perl Scripting Language

CRASH COURSE PYTHON. Het begint met een idee

PYTHON Basics

The Clean programming language. Group 25, Jingui Li, Daren Tuzi

ESCI 386 Scientific Programming, Analysis and Visualization with Python. Lesson 5 Program Control

[1] Learned how to set up our computer for scripting with python et al. [3] Solved a simple data logistics problem using natural language/pseudocode.

Python. Python. 1 Python. M.Ulvrova, L.Pouilloux (ENS LYON) Informatique L3 Automne / 25

Lab 4.4 Secret Messages: Indexing, Arrays, and Iteration

Crash Dive into Python

Hands-on Exercise 1: VBA Coding Basics

Introduction to Python

Lecture 5: Java Fundamentals III

Introduction to Microsoft OneNote

Example of a Java program

Lecture 4: Writing shell scripts

2! Multimedia Programming with! Python and SDL

VHDL Test Bench Tutorial

Python for Rookies. Example Examination Paper

PRI-(BASIC2) Preliminary Reference Information Mod date 3. Jun. 2015

Hands-On Python A Tutorial Introduction for Beginners Python 3.1 Version

Problem 1. CS 61b Summer 2005 Homework #2 Due July 5th at the beginning of class

Hypercosm. Studio.

Lab 1: Introduction to C, ASCII ART and the Linux Command Line Environment

Introduction to Python for Text Analysis

VB.NET Programming Fundamentals

ESPResSo Summer School 2012

2Creating Reports: Basic Techniques. Chapter

CIS 192: Lecture 10 Web Development with Flask

Secrets of printf. 1 Background. 2 Simple Printing. Professor Don Colton. Brigham Young University Hawaii. 2.1 Naturally Special Characters

Sources: On the Web: Slides will be available on:

Programming Languages CIS 443

Perl in a nutshell. First CGI Script and Perl. Creating a Link to a Script. print Function. Parsing Data 4/27/2009. First CGI Script and Perl

Introduction to Data Structures

Advanced Tornado TWENTYONE Advanced Tornado Accessing MySQL from Python LAB

AN INTRODUCTION TO UNIX

Certified PHP Developer VS-1054

INFORMATION BROCHURE Certificate Course in Web Design Using PHP/MySQL

High-Level Programming Languages. Nell Dale & John Lewis (adaptation by Michael Goldwasser)

A Python Tour: Just a Brief Introduction CS 303e: Elements of Computers and Programming

Intro to scientific programming (with Python) Pietro Berkes, Brandeis University

JavaScript For Cats. An introduction for new programmers. Table of contents. Don't be a scaredy-cat. So easy your human companion could do it too!

Systems Programming & Scripting

Hands-On UNIX Exercise:

csce4313 Programming Languages Scanner (pass/fail)

B&K Precision 1785B, 1786B, 1787B, 1788 Power supply Python Library

Microsoft Office PowerPoint 2007 Basics Workshop

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

COMP 356 Programming Language Structures Notes for Chapter 4 of Concepts of Programming Languages Scanning and Parsing

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

DATA 301 Introduction to Data Analytics Microsoft Excel VBA. Dr. Ramon Lawrence University of British Columbia Okanagan

Python. KS3 Programming Workbook. Name. ICT Teacher Form. Do you speak Parseltongue?

grep, awk and sed three VERY useful command-line utilities Matt Probert, Uni of York grep = global regular expression print

Pseudo code Tutorial and Exercises Teacher s Version

Microsoft Access 3: Understanding and Creating Queries

Online account access

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

Java Crash Course Part I

CS101 Lecture 24: Thinking in Python: Input and Output Variables and Arithmetic. Aaron Stevens 28 March Overview/Questions

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Tutorial Guide to the IS Unix Service

Introduction to Pig. Content developed and presented by: 2009 Cloudera, Inc.

Notepad++ The COMPSCI 101 Text Editor for Windows. What is a text editor? Install Python 3

Programming Exercises

USING MICROSOFT WORD 2008(MAC) FOR APA TASKS

Turtle Power. Introduction: Python. In this project, you ll learn how to use a turtle to draw awesome shapes and patterns. Activity Checklist

Object Oriented Software Design

Python Evaluation Rules

Like any function, the UDF can be as simple or as complex as you want. Let's start with an easy one...

Computer Science 1 CSci 1100 Lecture 3 Python Functions

Modeling with Python

COMSC 100 Programming Exercises, For SP15

LEARNING TO PROGRAM WITH PYTHON. Richard L. Halterman

Advanced Bash Scripting. Joshua Malone

Creating a Guest Book Using WebObjects Builder

Transcription:

1. BASICS OF PYTHON JHU Physics & Astronomy Python Workshop 2015 Lecturer: Mubdi Rahman

HOW IS THIS WORKSHOP GOING TO WORK? We will be going over all the basics you need to get started and get productive in Python! Please code along with us as we go! There are likely multiple ways of doing many things in Python, but we re going to show you one way. It may not be the best for your particular purposes, but we will try to be self consistent. We will constantly refer you back to the documentation. The packages we have here have far more functionality than the scope of this workshop. If there s something that you want to do, Python likely has a package or function that can do it (or at least make your life easier).

HOW IS THIS WORKSHOP GOING TO WORK? We will be going over all the basics you need to get started and get productive in Python! Please code along with us as we go! There are likely multiple ways of doing many things in Python, but we re going to show you one way. It may not be the best for your particular purposes, but we will try to be self consistent. These boxes will have useful tidbits about python conventions or hints on how to make your coding life easier! We will constantly refer you back to the documentation. The packages we have here have far more functionality than the scope of this workshop. If there s something that you want to do, Python likely has a package or function that can do it (or at least make your life easier).

WHY PYTHON? Open Source/Free: No need to worry about licences Cross-platform: Can be used with Windows/Macs OS/Linux Full-featured Packages: If there s something you want to do, there s probably a package out there to help you Code Portability: With most code, it can run unaltered on a plethora of computers so long as all the required modules are supplied Large and Growing Community: People from all fields from Astronomy to Sociology are coding in Python, creating a diverse and rich community of experts all over.

WHY PYTHON? Open Source/Free: No need to worry about licences Cross-platform: Can be used with Windows/Macs OS/Linux Full-featured Packages: If there s something you want to do, there s probably a package out there to help you In this workshop, we ll be using Python 2, but teach you how to code in Python 3 (which is being slowly adopted across the Code Portability: With most code, it can run unaltered on a plethora of computers so long as all the required modules are supplied Large and Growing Community: People from all fields from Astronomy to Sociology are coding in Python, community) creating a diverse and rich community of experts all over.

RUNNING PYTHON Directly from script: >> python scriptname.py Running a python script from beginning to end in your favourite terminal

RUNNING PYTHON Directly from script: >> python scriptname.py Python scripts traditionally have the extension.py Running a python script from beginning to end in your favourite terminal

RUNNING PYTHON Directly from script: >> python scriptname.py Interactively: >> ipython Opening an ipython process to either run a script, or use as a calculator or both!

RUNNING PYTHON Directly from script: >> python scriptname.py Interactively: >> ipython You can also run straight python Opening an ipython process to either run a interactively, script, or use but as this a is not calculator or both! recommended

RUNNING PYTHON Directly from script: >> python scriptname.py Interactively: >> ipython Running a script once in ipython: In [1]: %run scriptname.py or: In [1]: execfile( scriptname.py )

LEAVING PYTHON If in script: python will automatically exit when script has completed Interactively: just type In [1]: exit Or press: Ctrl-D (on Windows, Linux, and Macs)

LEAVING PYTHON If in script: python will automatically exit when script has completed Interactively: just type In [1]: exit Or press: Ctrl-D (on Windows, Linux, and Macs) Ctrl-C will not exit you out of (i)python, but rather cancel what you are currently doing

INTERACTIVE PYTHON (IPYTHON) A special shell on top of python that makes using it interactively a breeze. It includes such features as: Tab-complete (both functions and variables) Documentation at the push of a? Full history accessible by pressing up and down Variables stay loaded for you to investigate and manipulate

IPYTHON MAGIC WORDS & CHARACTERS To get documentation (for anything): To run a shell command: To run a script file: To time a function: To see your command history: In [1]: functname? In [2]:!cd dirname In [3]: %run scriptname.py In [4]: %timeit command In [5]: %history

IPYTHON MAGIC WORDS & CHARACTERS To get documentation (for anything): To run a shell command: To run a script file: To time a function: To see your command history: In [1]: functname? In [2]:!cd dirname In [3]: %run scriptname.py In [4]: %timeit command In [5]: %history Many basic shell commands (i.e., cd, ls, pwd) work in ipython without the use of the bang (!)

CANOPY: A USEFUL DEVELOPMENT ENVIRONMENT

CANOPY: A USEFUL DEVELOPMENT ENVIRONMENT File Browser

CANOPY: A USEFUL DEVELOPMENT ENVIRONMENT Text Editor

CANOPY: A USEFUL DEVELOPMENT ENVIRONMENT Ipython Terminal

MODULES: THE POWER OF PYTHON The base language of Python is actually quite limited. Most of its power comes from Modules (or sometimes referred to as Packages) Modules must be imported before they can be used: In [1]: import module1 In [2]: import module2, module3 Once imported, you can access functions or variables: In [3]: module1.function1() Importing single or multiple modules on a single line

MODULES: THE POWER OF PYTHON Sometimes typing the module name all the time can be annoying in which case: Creating a shorter name or just getting the function you want In [1]: import module1 as m1 In [2]: from module2 import function2 Once imported, you can access functions or variables: In [3]: m1.function1() In [4]: function2()

MODULES: THE POWER OF PYTHON Sometimes typing the module name all the time can be annoying in which case: Creating a shorter name or just getting In [1]: import module1 as m1 the function you In [2]: from module2 import function2 Some places will show examples want that involve importing all functions in a module by: Once imported, you can access functions or variables: In [3]: m1.function1() In [4]: function2() from module1 import * While this may seem handy, it is dangerous. DON T DO THIS!

INSTALLING NEW MODULES Enthought s Canopy provides the majority of modules you ll want and/or need automatically. But there are modules that you ll likely want to get. Canopy makes this easy using the Package Manager

INSTALLING NEW MODULES Python also makes installing packages easy in general using pip on the command line: C:\Users\Mubdi> pip install packagename This downloads and installs any package available on the (centralized) Python Package Index (PyPI) C:\Users\Mubdi> pip install http://url.goes.here This downloads and installs the package from somewhere on the internet

BASICS OF A SCRIPT: COMMENTS The most important part of any script In [1]: # This is a comment In [2]: # This is also a comment For longer comments (in a script for instance): ''' This text is in a comment So is this text ''' This text is outside a comment

BASICS OF A SCRIPT: COMMENTS Take the comment pledge: I will comment liberally and consistently throughout all code I write, or so help me Python guru.

BASICS OF A SCRIPT: COMMENTS Take the comment pledge: I will comment liberally and consistently throughout all code I write, or so help me Comment. It s the right thing to do. Just do it. Really. Python guru.

BASICS OF A SCRIPT: INDENTATION Python uses indents to indicate blocks of code no brackets! # My schematic python script command 1 command 2 command 3 inner command 1 inner command 2 more inner command 1 inner command 3 command 4

BASICS OF A SCRIPT: INDENTATION Python uses indents to indicate blocks of code no brackets! # My schematic python script command 1 command 2 command 3 inner command 1 inner command 2 more inner command 1 inner command 3 command 4 Let your text editor deal with indenting for you. And when you need to do it yourself, use spaces not tabs.

BASICS OF A SCRIPT: VARIABLES Variables are simple and flexible in python. There is no need to declare any variable type before setting it. And they can be set at any point throughout the script or on the fly (if using it interactively): In [1]: var1 = value # No need to declare In [2]: var2, var3 = value2, value3 In [3]: # Multiple Values can be set at once Anything can be a variable in python: numbers, strings, functions, modules, et cetera. You can check out what type the variable is by: In [3]: type(var1)

BASICS OF A SCRIPT: PRIMITIVE VARIABLES There are only a few built in variables in python: Strings (str) Integers (int) Floats (float) Any form of text. These can be enclosed in single ( ) or double ( ) quotes. They also accept escape characters (i.e., \n, \t, \a) In [1]: var1 = This is a String In [2]: var2 = This is also a String When added, they make a longer string: In [3]: var3 = var1 + var2

BASICS OF A SCRIPT: PRIMITIVE VARIABLES There are only a few built in variables in python: Strings (str) Integers (int) Floats (float) Any integer (, -1, 0, 1, ). Mathematical operations are as you expect In [1]: var1, var2 = 1, 2 They are subject to integer math: In [2]: var1/var2 # will give you 0, not 0.5

BASICS OF A SCRIPT: PRIMITIVE VARIABLES There are only a few built in variables in python: Strings (str) Integers (int) Floats (float) Any integer (, -1, 0, 1, ). Mathematical operations are as you expect In [1]: var1, var2 = 1, 2 They are subject to integer math: In [2]: var1/var2 # will give you 0, not 0.5 Taking an exponent uses the double asterisk character (**): x = y**2

BASICS OF A SCRIPT: PRIMITIVE VARIABLES There are only a few built in variables in python: Strings (str) Integers (int) Floats (float) Any integer (, -1, 0, 1, ). Mathematical operations are as you expect In [1]: var1, var2 = 1, 2 They are subject to integer math: In [2]: var1/var2 # will give you 0, not 0.5 This is the only case throughout this workshop that something will change in Python 3: all math will default to floating point math.

BASICS OF A SCRIPT: PRIMITIVE VARIABLES There are only a few built in variables in python: Strings (str) Integers (int) Floats (float) Any real number (1.0, 2.5, 1e25). Mathematical operations are as you expect In [1]: var1, var2 = 1.0, 2e2 Any operation with an int and a float will give you a float: In [2]: 1/2.0 # will give you 0.5, not 0

BASICS OF A SCRIPT: PRIMITIVE VARIABLES There are only a few built in variables in python: Strings (str) Integers (int) Floats (float) Any real number (1.0, 2.5, 1e25). Mathematical operations are as you expect Every variable in python is an In [1]: var1, var2 = 1.0, 2e2 object that has methods (functions) associated with it. You Any operation with an int and a float will give you a can float: access these with the dot character (.) after the variable In [2]: 1/2.0 # will give you 0.5, name: not 0 var1.method()

BASICS OF A SCRIPT: LISTS Basic ordered grouping of any type of variables: In [1]: list1 = [1, 2, 3] # Lists can contain different types of variables In [2]: list2 = [1, a, 3.4] # You can make lists of lists In [3]: list3 = [1, [ a, b, c ], 3.4] Accessing individual components of a list: In [4]: x = list1[2] # Returns the 3 rd element # Indexing of lists starts at 0 and goes to n-1 In [5]: len(list1) # Gets the size of the list

BASICS OF A SCRIPT: LISTS Useful functions associated with lists: # Create a list of integers from 0 to 3 In [1]: list1 = range(4) # Sort your list In [2]: sortedlist = sort(list2) # Add more to your list In [3]: list3 = list3.append(newvariable) # Combine multiple lists together In [4]: combinedlist = list1 + list2

BASICS OF A SCRIPT: LISTS Useful functions associated with lists: # Create a list of integers from 0 to 3 In [1]: list1 = range(4) # Sort your list In [2]: sortedlist = sort(list2) # Add more to your list In [3]: list3 = list3.append(newvariable) # Combine multiple lists together You can create an empty list to In [4]: combinedlist = list1 + list2 append to: emptylist = []

BASICS OF A SCRIPT: TUPLES Ordered grouping of variables. Not as flexible as lists (not mutable) but the basics are the same: In [1]: tuple1 = (1, 2, 3) In [2]: tuple2 = (1, a, 3.4) In [3]: tuple3 = (1, ( a, b, c ), 3.4) Can also quickly assign values from within tuples: In [4]: tuple4 = (1, 2, 3) In [5]: var1, var2, var3 = tuple4 # also works for lists

BASICS OF A SCRIPT: INDEXING Taking a simple list: 0 1 2 3 4 5 6 7 8 9 list[0] list[5] Simple indexing

BASICS OF A SCRIPT: INDEXING Taking a simple list: 0 1 2 3 4 5 6 7 8 9-10 -9-8 -7-6 -5-4 -3-2 -1 list[-10] list[-5] Inverse indexing

BASICS OF A SCRIPT: INDEXING Taking a simple list: 0 1 2 3 4 5 6 7 8 9 list[1:] Spanning arrays list[5:8] list[1:-1]

BASICS OF A SCRIPT: INDEXING Taking a simple list: 0 1 2 3 4 5 6 7 8 9 list[1:] Spanning arrays The range you choose will exclude the value at the stop number list[5:8] list[1:-1]

BASICS OF A SCRIPT: INDEXING Taking a simple list: 0 1 2 3 4 5 6 7 8 9 list[::2] Changing counting

BASICS OF A SCRIPT: INDEXING Taking a simple list: 0 1 2 3 4 5 6 7 8 9 list[::2] Changing counting To reverse the order of an array, just use: [::-1]

BASICS OF A SCRIPT: DICTIONARIES Unordered grouping of variables accessed by key. Anything can be a key or a value: In [1]: dict1 = { val1 :1, 2:2, val3 :3} In [2]: dict1[ val1 ] # Returns 1 In [3]: dict1[ newval ] = 4 # Add new value Can quickly get all the keys in a dictionary (in a list): In [4]: dict1keys = dict1.keys()

BASICS OF A SCRIPT: FUNCTIONS Making a function is quite simple and can be defined anywhere: def function1(var1, var2): # Your Code goes here var3 = var1 + var2 return var3 You can define optional arguments and return multiple values: def function1(var1, var2= value ): var3 = var1 + var2 return var3, var2 # This will be a tuple

BASICS OF A SCRIPT: FLOW CONTROL Conditional (if-else) statements: if var1 == 0: Code to run if var1 is 0 elif var1 == 1: Code to run if var1 is 1 else: Code to run otherwise

BASICS OF A SCRIPT: FLOW CONTROL While loop: while var1 > 5: Code to run (in a loop) if var1 > 5 For loop: for tmp_var in list1: tmp_var is set to the values in list1 # If you want a for loop with numbers from 0 to N-1: for tmp_var in range(n): Code to run with tmp_var = 1 to N

BASICS OF A SCRIPT: FLOW CONTROL Special keywords when you are within loops or conditionals Skip everything else in this iteration and move to the next: continue Exit out of the most recent loop: break These keywords are usually put in conjuction with an if statement.

BASICS OF A SCRIPT: PRINTING Printing is very easy: In [1]: print( This is a message. ) In [2]: print(variable1) Mixing variables and text is also easy: In [1]: print( This is a %s message. % string ) In [2]: print( %f, %i % (2.0, 2)) # Using tuple In [3]: print( %1.3f % 1.12345) # Prints 1.123

EXERCISE TIME! C is for cookie. That s good enough for me.