Introduction to Python

Similar documents
Introduction to Python

The current topic: Python. Announcements. Python. Python

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

Outline. Simple types in Python Collections Processing collections Strings Tips. 1 On Python language. 2 How to use Python. 3 Syntax of Python

Exercise: The basics - variables and types

Advanced Python. Executive Summary, Session 1

Beyond Blocks: Python Session #1

Exercise: The basics - variables and types

Getting Started with Python

Fundamentals of Programming (Python) Getting Started with Programming

Table of Contents EVALUATION COPY

Python for C programmers

Scripting Languages. Python basics

CSCE 110 Programming I

Control Structures 1 / 17

PYTHON FOR KIDS A Pl ayfu l I ntrodu ctio n to Prog r am m i ng J a s o n R. B r i g g s

Python. Executive Summary

(IUCAA, Pune) kaustubh[at]iucaa[dot]ernet[dot]in.

Introduction to Python

A Little Python Part 1. Introducing Programming with Python

Python 1: Intro! Max Dougherty Andrew Schmitt

Comp Exam 1 Overview.

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming

Python and Bioinformatics. Pierre Parutto

Python at Glance. a really fast (but complete) ride into the Python hole. Paolo Bellagente - ES3 - DII - UniBS

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Some material adapted from Upenn cmpe391 slides and other sources

1 Classes. 2 Exceptions. 3 Using Other Code. 4 Problems. Sandeep Sadanandan (TU, Munich) Python For Fine Programmers May 16, / 19

Python. Karin Lagesen.

Sequence types. str and bytes are sequence types Sequence types have several operations defined for them. Sequence Types. Python

Programming in Python

ECE 364 Software Engineering Tools Lab. Lecture 3 Python: Introduction

Variable and Data Type I

#11: File manipulation Reading: Chapter 7

Getting Started Values, Expressions, and Statements CS GMU

[Software Development] Python (Part A) Davide Balzarotti. Eurecom Sophia Antipolis, France

Course May 18, Advanced Computational Physics. Course Hartmut Ruhl, LMU, Munich. People involved. SP in Python: 3 basic points

Python Workshop. January 18, Chaitanya Talnikar. Saket Choudhary

At full speed with Python

Python - Variable Types. John R. Woodward

Large-Scale Networks

Python Tutorial. Day 1

Variable and Data Type I

Python debugging and beautification

18.1. CS 102 Unit 18. Python. Mark Redekopp

Computer Sciences 368 Scripting for CHTC Day 3: Collections Suggested reading: Learning Python

Types, lists & functions

A Little Python Part 2

Try and Error. Python debugging and beautification

Introduction to Python (All the Basic Stuff)

Senthil Kumaran S

Python for Finance. Introduction and Basics of Python. Andras Niedermayer

And Parallelism. Parallelism in Prolog. OR Parallelism

Class extension and. Exception handling. Genome 559

Programming to Python

CIS192: Python Programming

Introduction to Python

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

Python Intro GIS Week 1. Jake K. Carr

Python for Non-programmers

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

Python review. 1 Python basics. References. CS 234 Naomi Nishimura

Introduction to Python

CMPT 120 Basics of Python. Summer 2012 Instructor: Hassan Khosravi

Python I. Some material adapted from Upenn cmpe391 slides and other sources

CSCE 110 Programming I

Python Programming: Lecture 2 Data Types

Introduction to Python. Genome 559: Introduction to Statistical and Computational Genomics Prof. James H. Thomas

CHAPTER 2: Introduction to Python COMPUTER PROGRAMMING SKILLS

Python The way of a program. Srinidhi H Asst Professor Dept of CSE, MSRIT

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Basic Python 3 Programming (Theory & Practical)

Idioms and Anti-Idioms in Python

CIS192 Python Programming. Robert Rand. August 27, 2015

Python Programming. Introduction Part II

Play with Python: An intro to Data Science

APT Session 2: Python

EE 355 Unit 17. Python. Mark Redekopp

Python Essential Reference, Second Edition - Chapter 5: Control Flow Page 1 of 8

MEIN 50010: Python Introduction

CS Programming Languages: Python

Strengthen Your Python Foundations

STSCI Python Introduction. Class URL

CS Advanced Unix Tools & Scripting

Jython. secondary. memory

61A Lecture 2. Friday, August 28, 2015

Introduction to Python

Constants. Variables, Expressions, and Statements. Variables. x = 12.2 y = 14 x = 100. Chapter

STA141C: Big Data & High Performance Statistical Computing

Exception Handling. Genome 559

Introductory Linux Course. Python I. Martin Dahlö UPPMAX. Author: Nina Fischer. Dept. for Cell and Molecular Biology, Uppsala University

Introduction to Python. Genome 559: Introduction to Statistical and Computational Genomics Prof. James H. Thomas

Class extension and. Exception handling. Genome 559

Teaching London Computing

Babu Madhav Institute of Information Technology, UTU 2015

Introduction to programming with Python

History Installing & Running Python Names & Assignment Sequences types: Lists, Tuples, and Strings Mutability

Abstract Data Types. CS 234, Fall Types, Data Types Abstraction Abstract Data Types Preconditions, Postconditions ADT Examples

Transcription:

Introduction to Python Michael Krisper Thomas Wurmitzer October 21, 2014 Michael Krisper, Thomas Wurmitzer Introduction to Python October 21, 2014 1 / 26

Schedule Tutorium I Dates & Deadlines Submission System Map/Reduce Example Introduction to Python (1) Tutorium II Introduction to Python (2) Questions Disclaimer Edited but mostly based on Michael Krisper s Python Introduction (with permission). Thank you! Michael Krisper, Thomas Wurmitzer Introduction to Python October 21, 2014 2 / 26

What is Python? Python is a dynamic, interpreted language. Source code does not declare the types of variables or parameters or methods. This makes the code short and flexible, and you lose the compile-time type checking in the source code. Python tracks the types of all values at runtime and flags code that does not make sense as it runs. 1 Huge standard library and community. Huge list of 3rd party libraries 2. If you want to know more about Python s history checkout Guido s Blog 3 on that topic. 1 https://developers.google.com/edu/python/introduction 2 https://github.com/vinta/awesome-python 3 http://python-history.blogspot.co.at Michael Krisper, Thomas Wurmitzer Introduction to Python October 21, 2014 3 / 26

Installation We use Python 2.7 - Python 3 is not supported and will most likely not work. Linux: Most distributions already come with Python 2.7. If not install them via your distributions packagemanager e.g. (pacman, apt,...) OSX: All recent versions ship with Python 2.7 out of the box. Windows: Windows Installer via python.org and check out the Windows FAQ 4. 4 https://docs.python.org/2/faq/windows.html Michael Krisper, Thomas Wurmitzer Introduction to Python October 21, 2014 4 / 26

Writing Python using REAL $EDITOR Figure 1: https://xkcd.com/378 Michael Krisper, Thomas Wurmitzer Introduction to Python October 21, 2014 5 / 26

Better than hoverboards! Figure 2: https://xkcd.com/353/ Michael Krisper, Thomas Wurmitzer Introduction to Python October 21, 2014 6 / 26

Writing Python: Hello World % cat hello.py print Hello World % python hello.py # Run code inside file Hello World % python -c "print Hello World " # Pass program as string. % python # Interactive Mode % ipython #... on steroids Michael Krisper, Thomas Wurmitzer Introduction to Python October 21, 2014 7 / 26

Writing Python: Hello World (Extended) #!/usr/bin/env python import sys import math def my_function(message): print message return math.e # return constant from module if name == main : if len(sys.argv) < 2: sys.exit(1) result = my_function(sys.argv[1]) print math.ceil(result) # function in module Michael Krisper, Thomas Wurmitzer Introduction to Python October 21, 2014 8 / 26

Writing Python: Calculations (interactive 5 ) % python Python 2.7.5 (default, Mar 9 2014, 22:15:05) [...] Type "help", "copyright", "credits" or "license" for more info >>> 3+4 # output: 7 >>> 5*3.7+1 # output: 19.5 >>> 2**3-1 # output: 7 >>> 5**70 # output: 847032947254...13916015625L >>> 3/2 # output: 1 >>> 3/2.0 # output: 1.5 >>> 3.0//4.0 # output: 0.0 >>> 5*"a" # output: "aaaaa" >>> 3+4 == 2**3-1 # output: True 5 https: //docs.python.org/2/tutorial/interpreter.html#invoking-the-interpreter Michael Krisper, Thomas Wurmitzer Introduction to Python October 21, 2014 9 / 26

Writing Python: Variables & Assignments >>> a Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name a is not defined >>> a = 42 # integer >>> a 42 >>> type(a) # output: <type int > >>> a += 1 # increase a by one >>> b = 1.78 # float >>> c = "Hello" # string >>> d = [1,2,3,4] # list >>> e = (1,2,3) # tuple >>> f, g = True, None Michael Krisper, Thomas Wurmitzer Introduction to Python October 21, 2014 10 / 26

Writing Python: Bool 67 bool(none) # False bool(0) # False bool({}) # False bool([]) # False bool("") # False bool(1) # True bool([1,2,3,4]) # True bool("hello") # True #... Python on Love a a https://twitter.com/johl/status/318494068365733889 >>> import this >>> love = this >>> this is love, love is not True or False, love is love >>> (True, True, True) Michael 6 Krisper, Thomas Wurmitzer Introduction to Python October 21, 2014 11 / 26

Writing Python: Strings 8 >>> s = Hello World >>> s = "Hello World" >>> s = """ Hello World """ # Multiline # Strings are Sequences >>> lie in believe # output: True >>> execute.find( cute ) # output: 3 >>> foo + bar # output: foobar >>> \n\nvalar Dohaeris.strip() # output: Valar Dohaeris >>> A;B;C\n;D.split( ; ) # output: [ A, B, C\n, D ] >>> help(str) 8 http://docs.python.org/2/library/stdtypes.html#string-methods Michael Krisper, Thomas Wurmitzer Introduction to Python October 21, 2014 12 / 26

Writing Python: Conversion >>> str(434) # 434 >>> int( 956 ) # 956 >>> int( \n\n210 \r\n ) # 210 >>> int( 5a ) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for int() with base 10: >>> int( 5a, 16) # 90 5a >>> float( 3.14 ) # 3.14 >>> type( 434 ) # <type str > >>> type(434) # <type int > Michael Krisper, Thomas Wurmitzer Introduction to Python October 21, 2014 13 / 26

Writing Python: Lists 9 >>> a = [4, 8, 15] # list definition >>> a[0] # get first element >>> len(a) # length of the list >>> a[1:3] # get a slice by range >>> a[-1] # get last element >>> a.append(16) # append element >>> a += [55, 23, 42] # concat lists >>> a.remove(55) # remove an element >>> del a[5] # delete element on index >>> sorted(a) # sort the list 9 https://docs.python.org/2/tutorial/datastructures.html Michael Krisper, Thomas Wurmitzer Introduction to Python October 21, 2014 14 / 26

Writing Python: Dictionary 10 >>> d = { "key": "value", "key2": "value2" } >>> d["key"] >>> d.keys() >>> d.values() >>> d["key3"] = 45 >>> "key" in d >>> len(d) >>> d.get("nokey", "default") # = "default" >>> d.setdefault ("nokey", "default") 10 https://docs.python.org/2/tutorial/datastructures.html Michael Krisper, Thomas Wurmitzer Introduction to Python October 21, 2014 15 / 26

Writing Python: Built-in Datatypes (Excerpt) int Integer 42 Bool Boolean: True, False True Long Long Integer 10000000000000000L Float Double 3.85 Complex Complex Number (3.1+0.9j) Str String Jaqen H ghar List List / Array [1, 2, 5.5, "asdf", 0] Dict Dictionary {"a":"foo", "b":"bar"} Set Set Set([1, 2, 1, 3, True]) Tuple Tuple (1, 2, None, True, 4) Michael Krisper, Thomas Wurmitzer Introduction to Python October 21, 2014 16 / 26

Writing Python: Built-in Functions 11 (Excerpt) len(...) max(...)/min(...) open(...) print input(...) range(...)/xrange(...) sorted(...) sum(...) type(...) Get length of a sequence Get max / min element of a sequence Open a file for read/write Output to console Read from console Create a counter sequence Sort a sequence Calculate the sum of a sequence Get the type of a variable Others: abs, dir, eval, format, hash, help, next, enumerate, ord, map, reduce, slice, unicode, zip, apply,... 11 https://docs.python.org/2/library/functions.html#built-in-funcs Michael Krisper, Thomas Wurmitzer Introduction to Python October 21, 2014 17 / 26

Writing Python: Built-in Functions 12 (Excerpt) print "Valar morghulis" # with newline print "Valar morghulis", # without newline print "a = ", 1, " b = ", 2 print "a = %d b = %d" % (1,2) print "{} of {}".format( mother, dragons ) import sys sys.stdout.write("who wrote the pink letter?") 12 https://docs.python.org/2/library/functions.html#built-in-funcs Michael Krisper, Thomas Wurmitzer Introduction to Python October 21, 2014 18 / 26

Control Flow 13 if points < 10 or bird is not word: print "Erm, seriously?" elif points < 40: print "Seriously?" else: print "Good job!" for word in [ ham, sausage, spam ]: print word while answer < 42: answer +=1 Additionally statements like pass, break or continue can be used to further control the above. 13 https://docs.python.org/2/tutorial/controlflow.html Michael Krisper, Thomas Wurmitzer Introduction to Python October 21, 2014 19 / 26

Functions 14 def say(string): print string >>> say( Hello ) # Output: Hello >>> say # Output: <function say at 0x102697938> >>> s = say >>> s( Hodor! ) # Output: Hodor! 14 https: //docs.python.org/2/tutorial/controlflow.html#defining-functions Michael Krisper, Thomas Wurmitzer Introduction to Python October 21, 2014 20 / 26

Classes 15 class Human(object): # Inherits from object def init (self, name): # Constructor self.name = name def speak(self): print self.name, ": Valar Morghulis." jh = Human("Jaqen H ghar"); jh.speak() 15 https://docs.python.org/2/tutorial/classes.html Michael Krisper, Thomas Wurmitzer Introduction to Python October 21, 2014 21 / 26

File I/O 16 fh = open( filename.txt, r ) lines = fh.readlines() fh.close() with open( filename.txt, w ) as f: f.write("\n" % ) with open( filename.txt, w ) as f: f.write("%d + %d = %d\n" % (2,3,2+3)) f.write("another line\n") f.write("another line\n") 16 https: //docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files Michael Krisper, Thomas Wurmitzer Introduction to Python October 21, 2014 22 / 26

DateTime 17 >>> import datetime >>> a = datetime.datetime(2014, 10, 26, 9, 15, 10) >>> b = datetime.datetime(2024, 10, 26, 9, 15, 10) >>> type(a) # Output: <type datetime.datetime > >>> a # 26.10.2014 09:15:10 >>> a < b # Output: True >>> st = "2013-11-06 09:57:52" >>> ft = "%Y-%m-%d %H:%M:%S" >>> c = datetime.datetime.strptime(st, ft) >>> type(c) # Output: <type datetime.datetime > >>> c # 06.11.2013 09:57:52 >>> 2013-11-06 09:57:52 < 2013-11-06 10:57:52 #??? >>> 2013-11-06 09:57:52 > 2013-11-06 10:57:52 #??? 17 http://docs.python.org/2/library/datetime.html Michael Krisper, Thomas Wurmitzer Introduction to Python October 21, 2014 23 / 26

(Common) Exceptions 18 >>> 2 + Hodor! Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for +: int and str >>> 2 + a Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name a is not defined >>> while Hodor print "Hodor!" File "<stdin>", line 1 while Hodor print "Hodor!" ^ SyntaxError: invalid syntax 18 https://docs.python.org/2/tutorial/errors.html Michael Krisper, Thomas Wurmitzer Introduction to Python October 21, 2014 24 / 26

Help & Resources Use help and dir in interactive mode. Python Language Reference I https://docs.python.org/2/reference/index.html Google s Python Class I https://developers.google.com/edu/python/ Think Python: How to Think Like a Computer Scientist I http://www.greenteapress.com/thinkpython/ Code Academy s Python Track I http://www.codecademy.com/en/tracks/python StackOverflow I http://stackoverflow.com/questions/tagged/python Reddit http://reddit.com/r/python http://reddit.com/r/learnpython Michael Krisper, Thomas Wurmitzer Introduction to Python October 21, 2014 25 / 26

Questions? email: thomas.wurmitzer@tugraz.at I Please use [DB2] or the course number 707.030 as a subject. Newsgroup: tu-graz.lv.dbase2 Question Hours I I 14.12.2015, 13:00 (HS i9 PZ2EG048) 11.01.2016, 13:00 (HS i9 PZ2EG048) Michael Krisper, Thomas Wurmitzer Introduction to Python October 21, 2014 26 / 26