Introduction to Python

Size: px
Start display at page:

Download "Introduction to Python"

Transcription

1 Introduction to Python Michael Krisper Thomas Wurmitzer March 22, 2014 Michael Krisper, Thomas Wurmitzer Introduction to Python March 22, / 27

2 Schedule Tutorium Dates & Deadlines Submission System Assignment I: Example (Short) Python Introduction networkx, numpy & matplotlib Disclaimer Edited but mostly based on Michael Krisper s Python Introduction (with permission). Thank you! Michael Krisper, Thomas Wurmitzer Introduction to Python March 22, / 27

3 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 Michael Krisper, Thomas Wurmitzer Introduction to Python March 22, / 27

4 Installation We use Python Python 3 is not supported (but may 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 Michael Krisper, Thomas Wurmitzer Introduction to Python March 22, / 27

5 Writing Python using REAL $EDITOR Figure 1: Michael Krisper, Thomas Wurmitzer Introduction to Python March 22, / 27

6 Better than hoverboards! Figure 2: Michael Krisper, Thomas Wurmitzer Introduction to Python March 22, / 27

7 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 March 22, / 27

8 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 March 22, / 27

9 Writing Python: Calculations (interactive 5 ) % python Python (default, Mar , 22:15:05) >>> 3+4 # output: 7 >>> 5*3.7+1 # output: 19.5 >>> 2**3-1 # output: 7 >>> 5**70 # output: L >>> 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 Hint: from future import division Before: 3/2 -> 1, After: 3/2 -> https: //docs.python.org/2/tutorial/interpreter.html#invoking-the-interpreter Michael Krisper, Thomas Wurmitzer Introduction to Python March 22, / 27

10 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 March 22, / 27

11 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 # Michael Krisper, Thomas Wurmitzer Introduction to Python March 22, / 27

12 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 Michael Krisper, Thomas Wurmitzer Introduction to Python March 22, / 27

13 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: '5a' >>> int('5a', 16) # 90 >>> float('3.14') # 3.14 >>> type('434') # <type 'str'> >>> type(434) # <type 'int'> Michael Krisper, Thomas Wurmitzer Introduction to Python March 22, / 27

14 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 Michael Krisper, Thomas Wurmitzer Introduction to Python March 22, / 27

15 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 Michael Krisper, Thomas Wurmitzer Introduction to Python March 22, / 27

16 Writing Python: Built-in Datatypes (Excerpt) int Integer 42 Bool Boolean: True, False True Long Long Integer L Float Double 3.85 Complex Complex Number ( j) 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 March 22, / 27

17 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, Michael Krisper, Thomas Wurmitzer Introduction to Python March 22, / 27

18 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 Michael Krisper, Thomas Wurmitzer Introduction to Python March 22, / 27

19 Control Flow 13 if points < 3 or 'bird' is not word: print "Erm, seriously?" elif points < 10: print "Seriously?" else: print "Good job!" for word in ['ham', 'sausage', 'spam']: print word for i, word in enumerate(['ham', 'sausage', 'spam']): print i, word while answer < 42: answer += Michael Krisper, Thomas Wurmitzer Introduction to Python March 22, / 27

20 Functions 14 def say(string): print string >>> say('hello') # Output: Hello >>> say # Output: <function say at 0x > >>> s = say >>> s('hodor!') # Output: Hodor! 14 https: //docs.python.org/2/tutorial/controlflow.html#defining-functions Michael Krisper, Thomas Wurmitzer Introduction to Python March 22, / 27

21 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 Michael Krisper, Thomas Wurmitzer Introduction to Python March 22, / 27

22 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 March 22, / 27

23 (Common) Exceptions 17 >>> 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 17 Michael Krisper, Thomas Wurmitzer Introduction to Python March 22, / 27

24 JSON 18 The json module provides methods for easily reading and writing data from and to files. import json json_string = '{'list': [1,2,3,4], 'key': 'value', 'truth': 42 }' content = json.loads(json_string) print contents['truth'] # output: 42 print contents['key'] # output: value print contents['list'] # output: [1,2,3,4] 18 Michael Krisper, Thomas Wurmitzer Introduction to Python March 22, / 27

25 networkx 19 The networkx module/library provides functionality to create, analyze and draw complex networks. import networkx as nx G = nx.graph() G.add_node(1) G.add_edge(1, 2) G.add_edge(2, 3) import matplotlib.pylab as plot plot.figure() nx.draw(g) plot.savefig("graph.png") 19 http: //networkx.github.io/documentation/latest/tutorial/tutorial.html Michael Krisper, Thomas Wurmitzer Introduction to Python March 22, / 27

26 Help & Resources Use help and dir in interactive mode. Library Documentation: networkx, numpy, matplotlib Python Language Reference Google s Python Class Think Python: How to Think Like a Computer Scientist Code Academy s Python Track The Hitchhiker s Guide to Python! StackOverflow Reddit Michael Krisper, Thomas Wurmitzer Introduction to Python March 22, / 27

27 Questions? 1 Ask now. 2 Ask in the newsgroup tu-graz.lv.web-science. 3 Send an Dominik Mösslang, dominik.moesslang@student.tugraz.at Ingo Holzmann, ingo.holzmann@student.tugraz.at Emanuel Lacić, emanuel.lacic@tugraz.at Thomas Wurmitzer, t.wurmitzer@student.tugraz.at Please use [WSWT] or the course number as a subject. Please post general questions regarding the assignment tasks to the tu-graz.lv.web-science. If you have a particular, specific problem, you can contact us per as well. Answering delays might be longer, though. Michael Krisper, Thomas Wurmitzer Introduction to Python March 22, / 27

Introduction to Python

Introduction to Python 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

More information

The current topic: Python. Announcements. Python. Python

The current topic: Python. Announcements. Python. Python The current topic: Python Announcements! Introduction! reasons for studying languages! language classifications! simple syntax specification Object-oriented programming: Python Types and values Syntax

More information

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

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D 1/58 Interactive use $ python Python 2.7.5 (default, Mar 9 2014, 22:15:05) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin Type "help", "copyright", "credits" or "license" for more information.

More information

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

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D 1/60 Interactive use $ python Python 2.7.5 (default, Mar 9 2014, 22:15:05) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin Type "help", "copyright", "credits" or "license" for more information.

More information

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

Outline. Simple types in Python Collections Processing collections Strings Tips. 1 On Python language. 2 How to use Python. 3 Syntax of Python Outline 1 On Python language 2 3 4 Marcin Młotkowski Object oriented programming 1 / 52 On Python language The beginnings of Pythons 90 CWI Amsterdam, Guido van Rossum Marcin Młotkowski Object oriented

More information

Advanced Python. Executive Summary, Session 1

Advanced Python. Executive Summary, Session 1 Advanced Python Executive Summary, Session 1 OBJECT: a unit of data of a particular type with characteristic functionality (i.e., methods and/or use with operators). Everything in Python is an object.

More information

Exercise: The basics - variables and types

Exercise: The basics - variables and types Exercise: The basics - variables and types Aim: Introduce python variables and types. Issues covered: Using the python interactive shell Creating variables Using print to display a variable Simple arithmetic

More information

Control Structures 1 / 17

Control Structures 1 / 17 Control Structures 1 / 17 Structured Programming Any algorithm can be expressed by: Sequence - one statement after another Selection - conditional execution (not conditional jumping) Repetition - loops

More information

Beyond Blocks: Python Session #1

Beyond Blocks: Python Session #1 Beyond Blocks: Session #1 CS10 Spring 2013 Thursday, April 30, 2013 Michael Ball Beyond Blocks : : Session #1 by Michael Ball adapted from Glenn Sugden is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike

More information

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 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 FO R K I D S A P l ay f u l I n t r o d u c t i o n to P r o g r a m m i n g Jason R. Briggs Index Symbols and Numbers + (addition operator), 17 \ (backslash) to separate lines of code, 235 in strings,

More information

Exercise: The basics - variables and types

Exercise: The basics - variables and types Exercise: The basics - variables and types Aim: Introduce python variables and types. Issues covered: Using the python interactive shell In the python interactive shell you don t need print Creating variables

More information

Getting Started with Python

Getting Started with Python Fundamentals of Programming (Python) Getting Started with Python Sina Sajadmanesh Sharif University of Technology Some slides have been adapted from Python Programming: An Introduction to Computer Science

More information

Python for C programmers

Python for C programmers Python for C programmers The basics of Python are fairly simple to learn, if you already know how another structured language (like C) works. So we will walk through these basics here. This is only intended

More information

Fundamentals of Programming (Python) Getting Started with Programming

Fundamentals of Programming (Python) Getting Started with Programming Fundamentals of Programming (Python) Getting Started with Programming Ali Taheri Sharif University of Technology Some slides have been adapted from Python Programming: An Introduction to Computer Science

More information

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

(IUCAA, Pune)   kaustubh[at]iucaa[dot]ernet[dot]in. Basics of Python - 2 by Kaustubh Vaghmare (IUCAA, Pune) E-mail: kaustubh[at]iucaa[dot]ernet[dot]in 1 of 54 Sunday 16 February 2014 05:30 PM Our First Program - Rewritten! Let us introduce the following

More information

Table of Contents EVALUATION COPY

Table of Contents EVALUATION COPY Table of Contents Introduction... 1-2 A Brief History of Python... 1-3 Python Versions... 1-4 Installing Python... 1-5 Environment Variables... 1-6 Executing Python from the Command Line... 1-7 IDLE...

More information

Scripting Languages. Python basics

Scripting Languages. Python basics Scripting Languages Python basics Interpreter Session: python Direct conversation with python (>>>) Python 3.5.2 (default, Nov 23 2017, 16:37:01) [GCC 5.4.0 20160609] on linux Type "help", "copyright",

More information

CSCE 110 Programming I

CSCE 110 Programming I CSCE 110 Programming I Basics of Python (Part 3): Functions, Lists, For Loops, and Tuples Dr. Tiffani L. Williams Department of Computer Science and Engineering Texas A&M University Spring 2014 Tiffani

More information

Comp Exam 1 Overview.

Comp Exam 1 Overview. Comp 170-400 Exam 1 Overview. Resources During the Exam The exam will be closed book, no calculators or computers, except as a word processor. In particular no Python interpreter running in a browser or

More information

Introduction to Python

Introduction to Python Introduction to Python CB2-101 Introduction to Scientific Computing November 11 th, 2014 Emidio Capriotti http://biofold.org/emidio Division of Informatics Department of Pathology Python Python high-level

More information

A Little Python Part 1. Introducing Programming with Python

A Little Python Part 1. Introducing Programming with Python A Little Python Part 1 Introducing Programming with Python Preface Not a complete course in a programming language Many details can t be covered Need to learn as you go My programming style is not considered

More information

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

1 Classes. 2 Exceptions. 3 Using Other Code. 4 Problems. Sandeep Sadanandan (TU, Munich) Python For Fine Programmers May 16, / 19 1 Classes 2 Exceptions 3 Using Other Code 4 Problems Sandeep Sadanandan (TU, Munich) Python For Fine Programmers May 16, 2009 1 / 19 Start with an Example Python is object oriented Everything is an object

More information

Types, lists & functions

Types, lists & functions Week 2 Types, lists & functions Data types If you want to write a program that allows the user to input something, you can use the command input: name = input (" What is your name? ") print (" Hello "+

More information

Python. Executive Summary

Python. Executive Summary Python Executive Summary DEFINITIONS OBJECT: a unit of data of a particular type with characteristic functionality (i.e., methods and/or response to operators). Everything in Python is an object. "atomic"

More information

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

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines. Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

APT Session 2: Python

APT Session 2: Python APT Session 2: Python Laurence Tratt Software Development Team 2017-10-20 1 / 17 http://soft-dev.org/ What to expect from this session: Python 1 What is Python? 2 Basic Python functionality. 2 / 17 http://soft-dev.org/

More information

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

Course May 18, Advanced Computational Physics. Course Hartmut Ruhl, LMU, Munich. People involved. SP in Python: 3 basic points May 18, 2017 3 I/O 3 I/O 3 I/O 3 ASC, room A 238, phone 089-21804210, email hartmut.ruhl@lmu.de Patrick Böhl, ASC, room A205, phone 089-21804640, email patrick.boehl@physik.uni-muenchen.de. I/O Scientific

More information

Large-Scale Networks

Large-Scale Networks Large-Scale Networks 3b Python for large-scale networks Dr Vincent Gramoli Senior lecturer School of Information Technologies The University of Sydney Page 1 Introduction Why Python? What to do with Python?

More information

Introduction to Python

Introduction to Python Introduction to Python Jon Kerr Nilsen, Dmytro Karpenko Research Infrastructure Services Group, Department for Research Computing, USIT, UiO Why Python Clean and easy-to-understand syntax alldata = cpickle.load(open(filename1,

More information

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

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming 2017 Table of contents 1 2 Integers and floats Integer int and float float are elementary numeric types in. integer >>> a=1 >>> a 1 >>> type (a) Integers and floats Integer int and float

More information

Python Workshop. January 18, Chaitanya Talnikar. Saket Choudhary

Python Workshop. January 18, Chaitanya Talnikar. Saket Choudhary Chaitanya Talnikar Saket Choudhary January 18, 2012 Python Named after this : Python Slide 1 was a joke! Python Slide 1 was a joke! Python : Conceived in late 1980s by Guido van Rossum as a successor to

More information

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

[Software Development] Python (Part A) Davide Balzarotti. Eurecom Sophia Antipolis, France [Software Development] Python (Part A) Davide Balzarotti Eurecom Sophia Antipolis, France 1 Homework Status 83 registered students 41% completed at least one challenge 5 command line ninjas 0 python masters

More information

CS Advanced Unix Tools & Scripting

CS Advanced Unix Tools & Scripting & Scripting Spring 2011 Hussam Abu-Libdeh slides by David Slater March 4, 2011 Hussam Abu-Libdeh slides by David Slater & Scripting Python An open source programming language conceived in the late 1980s.

More information

Python Tutorial. Day 1

Python Tutorial. Day 1 Python Tutorial Day 1 1 Why Python high level language interpreted and interactive real data structures (structures, objects) object oriented all the way down rich library support 2 The First Program #!/usr/bin/env

More information

Some material adapted from Upenn cmpe391 slides and other sources

Some material adapted from Upenn cmpe391 slides and other sources Some material adapted from Upenn cmpe391 slides and other sources History Installing & Running Python Names & Assignment Sequences types: Lists, Tuples, and Strings Mutability Understanding Reference Semantics

More information

Python 1: Intro! Max Dougherty Andrew Schmitt

Python 1: Intro! Max Dougherty Andrew Schmitt Python 1: Intro! Max Dougherty Andrew Schmitt Computational Thinking Two factors of programming: The conceptual solution to a problem. Solution syntax in a programming language BJC tries to isolate and

More information

At full speed with Python

At full speed with Python At full speed with Python João Ventura v0.1 Contents 1 Introduction 2 2 Installation 3 2.1 Installing on Windows............................ 3 2.2 Installing on macos............................. 5 2.3

More information

Introduction to Scientific Python, CME 193 Jan. 9, web.stanford.edu/~ermartin/teaching/cme193-winter15

Introduction to Scientific Python, CME 193 Jan. 9, web.stanford.edu/~ermartin/teaching/cme193-winter15 1 LECTURE 1: INTRO Introduction to Scientific Python, CME 193 Jan. 9, 2014 web.stanford.edu/~ermartin/teaching/cme193-winter15 Eileen Martin Some slides are from Sven Schmit s Fall 14 slides 2 Course Details

More information

Python. Karin Lagesen.

Python. Karin Lagesen. Python Karin Lagesen karin.lagesen@bio.uio.no Plan for the day Basic data types data manipulation Flow control and file handling Functions Biopython package What is programming? Programming: ordered set

More information

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

ECE 364 Software Engineering Tools Lab. Lecture 3 Python: Introduction ECE 364 Software Engineering Tools Lab Lecture 3 Python: Introduction 1 Introduction to Python Common Data Types If Statements For and While Loops Basic I/O Lecture Summary 2 What is Python? Python is

More information

Variable and Data Type I

Variable and Data Type I Islamic University Of Gaza Faculty of Engineering Computer Engineering Department Lab 2 Variable and Data Type I Eng. Ibraheem Lubbad September 24, 2016 Variable is reserved a location in memory to store

More information

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

Python for Finance. Introduction and Basics of Python. Andras Niedermayer Python for Finance Introduction and Basics of Python Andras Niedermayer Outline 1 Introduction 2 Why Python? 3 Python installation and environments 4 First Steps in Python 5 Variables 6 Basic Operations

More information

#11: File manipulation Reading: Chapter 7

#11: File manipulation Reading: Chapter 7 CS 130R: Programming in Python #11: File manipulation Reading: Chapter 7 Contents File manipulation Text ASCII files Binary files - pickle Exceptions File manipulation Electronic files Files store useful

More information

Getting Started Values, Expressions, and Statements CS GMU

Getting Started Values, Expressions, and Statements CS GMU Getting Started Values, Expressions, and Statements CS 112 @ GMU Topics where does code go? values and expressions variables and assignment 2 where does code go? we can use the interactive Python interpreter

More information

Python Programming. Introduction Part II

Python Programming. Introduction Part II Python Programming Introduction Part II Type Conversion One data type > another data type Example: int > float, int > string. >>> a = 5.5 >>> b = int(a) >>> print(b) 5 >>>> print(a) 5.5 Conversion from

More information

Introduction to Machine Learning. Useful tools: Python, NumPy, scikit-learn

Introduction to Machine Learning. Useful tools: Python, NumPy, scikit-learn Introduction to Machine Learning Useful tools: Python, NumPy, scikit-learn Antonio Sutera and Jean-Michel Begon September 29, 2016 2 / 37 How to install Python? Download and use the Anaconda python distribution

More information

Python - Variable Types. John R. Woodward

Python - Variable Types. John R. Woodward Python - Variable Types John R. Woodward Variables 1. Variables are nothing but named reserved memory locations to store values. This means that when you create a variable you reserve some space in memory.

More information

Programming in Python

Programming in Python 3. Sequences: Strings, Tuples, Lists 15.10.2009 Comments and hello.py hello.py # Our code examples are starting to get larger. # I will display "real" programs like this, not as a # dialog with the Python

More information

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

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

Python debugging and beautification

Python debugging and beautification Python debugging and beautification #!/usr/bin/env python # # # THIS CODE DOES NOT WORK import sys def read(a): myfile = open(a,'r'): for i in myfile: yield i myfile.close() def count_chars(a): sum = 0

More information

Variable and Data Type I

Variable and Data Type I The Islamic University of Gaza Faculty of Engineering Dept. of Computer Engineering Intro. To Computers (LNGG 1003) Lab 2 Variable and Data Type I Eng. Ibraheem Lubbad February 18, 2017 Variable is reserved

More information

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

Sequence types. str and bytes are sequence types Sequence types have several operations defined for them. Sequence Types. Python Python Sequence Types Sequence types str and bytes are sequence types Sequence types have several operations defined for them Indexing Python Sequence Types Each element in a sequence can be extracted

More information

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

CMPT 120 Basics of Python. Summer 2012 Instructor: Hassan Khosravi CMPT 120 Basics of Python Summer 2012 Instructor: Hassan Khosravi Python A simple programming language to implement your ideas Design philosophy emphasizes code readability Implementation of Python was

More information

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

Python The way of a program. Srinidhi H Asst Professor Dept of CSE, MSRIT Python The way of a program Srinidhi H Asst Professor Dept of CSE, MSRIT 1 Problem Solving Problem solving means the ability to formulate problems, think creatively about solutions, and express a solution

More information

Try and Error. Python debugging and beautification

Try and Error. Python debugging and beautification Try and Error Python debugging and beautification What happens when something goes wrong Catching exceptions In order to handle errors, you can set up exception handling blocks in your code. The keywords

More information

Introduction to Python

Introduction to Python Introduction to Python Reading assignment: Perkovic text, Ch. 1 and 2.1-2.5 Python Python is an interactive language. Java or C++: compile, run Also, a main function or method Python: type expressions

More information

61A Lecture 2. Friday, August 28, 2015

61A Lecture 2. Friday, August 28, 2015 61A Lecture 2 Friday, August 28, 2015 Names, Assignment, and User-Defined Functions (Demo) Types of Expressions Primitive expressions: 2 add 'hello' Number or Numeral Name String Call expressions: max

More information

And Parallelism. Parallelism in Prolog. OR Parallelism

And Parallelism. Parallelism in Prolog. OR Parallelism Parallelism in Prolog And Parallelism One reason that Prolog is of interest to computer scientists is that its search mechanism lends itself to parallel evaluation. In fact, it supports two different kinds

More information

Class extension and. Exception handling. Genome 559

Class extension and. Exception handling. Genome 559 Class extension and Exception handling Genome 559 Review - classes 1) Class constructors - class MyClass: def init (self, arg1, arg2): self.var1 = arg1 self.var2 = arg2 foo = MyClass('student', 'teacher')

More information

Introduction to Python. Dmytro Karpenko Research Infrastructure Services Group, Department for Research Computing, USIT, UiO

Introduction to Python. Dmytro Karpenko Research Infrastructure Services Group, Department for Research Computing, USIT, UiO Introduction to Python Dmytro Karpenko Research Infrastructure Services Group, Department for Research Computing, USIT, UiO Research Computing Services tutorial and courses November 3-7, 2014 Why python

More information

Python and Bioinformatics. Pierre Parutto

Python and Bioinformatics. Pierre Parutto Python and Bioinformatics Pierre Parutto October 9, 2016 Contents 1 Common Data Structures 2 1.1 Sequences............................... 2 1.1.1 Manipulating Sequences................... 2 1.1.2 String.............................

More information

MEIN 50010: Python Introduction

MEIN 50010: Python Introduction : Python Fabian Sievers Higgins Lab, Conway Institute University College Dublin Wednesday, 2017-10-04 Outline Goals Teach basic programming concepts Apply these concepts using Python Use Python Packages

More information

Python Intro GIS Week 1. Jake K. Carr

Python Intro GIS Week 1. Jake K. Carr GIS 5222 Week 1 Why Python It s simple and easy to learn It s free - open source! It s cross platform IT S expandable!! Why Python: Example Consider having to convert 1,000 shapefiles into feature classes

More information

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

Python review. 1 Python basics. References. CS 234 Naomi Nishimura Python review CS 234 Naomi Nishimura The sections below indicate Python material, the degree to which it will be used in the course, and various resources you can use to review the material. You are not

More information

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

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes GIS 4653/5653: Spatial Programming and GIS More Python: Statements, Types, Functions, Modules, Classes Statement Syntax The if-elif-else statement Indentation and and colons are important Parentheses and

More information

Exception Handling. Genome 559

Exception Handling. Genome 559 Exception Handling Genome 559 Review - classes Use your own classes to: - package together related data - conceptually organize your code - force a user to conform to your expectations Class constructor:

More information

STSCI Python Introduction. Class URL

STSCI Python Introduction. Class URL STSCI Python Introduction Class 2 Jim Hare Class URL www.pst.stsci.edu/~hare Each Class Presentation Homework suggestions Example files to download Links to sites by each class and in general I will try

More information

18.1. CS 102 Unit 18. Python. Mark Redekopp

18.1. CS 102 Unit 18. Python. Mark Redekopp 18.1 CS 102 Unit 18 Python Mark Redekopp 18.2 Credits Many of the examples below are taken from the online Python tutorial at: http://docs.python.org/tutorial/introduction.html 18.3 Python in Context Two

More information

STA141C: Big Data & High Performance Statistical Computing

STA141C: Big Data & High Performance Statistical Computing STA141C: Big Data & High Performance Statistical Computing Lecture 1: Python programming (1) Cho-Jui Hsieh UC Davis April 4, 2017 Python Python is a scripting language: Non-scripting language (C++. java):

More information

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

Python I. Some material adapted from Upenn cmpe391 slides and other sources Python I Some material adapted from Upenn cmpe391 slides and other sources Overview Names & Assignment Data types Sequences types: Lists, Tuples, and Strings Mutability Understanding Reference Semantics

More information

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

Introduction to Python. Genome 559: Introduction to Statistical and Computational Genomics Prof. James H. Thomas Introduction to Python Genome 559: Introduction to Statistical and Computational Genomics Prof. James H. Thomas If you have your own PC, download and install a syntax-highlighting text editor and Python

More information

A Little Python Part 3

A Little Python Part 3 A Little Python Part 3 Introducing Programming with Python I/O, Files, Object Classes, Exception Handling Outline I/O Files opening File I/O, reading writing Python Objects Defining a new object Inheritance

More information

Class extension and. Exception handling. Genome 559

Class extension and. Exception handling. Genome 559 Class extension and Exception handling Genome 559 Review - classes 1) Class constructors - class myclass: def init (self, arg1, arg2): self.var1 = arg1 self.var2 = arg2 foo = myclass('student', 'teacher')

More information

Python Programming, bridging course 2011

Python Programming, bridging course 2011 Python Programming, bridging course 2011 About the course Few lectures Focus on programming practice Slides on the homepage No course book. Using online resources instead. Online Python resources http://www.python.org/

More information

A Little Python Part 2

A Little Python Part 2 A Little Python Part 2 Introducing Programming with Python Data Structures, Program Control Outline Python and the System Data Structures Lists, Dictionaries Control Flow if, for, while Reminder - Learning

More information

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

Computer Sciences 368 Scripting for CHTC Day 3: Collections Suggested reading: Learning Python Day 3: Collections Suggested reading: Learning Python (3rd Ed.) Chapter 8: Lists and Dictionaries Chapter 9: Tuples, Files, and Everything Else Chapter 13: while and for Loops 1 Turn In Homework 2 Homework

More information

CIS192 Python Programming. Robert Rand. August 27, 2015

CIS192 Python Programming. Robert Rand. August 27, 2015 CIS192 Python Programming Introduction Robert Rand University of Pennsylvania August 27, 2015 Robert Rand (University of Pennsylvania) CIS 192 August 27, 2015 1 / 30 Outline 1 Logistics Grading Office

More information

Introduction to Python (All the Basic Stuff)

Introduction to Python (All the Basic Stuff) Introduction to Python (All the Basic Stuff) 1 Learning Objectives Python program development Command line, IDEs, file editing Language fundamentals Types & variables Expressions I/O Control flow Functions

More information

Python Programming: Lecture 2 Data Types

Python Programming: Lecture 2 Data Types Python Programming: Lecture 2 Data Types Lili Dworkin University of Pennsylvania Last Week s Quiz 1..pyc files contain byte code 2. The type of math.sqrt(9)/3 is float 3. The type of isinstance(5.5, float)

More information

Python: A great programming toolkit

Python: A great programming toolkit Python: A great programming toolkit Asokan Pichai Prabhu Ramachandran Department of Aerospace Engineering IIT Bombay 25, July 2009 Acknowledgements This program is conducted by IIT, Bombay through CDEEP

More information

Basic Python 3 Programming (Theory & Practical)

Basic Python 3 Programming (Theory & Practical) Basic Python 3 Programming (Theory & Practical) Length Delivery Method : 5 Days : Instructor-led (Classroom) Course Overview This Python 3 Programming training leads the student from the basics of writing

More information

Programming to Python

Programming to Python Programming to Python Sept., 5 th Slides by M. Stepp, M. Goldstein, M. DiRamio, and S. Shah Compiling and interpreting Many languages require you to compile (translate) your program into a form that the

More information

Programming in Python

Programming in Python Programming in Python Session-I Indian Institute of Space Science and Technology Thiruvananthapuram, Kerala, India 695547 IEEE Student Branch & Computer Science and Engineering Club, IIST Workshop plan

More information

Physics 514 Basic Python Intro

Physics 514 Basic Python Intro Physics 514 Basic Python Intro Emanuel Gull September 8, 2014 1 Python Introduction Download and install python. On Linux this will be done with apt-get, evince, portage, yast, or any other package manager.

More information

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

Introductory Linux Course. Python I. Martin Dahlö UPPMAX. Author: Nina Fischer. Dept. for Cell and Molecular Biology, Uppsala University Introductory Linux Course Martin Dahlö UPPMAX Author: Nina Fischer Dept. for Cell and Molecular Biology, Uppsala University August, 2018 Outline Python basics get started with Python Data types Control

More information

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

Abstract Data Types. CS 234, Fall Types, Data Types Abstraction Abstract Data Types Preconditions, Postconditions ADT Examples Abstract Data Types CS 234, Fall 2017 Types, Data Types Abstraction Abstract Data Types Preconditions, Postconditions ADT Examples Data Types Data is stored in a computer as a sequence of binary digits:

More information

CIS192: Python Programming

CIS192: Python Programming CIS192: Python Programming Introduction Harry Smith University of Pennsylvania January 18, 2017 Harry Smith (University of Pennsylvania) CIS 192 Lecture 1 January 18, 2017 1 / 34 Outline 1 Logistics Rooms

More information

Built-in Types of Data

Built-in Types of Data Built-in Types of Data Types A data type is set of values and a set of operations defined on those values Python supports several built-in data types: int (for integers), float (for floating-point numbers),

More information

Strengthen Your Python Foundations

Strengthen Your Python Foundations Strengthen Your Python Foundations The code examples that are provided along with the chapters don't require you to master Python. However, they will assume that you previously obtained a working knowledge

More information

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

Python Essential Reference, Second Edition - Chapter 5: Control Flow Page 1 of 8 Python Essential Reference, Second Edition - Chapter 5: Control Flow Page 1 of 8 Chapter 5: Control Flow This chapter describes related to the control flow of a program. Topics include conditionals, loops,

More information

UNIVERSITÀ DI PADOVA. < 2014 March >

UNIVERSITÀ DI PADOVA. < 2014 March > UNIVERSITÀ DI PADOVA < 2014 March > Easy-to-learn: Python has relatively few keywords, simple structure, and a clearly defined syntax. Easy-to-read: Python code is much more clearly defined and visible

More information

Data Handing in Python

Data Handing in Python Data Handing in Python As per CBSE curriculum Class 11 Chapter- 3 By- Neha Tyagi PGT (CS) KV 5 Jaipur(II Shift) Jaipur Region Introduction In this chapter we will learn data types, variables, operators

More information

Python for Non-programmers

Python for Non-programmers Python for Non-programmers A Gentle Introduction 1 Yann Tambouret Scientific Computing and Visualization Information Services & Technology Boston University 111 Cummington St. yannpaul@bu.edu Winter 2013

More information

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

Constants. Variables, Expressions, and Statements. Variables. x = 12.2 y = 14 x = 100. Chapter Variables, Expressions, and Statements Chapter 2 Unless otherwise noted, the content of this course material is licensed under a Creative Commons Attribution 3.0 License. http://creativecommons.org/licenses/by/3.0/.

More information

Introduction to Python for Plone developers

Introduction to Python for Plone developers Plone Conference, October 15, 2003 Introduction to Python for Plone developers Jim Roepcke Tyrell Software Corporation What we will learn Python language basics Where you can use Python in Plone Examples

More information

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

Introduction to Python. Genome 559: Introduction to Statistical and Computational Genomics Prof. James H. Thomas Introduction to Python Genome 559: Introduction to Statistical and Computational Genomics Prof. James H. Thomas If you have your own PC, download and install a syntax-highlighting text editor and Python

More information

Algorithms and Programming I. Lecture#12 Spring 2015

Algorithms and Programming I. Lecture#12 Spring 2015 Algorithms and Programming I Lecture#12 Spring 2015 Think Python How to Think Like a Computer Scientist By :Allen Downey Installing Python Follow the instructions on installing Python and IDLE on your

More information

Python for Finance. Control Flow, data structures and first application (part 2) Andras Niedermayer

Python for Finance. Control Flow, data structures and first application (part 2) Andras Niedermayer Python for Finance Control Flow, data structures and first application (part 2) Andras Niedermayer Outline 1 Control Flow 2 Modules 3 Data types and structures. Working with arrays and matrices. 4 Numpy

More information

CSC148 Fall 2017 Ramp Up Session Reference

CSC148 Fall 2017 Ramp Up Session Reference Short Python function/method descriptions: builtins : input([prompt]) -> str Read a string from standard input. The trailing newline is stripped. The prompt string, if given, is printed without a trailing

More information

Teaching London Computing

Teaching London Computing Teaching London Computing A Level Computer Science Topic 3: Advanced Programming in Python William Marsh School of Electronic Engineering and Computer Science Queen Mary University of London Aims Further

More information