Introduction to Python

Size: px
Start display at page:

Download "Introduction to Python"

Transcription

1 Introduction to Python MPBA Fondazione Bruno Kessler Trento Italy Roberto Visintainer 1

2 Intro Python is an open source scripting language. Developed by Guido van Rossum in the early 1990s Named after Monty Python Available for download from Why Python? Who? Rapid prototyping Reduced training time GUI application Portable (Fortran, C) Object oriented Mature language More and more companies and institutions are choosing Python 2

3 Compiled / Interpreted Language Executable Your code { Objects Your Code code Source code { Code Your Code code { } Code Code } Code Code Code } Different Files Line by Line Your code { Code Code } Code Code Compiler Executable Execution Result Interpreter Execution Result 3

4 Compiled / Interpreted Language Compiled: Interpreted: Pros Faster execution Can produce a distributable executable standalone files Pros Steep learning curve Takes automatically care of memory usage Allows fast prototyping Cons More complicated to build (many files) User has to administrate Memory usage Cons Usually slower Does not produce standalone programs 4

5 The Interpreter Interactive Interface to Python $ python Python (r266:84292, Sep , 16:22:56) [GCC 4.4.5] on linux2 Type "help", "copyright", "credits" or "license" for more information. Prompt Python Inputs are Interpreted ((2*6) 7)**2 25 To exit In Unix: Tipe Ctrl + D 5

6 Running programs You can create python programs with a text editor such emacs (using a python editing mode) It is possible to make your <program>.py program executable adding as first line of your code #!/usr/bin/python Execute your program with./<program>.py 6

7 Running programs Interpreter or $ emacs example.py $ chmod u+x example.py $./example.py Program #!/usr/bin/python for i in (1,2,3,4,5): print i 7

8 Main Instructions Allocation / Assignment a = 3 a 3 e = hi e 'hi' 'a' 5 b = 'a' b b = a + 2 b Basic Operations a a a a a a + b b * b / b % b ** b import math math.sqrt(b) math.log(a, base) math.log10(a) math.exp(b) math.degree(b) math.degrees(b) math.radiants(a) math.sin(a) math.cos(b) math.e math.pi help(math) help(math.ceil) 8

9 Control Instructions if Test if <Test> : Commands if <Test> : Commands elif <Test> : Commands If the test (boolean condition) is met Commands are executed Operators: == > < <= >=!= Conditions: and or not if <Test> : Commands else: Commands if <Test> : Commands elif <Test> : Commands else: Commands True / False Booleans: True False 0 # False '' # False [] {} () None # # # # False False False False 9

10 Control Instructions for Loops for i in <Sequence to iterate on> : Commands As far as there are elements in the sequence Commands are executed range(n) function range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] range( 10, 100, 30) [ 10, 40, 70] range(5,10) [5, 6, 7, 8, 9] range( 10, 100, 30) [] range(0,10,3) [0, 3, 6, 9] 10

11 Control Instructions while Loops Keeps running Commands as far as the condition is True (Condition = Boolean Function) while <Stop Condition> : Commands Increment / Decrement a Variable a, step = 1,.5 a += step a a = 2*step a i = 3 r = 0 while i!= 0: r = r + 2 i = 1 r 11

12 Data I/O From File f=open('<path/file>', '<mode>') mode (optional) can be: w write (OVERWRITES) r read (default) a append r+ read and write Read f.readline() txt line f.readlines() [ line, line,...] f.read(<b>) txt # Byte you want to read (default all the text) 12

13 Data I/O From File f.tell() # ask at what position of the file is the reader <position> # in bytes f.seek(<b>,<r>) # (B)yte you move to, (R)eference {0=beginning, # 1=current pos, 2=end} f.close() Write f = open('<path/file>', '<mode>') f.write('string') f.close() Output Formatting %s String print'i have %d %s and %d %s' % (2,'cats', 3, 'dogs') %d Int I have 2 cats and 3 dogs %f Float print 'dogs divided by cats %f' % (3/2.) Dogs divided by cats

14 Types of Variables type String 'A' + ' string' 'A string' 'A string'[3] # like a list 't' S = 'A string' S[3] = 't' # ERROR! # unlike list Numbers type type type type int : 0, 5, 9 # Up to 8 Bytes long : 0L, 5L, 9L float : 0.,.5, , 5.2e+9 complex : 5+6j (j= 1 ) NB.: Conversion string float is not automatic: b = '1.4' # b is a string 2.4 * b # ERROR! 2.4 * float(b) # WORKS 14

15 Types of Variables More on Numbers 1 b = '1.4' int(b) b = float(b) c = int(b) c a, b = 1, 2 a/2 0 a, b = 1, 2. a/b 0.5 # # # # b is a string ERROR Can't convert Conversion string float IT WORKS BY TRUNCATION # Initialize 2 int # Operations between int and int # GIVES ALWAYS AN INT # Initialize 1 int and 1 float # Operations between int and float # GIVES A FLOAT 15

16 Types of Variables Lists [ ] and Tuples ( ) L = ['1.4',1.4,'ciao',[1,2,3]] T = ('1.4',1.4,'ciao',[1,2,3]) L T L[2] T[2] len(t) len(l) L[1] = 4 L ['1.4', 4, 'ciao', [1, 2, 3]] T[1] = 4 # initialization of # initialization of # read list # read tuple # read third element # read third element # returns the length # returns the length # change element list tuple of T of L # ERROR! TUPLES ARE IMMUTABLE 16

17 Types of Variables more on Lists [ ] L = ['1.4',1.4,'ciao',[1,2,3]] L.append(<element>) L.remove(<element>) L.index(<element>) # Initialization of list # Adds <element> in the last # Place of the list # Removes the first <element> # from the list # Returns the position of the # first <element> of the list # # # L.insert(<position>, <element>) # # # L.sort() # L.reverse() # L.pop(<position>) Returns and eliminates the element in <position> (default <last position>). Inserts <element> in <position> Sorts the elements Reverses the order of the elements 17

18 Types of Variables more on Lists [ ] Slicing L = ['a','b','c','d','e','f','g','h'] L[4] 'e' L[ 1] L[:] 'h' ['a','b','c','d','e','f','g','h'] L[ 3] L[2:5] 'f' ['c', 'd', 'e'] L[ 3: 1] L[3:] ['f', 'g'] ['d', 'e', 'f', 'g', 'h'] L [1:4] = [] L[:3] L ['a', 'b', 'c'] ['a', 'e', 'f', 'g', 'h'] L[3] = L[3]+'igi' ['a', 'e', 'f', 'gigi', 'h'] 18

19 Types of Variables Iterating on List for item in L:... print 'the item is ',item for idx, it in enumerate(l):... print 'pos: ',idx,'val: ',it # At each iteration item takes # one of the values of L # At each iteration idx takes the value of # the position of L, it takes the value of # the item for idx in range(len(l)):... print 'L[%d] = %s' % (idx, L[idx]) 19

20 Types of Variables Dictionaries { } Is a kind of list where the index, referred to as key, can be an arbitrary text (any immutable object) # Initialization D = {} D['TEL NUM'] = ' ' D['HEIGHT'] = 1.90 D['WEIGHT'] = 100 D['GIRL'] = 'Brunilde' D['HOBY'] = ('python', 'guitar', 'beer') 20

21 Types of Variables Main Operations D['GIRL'] D.keys() # Extracts key corresponding to key GIRL # Returns a copy of list of keys D.has.key('COLOR') 'COLOR' in D # Does D have key davidecol? # Same test as above D.get('GIRL', 1.0) # As D['GIRL'] but returns 1.0 # in case the key does not exist D.items() # Returns a list of (key,value) # tuple del D['GIRL'] # Delete item len(d) # Returns the number of items 21

22 Functions What are they? A Function is a portion of code within a larger program that performs a specific task and is relatively independent of the remaining code. Can be called several times and/or from several places during a single execution including from other functions. What are they for? Judicious use of functions help a structured programming approach. Will heavily reduce the time for the development and maintenance of a large program, while increasing its quality and reliability. Functions, often collected into libraries, are an important mechanism for sharing and trading software. The discipline of object-oriented programming is based on objects and methods 22

23 Functions Function definition begins with def Function Name Function Arguments Colon def myfunction( <arg0>, a = <arg1>, b = <arg2> ): ''' < Documentation String > ''' <commandline 0> <commandline 1> return <something> indentation Key word return indicates the value to send back to the caller 23

24 Functions Function Variables are local: in general all variables allocated in a function are destroyed upon return. def myfun (a, b, c): d = a+b e = d*c return e RES = myfun(1,2,3) RES d # ERROR!! e # ERROR!! # definition # allocation of d # allocation of e NameError: name 'd' is not defined NameError: name 'e' is not defined 24

25 Functions Arguments Positional: they need to be passed to the function they need to be passed in the right order def power( a, b ): ''' returns a^b ''' c = a**b return c power (2,10)!= power (10,2) def sumsub( lnum, a ): ''' lnum + or a ''' for i in range(len(lnum)): if lnum[i] > 0: lnum[i] = lnum[i]+a elif lnum[i] < 0: lnum[i] = lnum[i] a return lnum sumsub(list, 10) OK sumsub(10, list) ERROR!! 25

26 Functions Arguments keyword arguments or named arguments: def wfile(filename, text, nlines = 10, mode = 'w' ): channel = open(filename, mode) for i in range(nlines): Default channel.write(text + '\n') channel.close() Call: wfile('intro','hi, my name is Mario',nlines =10,mode = 'w') Useless 26

27 Functions Variable number of Arguments def fwrite(file, L): channel = open(file, 'w') for i in L: channel.write(i + '\n') channel.close() Call: fwrite('intro',['hi,','my name is Mario','and I am','a farmer']) 27

28 Modules A module is a file containing Python definitions and statements. The file name is the module name with the suffix.py appended. # Fibonacci numbers module def fib(n): # write Fibonacci series up to n a, b = 0, 1 while b < n: print b, a, b = b, a+b def fib2(n): # return Fibonacci series up to n result = [] a, b = 0, 1 while b < n: result.append(b) a, b = b, a+b return result create a file called fibo.py and write this code in it 28

29 Modules How to use a module import fibo # Using the module name you can access the functions fibo.fib(1000) fibo.fib2(1000) # This does not enter the names of the functions defined # in fibo directly in the current symbol table import fibo as fi fi.fib(1000) fi.fib2(1000) # As before, but very useful for functions used very often # or modules with long names NB.: Modules can import other modules. Put the import statements at the beginning of a module or script. ref.: 29

30 Modules More on How to use a module from fibo import fib, fib2 fib(1000) fib2(1000) # It is like cutting and pasting the definition of the functions in your code To import all the functions of a library: from fibo import * fib(1000) fib2(1000) These last two are deprecated because the reduce the readability of the code and could cover other functions without knowing it. import fibo as fi Normally If you change your module, you have to restart the interpreter to use the modified functions, or you can use: fi=reload(fi) Remember the function help(<modulename>) 30

31 Classes What Are They? A class defines the structure and the behavior of an object are defined by, which is a definition, or model, of all objects of a specific type. Why Should we use them? Example: Library We could define a Class book, each object of this class will have a 31

32 Classes What Are They? A class defines the structure and the behavior of an object are defined by, which is a definition, or model, of all objects of a specific type. Why Should we use them? Example: Library We could define a Class book, each object of this class will have a Attributes State (structure): Title Author Number of Pages List People who borrowed Presence/Absence Modules (functions): Borrow Return Is the Book Available? 32

33 Classes What Are They? A class defines the structure and the behavior of an object are defined by, which is a definition, or model, of all objects of a specific type. Why Should we use them? Example: Library We could define a Class book, each object of this class will have a Attributes State (structure): Title Author Never Change Number of Pages List People who borrowed Presence/Absence Modules (functions): Borrow Return Is the Book Available? Returns Yes/No 33

34 Classes Class Definition class MyClass: "A simple example class" def init (self): DEFINE STRUCTURE def f(self): DEFINE METHODS 34

35 Classes Class Definition Class Instantiation class MyClass: "A simple example class" def init (self): self.i = def f(self): return 'hello world' x = MyClass() Creates a new instance of the class and assigns this object to the local variable x. Use the structure of x x.i x.f() hello world 35

36 Classes Class Definition e = 123 class Test: def init (self): self.e = 5 def go(self): print e class Test2: def init (self): self.e = 5 def go(self): print self.e Class Instantiation x = Test() x2 = Test2() x.go() 123 x2.go() 5 self indicates the Object itself. self.e indicates the Attribute of the Object (reachable because self is in passed to the function) 36

37 Classes Class Definition class Bag: def init (self): self.data = [] def add(self, x): self.data.append(x) def addtwice(self, x): self.add(x) self.add(x) Recursions are ALLOWED Class Instantiation MULTIUPLE Instantiations Handag = Bag() Backpack = Bag() Suitcase = Bag() 37

38 Classes Class Definition class MyClass2: ''' A simple class to increase and subtract ''' def init (self, orig): self.i = orig def tellme(self): return self.i def increase(self, p): self.i = self.i + p def decrease (self, m): self.i = self.i m Class Instantiation goofy = MyClass2(10) Use the Object goofy: goofy.tellme() 10 goofy.increase(15) goofy.tellme() 25 goofy.decrease(50) goofy.tellme() 25 38

39 Classes Class Definition class MyClass2: A simple class to increase and subtract def init (self, orig): self.i = orig def tellme(self): "A comment on tellme()" return self.i def increase(self, m): A comment on increase() self.i = self.i + m def decrease (self, m): A comment on decrease() self.i = self.i m # Comments on DOCUMENTATION!!! Writing undocumented code is a waste of time because nobody else will be able to use it. goofy = MyClass2() Help! goofy. doc help(paperino) line 39

40 Classes class arithmetic: def init (self, first, second): self.a = first self.b = second def times(self): c = self.a * self.b return c def division(self): c = self.a/self.b return c QUESTIONS: goofy = arithmetic(3,6) goofy.division() >>?? goofy = arithmetic('ciccio', 6) goofy.times() >>?? goofy.division() >>?? >> ERROR?? 40

41 References Official Website: Official Tutorial: Official Documentation: Cookbook: Google 41

Introduction to Python

Introduction to Python Introduction to Python www.python.org MPBA Fondazione Bruno Kessler Trento Italy Roberto Visintainer visintainer@fbk.eu 1 Intro Python is an open source scripting language. Developed by Guido van Rossum

More information

Python. Jae-Gil Lee Based on the slides by K. Naik, M. Raju, and S. Bhatkar. December 28, Outline

Python. Jae-Gil Lee Based on the slides by K. Naik, M. Raju, and S. Bhatkar. December 28, Outline Python Jae-Gil Lee Based on the slides by K. Naik, M. Raju, and S. Bhatkar December 28, 2011 1 Outline Introduction Installation and Use Distinct Features Python Basics Functional Example Comparisons with

More information

Senthil Kumaran S

Senthil Kumaran S Senthil Kumaran S http://www.stylesen.org/ Agenda History Basics Control Flow Functions Modules History What is Python? Python is a general purpose, object-oriented, high level, interpreted language Created

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

Data type built into Python. Dictionaries are sometimes found in other languages as associative memories or associative arrays.

Data type built into Python. Dictionaries are sometimes found in other languages as associative memories or associative arrays. NETB 329 Lecture 4 Data Structures in Python Dictionaries Data type built into Python. Dictionaries are sometimes found in other languages as associative memories or associative arrays. 1 of 70 Unlike

More information

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

History Installing & Running Python Names & Assignment Sequences types: Lists, Tuples, and Strings Mutability History Installing & Running Python Names & Assignment Sequences types: Lists, Tuples, and Strings Mutability Some material adapted from Upenn cmpe391 slides and other sources Invented in the Netherlands,

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

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

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

Introduction to Python Part 1. Brian Gregor Research Computing Services Information Services & Technology

Introduction to Python Part 1. Brian Gregor Research Computing Services Information Services & Technology Introduction to Python Part 1 Brian Gregor Research Computing Services Information Services & Technology RCS Team and Expertise Our Team Scientific Programmers Systems Administrators Graphics/Visualization

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

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

Organization of Programming Languages CS 3200/5200D. Lecture 12

Organization of Programming Languages CS 3200/5200D. Lecture 12 Organization of Programming Languages CS 3200/5200D Razvan C. Bunescu School of Electrical Engineering and Computer Science bunescu@ohio.edu Scripting Languages: Python Designed by Guido van Rossum in

More information

381 INTRODUCTION TO PYTHON SUSHIL J. LOUIS

381 INTRODUCTION TO PYTHON SUSHIL J. LOUIS 381 INTRODUCTION TO PYTHON SUSHIL J. LOUIS PYTHON - FROM MONTY PYTHON Guido Van Rossum started implementing in 1989. BDFL. We will be using Python 2.6.4 Easy to learn, powerful, interpreted language Dynamic

More information

PYTHON FOR MEDICAL PHYSICISTS. Radiation Oncology Medical Physics Cancer Care Services, Royal Brisbane & Women s Hospital

PYTHON FOR MEDICAL PHYSICISTS. Radiation Oncology Medical Physics Cancer Care Services, Royal Brisbane & Women s Hospital PYTHON FOR MEDICAL PHYSICISTS Radiation Oncology Medical Physics Cancer Care Services, Royal Brisbane & Women s Hospital TUTORIAL 1: INTRODUCTION Thursday 1 st October, 2015 AGENDA 1. Reference list 2.

More information

Python Basics. Nakul Gopalan With help from Cam Allen-Lloyd

Python Basics. Nakul Gopalan With help from Cam Allen-Lloyd Python Basics Nakul Gopalan ngopalan@cs.brown.edu With help from Cam Allen-Lloyd 1 Introduction to the idea Readable, easy to learn programming language. Created by Guido van Rossum Named after the BBC

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

Python: Short Overview and Recap

Python: Short Overview and Recap Python: Short Overview and Recap Benjamin Roth CIS LMU Benjamin Roth (CIS LMU) Python: Short Overview and Recap 1 / 39 Data Types Object type Example creation Numbers (int, float) 123, 3.14 Strings this

More information

Flow Control: Branches and loops

Flow Control: Branches and loops Flow Control: Branches and loops In this context flow control refers to controlling the flow of the execution of your program that is, which instructions will get carried out and in what order. In the

More information

Shell / Python Tutorial. CS279 Autumn 2017 Rishi Bedi

Shell / Python Tutorial. CS279 Autumn 2017 Rishi Bedi Shell / Python Tutorial CS279 Autumn 2017 Rishi Bedi Shell (== console, == terminal, == command prompt) You might also hear it called bash, which is the most widely used shell program macos Windows 10+

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

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

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

[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

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

Accelerating Information Technology Innovation

Accelerating Information Technology Innovation Accelerating Information Technology Innovation http://aiti.mit.edu Cali, Colombia Summer 2012 Lesson 1 Introduction to Python Agenda What is Python? and Why Python? Basic Syntax Strings User Input Useful

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

Accelerating Information Technology Innovation

Accelerating Information Technology Innovation Accelerating Information Technology Innovation http://aiti.mit.edu/program/philippines-summer-2012/ Philippines Summer 2012 Lecture 1 Introduction to Python June 19, 2012 Agenda About the Course What is

More information

Question 1. Part (a) Part (b) December 2013 Final Examination Marking Scheme CSC 108 H1F. [13 marks] [4 marks] Consider this program:

Question 1. Part (a) Part (b) December 2013 Final Examination Marking Scheme CSC 108 H1F. [13 marks] [4 marks] Consider this program: Question 1. Part (a) [4 marks] Consider this program: [13 marks] def square(x): (number) -> number Write what this program prints, one line per box. There are more boxes than you need; leave unused ones

More information

Introduction to Python. Prof. Steven Ludtke

Introduction to Python. Prof. Steven Ludtke Introduction to Python Prof. Steven Ludtke sludtke@bcm.edu 1 8512 documented lanuages (vs. 2376) Four of the first modern languages (50s): FORTRAN (FORmula ( TRANslator LISP (LISt ( Processor ALGOL COBOL

More information

CHAPTER 2: Introduction to Python COMPUTER PROGRAMMING SKILLS

CHAPTER 2: Introduction to Python COMPUTER PROGRAMMING SKILLS CHAPTER 2: Introduction to Python COMPUTER PROGRAMMING SKILLS 1439-1440 1 Outline 1. Introduction 2. Why Python? 3. Compiler and Interpreter 4. The first program 5. Comments and Docstrings 6. Python Indentations

More information

Why Python? Introduction into Python. Introduction: Remarks. Where to get Python and Learn More?

Why Python? Introduction into Python. Introduction: Remarks. Where to get Python and Learn More? Why Python? Introduction into Python Daniel Polani Properties: minimalistic syntax powerful high-level data structures built in scripting, rapid applications, and as we will se AI widely in use (a plus

More information

PLEASE HAND IN UNIVERSITY OF TORONTO Faculty of Arts and Science

PLEASE HAND IN UNIVERSITY OF TORONTO Faculty of Arts and Science PLEASE HAND IN UNIVERSITY OF TORONTO Faculty of Arts and Science DECEMBER 2013 EXAMINATIONS CSC 108 H1F Instructors: Craig and Gries Duration 3 hours PLEASE HAND IN Examination Aids: None Student Number:

More information

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

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming Intro to Programming Unit 7 Intro to Programming 1 What is Programming? 1. Programming Languages 2. Markup vs. Programming 1. Introduction 2. Print Statement 3. Strings 4. Types and Values 5. Math Externals

More information

Here n is a variable name. The value of that variable is 176.

Here n is a variable name. The value of that variable is 176. UNIT II DATA, EXPRESSIONS, STATEMENTS 9 Python interpreter and interactive mode; values and types: int, float, boolean, string, and list; variables, expressions, statements, tuple assignment, precedence

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

A nano intro to Python

A nano intro to Python A nano intro to Python (just to start working with NLTK ) Ing. Roberto Tedesco, PhD roberto.tedesco@polimi.it NLP AA 18-19 Prof. L. Sbattella Brief description of Python progs 2 l Official web site: https://www.python.org

More information

egrapher Language Reference Manual

egrapher Language Reference Manual egrapher Language Reference Manual Long Long: ll3078@columbia.edu Xinli Jia: xj2191@columbia.edu Jiefu Ying: jy2799@columbia.edu Linnan Wang: lw2645@columbia.edu Darren Chen: dsc2155@columbia.edu 1. Introduction

More information

Introduction to Python Part 2

Introduction to Python Part 2 Introduction to Python Part 2 v0.2 Brian Gregor Research Computing Services Information Services & Technology Tutorial Outline Part 2 Functions Tuples and dictionaries Modules numpy and matplotlib modules

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

Chapter 2. Python Programming for Physicists. Soon-Hyung Yook. March 31, Soon-Hyung Yook Chapter 2 March 31, / 52

Chapter 2. Python Programming for Physicists. Soon-Hyung Yook. March 31, Soon-Hyung Yook Chapter 2 March 31, / 52 Chapter 2 Python Programming for Physicists Soon-Hyung Yook March 31, 2017 Soon-Hyung Yook Chapter 2 March 31, 2017 1 / 52 Table of Contents I 1 Getting Started 2 Basic Programming Variables and Assignments

More information

Basic Concepts. Computer Science. Programming history Algorithms Pseudo code. Computer - Science Andrew Case 2

Basic Concepts. Computer Science. Programming history Algorithms Pseudo code. Computer - Science Andrew Case 2 Basic Concepts Computer Science Computer - Science - Programming history Algorithms Pseudo code 2013 Andrew Case 2 Basic Concepts Computer Science Computer a machine for performing calculations Science

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

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

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

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 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

Lecture 7: Python s Built-in. in Types and Basic Statements

Lecture 7: Python s Built-in. in Types and Basic Statements The University of North Carolina at Chapel Hill Spring 2002 Lecture 7: Python s Built-in in Types and Basic Statements Jan 25 1 Built-in in Data Structures: Lists A list is an ordered collection of objects

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 An Introduction

Python An Introduction Python An Introduction Calle Lejdfors and Lennart Ohlsson calle.lejdfors@cs.lth.se Python An Introduction p. 1 Overview Basic Python Numpy Python An Introduction p. 2 What is Python? Python plays a key

More information

Problem 1 (a): List Operations

Problem 1 (a): List Operations Problem 1 (a): List Operations Task 1: Create a list, L1 = [1, 2, 3,.. N] Suppose we want the list to have the elements 1, 2, 10 range(n) creates the list from 0 to N-1 But we want the list to start from

More information

CS Summer 2013

CS Summer 2013 CS 1110 - Summer 2013 intro to programming -- how to think like a robot :) we use the Python* language (www.python.org) programming environments (many choices): Eclipse (free from www.eclipse.org), or

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

Introduction to Python

Introduction to Python Introduction to Python خانه ریاضیات اصفهان فرزانه کاظمی زمستان 93 1 Why Python? Python is free. Python easy to lean and use. Reduce time and length of coding. Huge standard library Simple (Python code

More information

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled Interpreted vs Compiled Python 1 Java Interpreted Easy to run and test Quicker prototyping Program runs slower Compiled Execution time faster Virtual Machine compiled code portable Java Compile > javac

More information

(CC)A-NC 2.5 by Randall Munroe Python

(CC)A-NC 2.5 by Randall Munroe Python http://xkcd.com/353/ (CC)A-NC 2.5 by Randall Munroe Python Python: Operative Keywords Very high level language Language design is focused on readability Mulit-paradigm Mix of OO, imperative, and functional

More information

Computational Integer Programming. Lecture 4: Python. Dr. Ted Ralphs

Computational Integer Programming. Lecture 4: Python. Dr. Ted Ralphs Computational Integer Programming Lecture 4: Python Dr. Ted Ralphs Computational MILP Lecture 4 1 Why Python? Pros As with many high-level languages, development in Python is quick and painless (relative

More information

Control, Quick Overview. Selection. Selection 7/6/2017. Chapter 2. Control

Control, Quick Overview. Selection. Selection 7/6/2017. Chapter 2. Control Chapter 2 Control, Quick Overview Control Selection Selection Selection is how programs make choices, and it is the process of making choices that provides a lot of the power of computing 1 Python if statement

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

Introduction to Python Part 1

Introduction to Python Part 1 Introduction to Python Part 1 v0.2 Brian Gregor Research Computing Services Information Services & Technology RCS Team and Expertise Our Team Scientific Programmers Systems Administrators Graphics/Visualization

More information

Introduction to VTK and Python. Filip Malmberg Uppsala universitet

Introduction to VTK and Python. Filip Malmberg Uppsala universitet Introduction to VTK and Python Filip Malmberg filip@cb.uu.se IT Uppsala universitet Todays lecture Introduction to the Visualization Toolkit (VTK) Some words about the assignments Introduction to Python

More information

PLEASE HAND IN UNIVERSITY OF TORONTO Faculty of Arts and Science

PLEASE HAND IN UNIVERSITY OF TORONTO Faculty of Arts and Science PLEASE HAND IN UNIVERSITY OF TORONTO Faculty of Arts and Science SUMMER 2012 EXAMINATIONS CSC 108 H1Y Instructors: Janicki Duration NA PLEASE HAND IN Examination Aids: None Student Number: Family Name(s):

More information

Python Interview Questions & Answers

Python Interview Questions & Answers Python Interview Questions & Answers Q 1: What is Python? Ans: Python is an interpreted, interactive, object-oriented programming language. It incorporates modules, exceptions, dynamic typing, very high

More information

PLEASE HAND IN UNIVERSITY OF TORONTO Faculty of Arts and Science

PLEASE HAND IN UNIVERSITY OF TORONTO Faculty of Arts and Science PLEASE HAND IN UNIVERSITY OF TORONTO Faculty of Arts and Science APRIL 2010 EXAMINATIONS CSC 108 H1S Instructors: Horton Duration 3 hours PLEASE HAND IN Examination Aids: None Student Number: Family Name(s):

More information

Python. Department of Computer Science And Engineering. European University Cyprus

Python. Department of Computer Science And Engineering. European University Cyprus 1 Python VICKY PAPADOPOULOU LESTA, Assistant Professor, Member at AHPC group MICHALIS KYPRIANOU, member of the AHPC group(internship project) Department of Computer Science And Engineering European University

More information

Rapid Application Development with

Rapid Application Development with Rapid Application Development with Scripting: Higher Level Programming for the 21st Century (IEEE Computer, March 1998) http://home.pacbell.net/ouster/scripting.html python Scripting Languages vs. System

More information

Introduction to Python

Introduction to Python Introduction to Python Development Environments what IDE to use? 1. PyDev with Eclipse 2. Sublime Text Editor 3. Emacs 4. Vim 5. Atom 6. Gedit 7. Idle 8. PIDA (Linux)(VIM Based) 9. NotePad++ (Windows)

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

Python Tutorial (DRAFT)

Python Tutorial (DRAFT) Python Tutorial (DRAFT) Guido van Rossum Dept. CST, CWI, Kruislaan 413 1098 SJ Amsterdam, The Netherlands E-mail: gu@cwi.nl 19 February 1991 Abstract Python is a simple, yet powerful programming language

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

Python as a First Programming Language Justin Stevens Giselle Serate Davidson Academy of Nevada. March 6th, 2016

Python as a First Programming Language Justin Stevens Giselle Serate Davidson Academy of Nevada. March 6th, 2016 Python as a First Programming Language Justin Stevens Giselle Serate Davidson Academy of Nevada Under Supervision of: Dr. Richard Kelley Chief Engineer, NAASIC March 6th, 2016 Science Technology Engineering

More information

1 Modules 2 IO. 3 Lambda Functions. 4 Some tips and tricks. 5 Regex. Sandeep Sadanandan (TU, Munich) Python For Fine Programmers May 30, / 22

1 Modules 2 IO. 3 Lambda Functions. 4 Some tips and tricks. 5 Regex. Sandeep Sadanandan (TU, Munich) Python For Fine Programmers May 30, / 22 1 Modules 2 IO 3 Lambda Functions 4 Some tips and tricks 5 Regex Sandeep Sadanandan (TU, Munich) Python For Fine Programmers May 30, 2009 1 / 22 What are they? Modules are collections of classes or functions

More information

Introduction to Python. Didzis Gosko

Introduction to Python. Didzis Gosko Introduction to Python Didzis Gosko Scripting language From Wikipedia: A scripting language or script language is a programming language that supports scripts, programs written for a special run-time environment

More information

Python BASICS. Introduction to Python programming, basic concepts: formatting, naming conventions, variables, etc.

Python BASICS. Introduction to Python programming, basic concepts: formatting, naming conventions, variables, etc. Python BASICS Introduction to Python programming, basic concepts: formatting, naming conventions, variables, etc. Identikit First appeared in 1991 Designed by Guido van Rossum General purpose High level

More information

C++ for Python Programmers

C++ for Python Programmers C++ for Python Programmers Adapted from a document by Rich Enbody & Bill Punch of Michigan State University Purpose of this document This document is a brief introduction to C++ for Python programmers

More information

CS 1301 CS1 with Robots Summer 2007 Exam 1

CS 1301 CS1 with Robots Summer 2007 Exam 1 Your Name: 1 / 6 CS 1301 CS1 with Robots Summer 2007 Exam 1 1. Vocabulary Matching: (15 points) Write the number from the correct definition in the blank next to each term on the left: _12_Print statement

More information

About the Final. Saturday, 7-10pm in Science Center 101. Closed book, closed notes. Not on the final: graphics, file I/O, vim, unix

About the Final. Saturday, 7-10pm in Science Center 101. Closed book, closed notes. Not on the final: graphics, file I/O, vim, unix CS 21 Final Review About the Final Saturday, 7-10pm in Science Center 101 Closed book, closed notes Not on the final: graphics, file I/O, vim, unix Expect Questions That Ask You To: Evaluate Python expressions

More information

Python. Tutorial Lecture for EE562 Artificial Intelligence for Engineers

Python. Tutorial Lecture for EE562 Artificial Intelligence for Engineers Python Tutorial Lecture for EE562 Artificial Intelligence for Engineers 1 Why Python for AI? For many years, we used Lisp, because it handled lists and trees really well, had garbage collection, and didn

More information

SOFT 161. Class Meeting 1.6

SOFT 161. Class Meeting 1.6 University of Nebraska Lincoln Class Meeting 1.6 Slide 1/13 Overview of A general purpose programming language Created by Guido van Rossum Overarching design goal was orthogonality Automatic memory management

More information

CPSC 217 Midterm (Python 3 version)

CPSC 217 Midterm (Python 3 version) CPSC 217 Midterm (Python 3 version) Duration: 50 minutes 6 March 2009 This exam has 61 questions and 11 pages. This exam is closed book. No notes, books, calculators or electronic devices, or other assistance

More information

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals:

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals: Numeric Types There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals: 1-123 +456 2. Long integers, of unlimited

More information

Introduction to Python

Introduction to Python Introduction to Python EECS 4415 Big Data Systems Tilemachos Pechlivanoglou tipech@eecs.yorku.ca 2 Background Why Python? "Scripting language" Very easy to learn Interactive front-end for C/C++ code Object-oriented

More information

Part III Appendices 165

Part III Appendices 165 Part III Appendices 165 Appendix A Technical Instructions Learning Outcomes This material will help you learn how to use the software you need to do your work in this course. You won t be tested on it.

More information

Basic Scripting, Syntax, and Data Types in Python. Mteor 227 Fall 2017

Basic Scripting, Syntax, and Data Types in Python. Mteor 227 Fall 2017 Basic Scripting, Syntax, and Data Types in Python Mteor 227 Fall 2017 Basic Shell Scripting/Programming with Python Shell: a user interface for access to an operating system s services. The outer layer

More information

STEAM Clown & Productions Copyright 2017 STEAM Clown. Page 1

STEAM Clown & Productions Copyright 2017 STEAM Clown. Page 1 What to add next time you are updating these slides Update slides to have more animation in the bullet lists Verify that each slide has stand alone speaker notes Page 1 Python 3 Running The Python Interpreter

More information

Princeton University COS 333: Advanced Programming Techniques A Subset of Python 2.7

Princeton University COS 333: Advanced Programming Techniques A Subset of Python 2.7 Princeton University COS 333: Advanced Programming Techniques A Subset of Python 2.7 Program Structure # Print "hello world" to stdout. print 'hello, world' # Print "hello world" to stdout. def f(): print

More information

2.Raspberry PI: Architecture & Hardware Specifications

2.Raspberry PI: Architecture & Hardware Specifications Course Contents: 1.Introduction to RASPBERRY PI Introduction to Open Source Hardware About Raspberry PI Brief Introduction to Hardware Parts & Usability 2.Raspberry PI: Architecture & Hardware Specifications

More information

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

CSCE 110 Programming I Basics of Python: Variables, Expressions, Input/Output CSCE 110 Programming I Basics of Python: Variables, Expressions, Input/Output Dr. Tiffani L. Williams Department of Computer Science and Engineering Texas A&M University Spring 2011 Python Python was developed

More information

Introduction to Programming in Python (1)

Introduction to Programming in Python (1) to Programming in Python (1) Steve Renals s.renals@ed.ac.uk ICL 26 September 2005 Steve Renalss.renals@ed.ac.uk to Programming in Python (1) Announcements Lab sessions: Groups listed on the web: http://www.inf.ed.ac.uk/admin/itodb/mgroups/labs/icl.html

More information

DSC 201: Data Analysis & Visualization

DSC 201: Data Analysis & Visualization DSC 201: Data Analysis & Visualization Classes Dr. David Koop Tuple, List, Dictionary, or Set? [1,2,"abc"] 2 Tuple, List, Dictionary, or Set? {"a", 1, 2} 3 Tuple, List, Dictionary, or Set? {} 4 Tuple,

More information

Python Tutorial. CSE 3461: Computer Networking

Python Tutorial. CSE 3461: Computer Networking Python Tutorial CSE 3461: Computer Networking 1 Outline Introduction to Python CSE Environment Tips for Python Primitive Types Tips for Encoding/Decoding an IP Address 2 Intro to Python Dynamically typed,

More information

Introduction to Programming in Python (2)

Introduction to Programming in Python (2) Introduction to Programming in Python (2) Steve Renals s.renals@ed.ac.uk ICL 29 September 2005 Conditionals Loops Function basics Variables and functions Functional programming Designing functions Python

More information

Get It Interpreter Scripts Arrays. Basic Python. K. Cooper 1. 1 Department of Mathematics. Washington State University. Basics

Get It Interpreter Scripts Arrays. Basic Python. K. Cooper 1. 1 Department of Mathematics. Washington State University. Basics Basic Python K. 1 1 Department of Mathematics 2018 Python Guido van Rossum 1994 Original Python was developed to version 2.7 2010 2.7 continues to receive maintenance New Python 3.x 2008 The 3.x version

More information

CME 193: Introduction to Scientific Python Lecture 1: Introduction

CME 193: Introduction to Scientific Python Lecture 1: Introduction CME 193: Introduction to Scientific Python Lecture 1: Introduction Nolan Skochdopole stanford.edu/class/cme193 1: Introduction 1-1 Contents Administration Introduction Basics Variables Control statements

More information

Python Mini Lessons last update: May 29, 2018

Python Mini Lessons last update: May 29, 2018 Python Mini Lessons last update: May 29, 2018 From http://www.onlineprogramminglessons.com These Python mini lessons will teach you all the Python Programming statements you need to know, so you can write

More information

PROGRAMMING FUNDAMENTALS

PROGRAMMING FUNDAMENTALS PROGRAMMING FUNDAMENTALS Q1. Name any two Object Oriented Programming languages? Q2. Why is java called a platform independent language? Q3. Elaborate the java Compilation process. Q4. Why do we write

More information

Key Differences Between Python and Java

Key Differences Between Python and Java Python Python supports many (but not all) aspects of object-oriented programming; but it is possible to write a Python program without making any use of OO concepts. Python is designed to be used interpretively.

More information

Short Python function/method descriptions:

Short Python function/method descriptions: Last Name First Name Student#. Short Python function/method descriptions: builtins : len(x) -> integer Return the length of the list, tuple, dict, or string x. max(l) -> value Return the largest value

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

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