Part IV. More on Python. Tobias Neckel: Scripting with Bash and Python Compact Max-Planck, February 16-26,

Size: px
Start display at page:

Download "Part IV. More on Python. Tobias Neckel: Scripting with Bash and Python Compact Max-Planck, February 16-26,"

Transcription

1 Part IV More on Python Compact Max-Planck, February 16-26,

2 More on Strings Special string methods (excerpt) s = " Frodo and Sam and Bilbo " s. islower () s. isupper () s. startswith (" Frodo ") # try s. startswith (" Frodo ", 2) s. endswith (" Bilbo ") s = s. strip () s. upper () s = s. lower () s. capitalize () # capitalize first character s = s. center ( len (s )+4) # center ( padding default : space ) s. lstrip () s. rstrip (" ") s = s. strip () s. find (" sam ") s. rfind (" and ") Compact Max-Planck, February 16-26,

3 More on Strings (2) Searching, splitting and joining (excerpt) s. find (" sam ") s. rfind (" and ") s. replace (" and ", "or") s. split () # or s. split ( None ); arbitrary numb. whitesp. s. split (" ") s. split (" and ") s. split (" and ", 1) s = """ Line by Line """ s. splitlines () ", ". join ([" sequence ", "of", " strings "]) Compact Max-Planck, February 16-26,

4 More on Built-in Sequences Dictionaries Map keys to values, arbitrary types Only immutable objects as keys Can serve as database d = {} d[" Bilbo "] = " Hobbit " d[" Elrond "] = " Elf " d [42] = 1234 d. has_key (" Bilbo ") d. keys () # unordered d. items () d. values () del d [42] d. clear () Compact Max-Planck, February 16-26,

5 More on Functions Functions have to be defined before actually called for the first time Note: Python is an interpreted language Variables Variables defined or assigned to in functions have local scope Global variables (surrounding context) can be accessed To modify global variables use global count = 0... def count_it (n): global count count += 1 In general: avoid global variables (pass as params instead) Compact Max-Planck, February 16-26,

6 Call by Reference vs. Call by value Call by reference: address (id) of parameter is handed over Call by value: value of parameter is handed over In Python: always call by reference But: assignment changes reference within function >>> def add_one (x): >>> x = x + 1 >>> >>> x = 3 >>> add_one (x) >>> x 3 Compact Max-Planck, February 16-26,

7 Call by Reference vs. Call by value (2) After assignment: local variable references to a new object. Using methods, the original object can be modified. >>> def append1 (l): >>> l = l + [4] >>> >>> def append2 (l): >>> l. append (4) >>> >>> l = [1,2,3] >>> append1 (l); l [1,2,3] >>> append2 (l); l [1,2,3,4] Compact Max-Planck, February 16-26,

8 More on Functions (2) Return values Functions can have multiple return values (returned as tuple) def get_hobbits (): return " Bilbo ", " Frodo " h = get_hobbits () (a, b) = get_hobbits () Assignment rules correspond to slice assignment l = [4, 2] (a, b) = l # implicit type conversion a, b = l l [0:3] = (3, 2) # implicit type conversion Compact Max-Planck, February 16-26,

9 More on Functions (3) Docstrings Functions (and classes, modules,...) can provide help text String after function header (can be multiline) def answer (): " Returns an answer to a question " print " answer " help ( answer ) Compact Max-Planck, February 16-26,

10 Arithmetic Operations Classical operations x + y # Addition x - y # Subtraction x * y # Multiplication x / y # Division x // y # Truncated division x ** y # Exponentiation x % y # Modulo x -= 2; x *= 4;... Division differs for int and float (Python < 3.0) 7/4 7.0/4 Compact Max-Planck, February 16-26,

11 More Operations General functions abs (x) divmod (x, y) # (x // y, x % y) pow (x, y [, modulo ]) # x**y % modulo round (x, [n]) # round to 10**( - n) Operations on integers x << y # Left shift x >> y # Right shift x & y # Bitwise and x y # Bitwise or x ^ y # Bitwise xor ~ x # Bitwise negation Compact Max-Planck, February 16-26,

12 File I/O Opening files Create file object (text files) fd = open (" testfile. txt ") # read fd = open (" testfile. txt ", r ) # read fd = open (" testfile. txt ", w ) # write fd = open (" testfile. txt ", a ) # append Create file object (binary files) fd = open (" testfile. txt ", rb ) # read fd = open (" testfile. txt ", wb ) # write fd = open (" testfile. txt ", ab ) # append open has more options (encoding, how to handle newlines,... ) Compact Max-Planck, February 16-26,

13 File I/O (2) Methods of file objects Reading fd. read () # all fd. read (n) # n Bytes fd. readline () # one line fd. readlines () # Writing fd. write (" New Text \n") fd. writelines ([" first line \n", " Second \n"]) Don t forget to write newlines Closing fd. close () Compact Max-Planck, February 16-26,

14 File I/O (3) Iterating over textfile for loop over file line by line fd = open (" fulltext. txt ") for line in fd: # rather than : in fd. readlines () print line # or: while True : line = fd. readline () if not line : break print line Compact Max-Planck, February 16-26,

15 File I/O (3) Iterating over textfile for loop over file line by line fd = open (" fulltext. txt ") for line in fd: # rather than : in fd. readlines () print line # or: while True : line = fd. readline () if not line : break print line Some more functions on file objects fd.tell() get current file position fd.seek(offset) set file to position fd.flush() flush output buffer. Note: buffered for efficiency Compact Max-Planck, February 16-26,

16 Getting more... Modules Outsource functionality in separate.py files Import them as library module Example (tools.py): """ This module provides some helper tools. Try it. """ counter = 42 def readfile ( fname ): " Read text file. Returns list of lines " fd = open ( fname, r ) data = fd. readlines () fd. close () return data def do_nothing (): "Do really nothing " pass Compact Max-Planck, February 16-26,

17 Modules (2) Import module import tools tools. do_nothing () print tools. counter Import module and change name import tools as t t. do_nothing () Import selected symbols to current namespace from tools import do_nothing, readfile from tools import counter as cntr do_nothing () print cntr Compact Max-Planck, February 16-26,

18 Modules (3) Import all symbols to current namespace from tools import * do_nothing () print counter Modules can control which symbols are imported by from module import *: # module tools. py all = [ readfile, counter ] Then do_nothing() is unknown after import * Compact Max-Planck, February 16-26,

19 Modules (3) Import all symbols to current namespace from tools import * do_nothing () print counter Modules can control which symbols are imported by from module import *: # module tools. py all = [ readfile, counter ] Then do_nothing() is unknown after import * Inspect namespace Inspect namespace of module with dir ( tools ) Compact Max-Planck, February 16-26,

20 Modules (4) Getting help Access docstrings import tools help ( tools ) help ( tools. do_nothing ) Compact Max-Planck, February 16-26,

21 Modules (4) Getting help Access docstrings import tools help ( tools ) help ( tools. do_nothing ) Execute module as main program tools.py should serve as program and module # tools.py... if name == main : print " tools.py executed " else : print " tools.py imported as module " Compact Max-Planck, February 16-26,

22 Modules (5) Reload module When debugging a module reload with reload (Python<3.0) reload ( tools ) Module search path Modules have to be in current directory or in directory in search path import sys sys. path. append (" folder /to/ module ") import... Automatically extend sys.path by setting environment variable PYTHONPATH Compact Max-Planck, February 16-26,

23 Packages Group modules Modules can be grouped together Folder structure determines modules, e.g.: tools / init. py # contents for " import tools " files. py # for " import tools. files " graphics. py # for " import tools. graphics " stringtools / init. py # for " import tools. stringtools "... further nesting If from tools import * should import submodules, tools/ init.py has to contain all = [" files ", " graphics "] Compact Max-Planck, February 16-26,

24 Command-Line Options Using sys sys.argv is list of command-line options First one (sys.argv[0]) is program name import sys print " Executing : %s" % ( sys. argv [0]) if len ( sys. argv ) < 2: print " Not enough parameters " sys. exit (1) print " Parameters :" print ", ". join ( sys. argv [1:]) Parse parameters... Compact Max-Planck, February 16-26,

25 Command-Line Options (2) Module argparse Class ArgumentParser in module argparse simplifies option parsing #!/ usr / bin / python import argparse p = argparse. ArgumentParser () # specify options p. add_argument ("-o", action =" store ", dest =" opt ") p. add_argument ("-v"," -- verbose ",action =" store_true ", dest =" verbose ", help =" Produce more output ") # parse options options = p. parse_args () if options. verbose : print " Starting program... " print options Compact Max-Planck, February 16-26,

26 Module argparse (2) Program now supports Default help Two custom parameters Try (parameters.py):./ parameters.py./ parameters. py -h./ parameters.py -o " Enjoy it" -- verbose./ parameters.py -v file1. txt file2. txt Compact Max-Planck, February 16-26,

27 Module argparse (3) Some parameters of add_argument One character "-x" and/or multiple character switches "--xyz" action can be store, store_true, store_false, append, count dest name of option default default value help help text type one of string (default), int, long, float, complex, choice choices = [ first, second, third ] for type= choice Compact Max-Planck, February 16-26,

28 Module argparse (3) Some parameters of add_argument One character "-x" and/or multiple character switches "--xyz" action can be store, store_true, store_false, append, count dest name of option default default value help help text type one of string (default), int, long, float, complex, choice choices = [ first, second, third ] for type= choice Help text with set_usage Reference to program name with %prog p = argparse. ArgumentParser ( % prog [ options ] file (s) Do nice things with file (s) ) Compact Max-Planck, February 16-26,

29 Standard Input, Output, and Error Module sys provides three standard file objects sys.stdin read only sys.stdout, sys.stderr write only import sys sys. stdout. write (" Enter line :\n") # = print "..." line = sys. stdin. readline () # or: line = raw_input (" Enter line :\ n") if error : sys. stderr. write (" Error!\n") write does not add newlines raw_input([text]) strips endling newline Input and output buffered Compact Max-Planck, February 16-26,

30 More on Lists List comprehension Short notation to create lists even_squares = [] for i in range (10): if i%2 == 0: even_squares. append (i*i) even_squares = [ i **2 for i in range (10) if i %2==0] Compare: { i 2 i {0,..., 9}, i even } Compact Max-Planck, February 16-26,

31 More on Lists List comprehension Short notation to create lists even_squares = [] for i in range (10): if i%2 == 0: even_squares. append (i*i) even_squares = [ i **2 for i in range (10) if i %2==0] Compare: { i 2 i {0,..., 9}, i even } Can contain more than one for... in... [if...] [(x,y. upper ()) for x in range (4) if x%2 == 0 for y in ["a", "b", "c"]] Compact Max-Planck, February 16-26,

32 More on Lists (2) Advanced slice assignement Note: assigning slices of mutable sequences can change size l = range (5) l [1:3] = [7,8,9] l [4:6] = [6] Compact Max-Planck, February 16-26,

33 More on Lists (2) Advanced slice assignement Note: assigning slices of mutable sequences can change size l = range (5) l [1:3] = [7,8,9] l [4:6] = [6] range and xrange range([i,] j [, stride]) creates list Memory allocated for whole list, even when only iterating over them, especially in loops xrange object calculates values when accessed (generator) for i in range (650000): do_something () for i in xrange (650000): do_something () Compact Max-Planck, February 16-26,

34 Even more on Built-in Sequences set and frozenset set is mutable, frozenset is not s = set ([3,1,2,3,"foo ",2]) len (s) l = [2,8,7] # any iterable sequence s. difference (l) s. intersection (l) s. union (l) s. symmetric_difference (l) s. issubset ([3,"foo "]) s. issuperset ([3,"foo "]) For set s. add (42) s. remove (3) s. intersection_update (l) # and more methods... Compact Max-Planck, February 16-26,

35 Even more on Functions Anonymous functions Can be defined using keyword lambda Lambda functions allow functional programming def inc (i): return i+1 inc = lambda (i): i+1 ( lambda i: i +1)(4) Common use: map function on list items / filter list l = range (10) map ( lambda x: x*x+1, l) filter ( lambda x: x %2==0, l) Compact Max-Planck, February 16-26,

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

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

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

Script language: Python Data and files

Script language: Python Data and files Script language: Python Data and files Cédric Saule Technische Fakultät Universität Bielefeld 4. Februar 2015 Python User inputs, user outputs Command line parameters, inputs and outputs of user data.

More information

Babu Madhav Institute of Information Technology, UTU 2015

Babu Madhav Institute of Information Technology, UTU 2015 Five years Integrated M.Sc.(IT)(Semester 5) Question Bank 060010502:Programming in Python Unit-1:Introduction To Python Q-1 Answer the following Questions in short. 1. Which operator is used for slicing?

More information

CS Programming Languages: Python

CS Programming Languages: Python CS 3101-1 - Programming Languages: Python Lecture 5: Exceptions / Daniel Bauer (bauer@cs.columbia.edu) October 08 2014 Daniel Bauer CS3101-1 Python - 05 - Exceptions / 1/35 Contents Exceptions Daniel Bauer

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

Advanced Algorithms and Computational Models (module A)

Advanced Algorithms and Computational Models (module A) Advanced Algorithms and Computational Models (module A) Giacomo Fiumara giacomo.fiumara@unime.it 2014-2015 1 / 34 Python's built-in classes A class is immutable if each object of that class has a xed value

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

Webgurukul Programming Language Course

Webgurukul Programming Language Course Webgurukul Programming Language Course Take One step towards IT profession with us Python Syllabus Python Training Overview > What are the Python Course Pre-requisites > Objectives of the Course > Who

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

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

GE PROBLEM SOVING AND PYTHON PROGRAMMING. Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING

GE PROBLEM SOVING AND PYTHON PROGRAMMING. Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING GE8151 - PROBLEM SOVING AND PYTHON PROGRAMMING Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING 1) Define Computer 2) Define algorithm 3) What are the two phases in algorithmic problem solving? 4) Why

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 CONTENT NOTE: Almost every task is explained with an example

PYTHON CONTENT NOTE: Almost every task is explained with an example PYTHON CONTENT NOTE: Almost every task is explained with an example Introduction: 1. What is a script and program? 2. Difference between scripting and programming languages? 3. What is Python? 4. Characteristics

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. Lecture and Lab 5 Day Course. Python Basics

Python Basics. Lecture and Lab 5 Day Course. Python Basics Python Basics Lecture and Lab 5 Day Course Course Overview Python, is an interpreted, object-oriented, high-level language that can get work done in a hurry. A tool that can improve all professionals ability

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

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

Python Training. Complete Practical & Real-time Trainings. A Unit of SequelGate Innovative Technologies Pvt. Ltd.

Python Training. Complete Practical & Real-time Trainings. A Unit of SequelGate Innovative Technologies Pvt. Ltd. Python Training Complete Practical & Real-time Trainings A Unit of. ISO Certified Training Institute Microsoft Certified Partner Training Highlights : Complete Practical and Real-time Scenarios Session

More information

Python Programming Language

Python Programming Language Python Programming Language Data Structure Sachin PVPPCOE December 22, 2015 Data types Basic objects: numbers(float, int, complex), strings, Tuples, lists, sets, & dictionaries Other data types: Modules,

More information

Script language: Python Data structures

Script language: Python Data structures Script language: Python Data structures Cédric Saule Technische Fakultät Universität Bielefeld 3. Februar 2015 Immutable vs. Mutable Previously known types: int and string. Both are Immutable but what

More information

Python INTRODUCTION: Understanding the Open source Installation of python in Linux/windows. Understanding Interpreters * ipython.

Python INTRODUCTION: Understanding the Open source Installation of python in Linux/windows. Understanding Interpreters * ipython. INTRODUCTION: Understanding the Open source Installation of python in Linux/windows. Understanding Interpreters * ipython * bpython Getting started with. Setting up the IDE and various IDEs. Setting up

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Object Oriented Programming Harry Smith University of Pennsylvania February 15, 2016 Harry Smith (University of Pennsylvania) CIS 192 Lecture 5 February 15, 2016 1 / 26 Outline

More information

Reading and writing files

Reading and writing files C H A P T E R 1 3 Reading and writing files 131 Opening files and file objects 131 132 Closing files 132 133 Opening files in write or other modes 132 134 Functions to read and write text or binary data

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

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

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

Lecture no

Lecture no Advanced Algorithms and Computational Models (module A) Lecture no. 3 29-09-2014 Giacomo Fiumara giacomo.fiumara@unime.it 2014-2015 1 / 28 Expressions, Operators and Precedence Sequence Operators The following

More information

IPSL python tutorial: some exercises for beginners

IPSL python tutorial: some exercises for beginners 1 of 9 10/22/2013 03:55 PM IPSL python tutorial: some exercises for beginners WARNING! WARNING! This is the FULL version of the tutorial (including the solutions) WARNING! Jean-Yves Peterschmitt - LSCE

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

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

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Generators Exceptions and IO Eric Kutschera University of Pennsylvania February 13, 2015 Eric Kutschera (University of Pennsylvania) CIS 192 February 13, 2015 1 / 24 Outline 1

More information

Table of Contents. Preface... xxi

Table of Contents. Preface... xxi Table of Contents Preface... xxi Chapter 1: Introduction to Python... 1 Python... 2 Features of Python... 3 Execution of a Python Program... 7 Viewing the Byte Code... 9 Flavors of Python... 10 Python

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Iterators, Generators, IO, and Exceptions Harry Smith University of Pennsylvania February 15, 2018 Harry Smith (University of Pennsylvania) CIS 192 Lecture 5 February 15, 2018

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

About Python. Python Duration. Training Objectives. Training Pre - Requisites & Who Should Learn Python

About Python. Python Duration. Training Objectives. Training Pre - Requisites & Who Should Learn Python About Python Python course is a great introduction to both fundamental programming concepts and the Python programming language. By the end, you'll be familiar with Python syntax and you'll be able to

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

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

Classifying malware using network traffic analysis. Or how to learn Redis, git, tshark and Python in 4 hours.

Classifying malware using network traffic analysis. Or how to learn Redis, git, tshark and Python in 4 hours. Classifying malware using network traffic analysis. Or how to learn Redis, git, tshark and Python in 4 hours. Alexandre Dulaunoy January 9, 2015 Problem Statement We have more 5000 pcap files generated

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Iterators, Generators, Exceptions & IO Raymond Yin University of Pennsylvania September 28, 2016 Raymond Yin (University of Pennsylvania) CIS 192 September 28, 2016 1 / 26 Outline

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

Python Working with files. May 4, 2017

Python Working with files. May 4, 2017 Python Working with files May 4, 2017 So far, everything we have done in Python was using in-memory operations. After closing the Python interpreter or after the script was done, all our input and output

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

Strings. Upsorn Praphamontripong. Note: for reference when we practice loop. We ll discuss Strings in detail after Spring break

Strings. Upsorn Praphamontripong. Note: for reference when we practice loop. We ll discuss Strings in detail after Spring break Note: for reference when we practice loop. We ll discuss Strings in detail after Spring break Strings Upsorn Praphamontripong CS 1111 Introduction to Programming Spring 2018 Strings Sequence of characters

More information

Index. object lifetimes, and ownership, use after change by an alias errors, use after drop errors, BTreeMap, 309

Index. object lifetimes, and ownership, use after change by an alias errors, use after drop errors, BTreeMap, 309 A Arithmetic operation floating-point arithmetic, 11 12 integer numbers, 9 11 Arrays, 97 copying, 59 60 creation, 48 elements, 48 empty arrays and vectors, 57 58 executable program, 49 expressions, 48

More information

What Version Number to Install

What Version Number to Install A Python Primer This chapter provides a quick overview of the Python language. The goal in this chapter is not to teach you the Python language excellent books have been written on that subject, such as

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

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

Functions, Scope & Arguments. HORT Lecture 12 Instructor: Kranthi Varala

Functions, Scope & Arguments. HORT Lecture 12 Instructor: Kranthi Varala Functions, Scope & Arguments HORT 59000 Lecture 12 Instructor: Kranthi Varala Functions Functions are logical groupings of statements to achieve a task. For example, a function to calculate the average

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

LECTURE 4 Python Basics Part 3

LECTURE 4 Python Basics Part 3 LECTURE 4 Python Basics Part 3 INPUT We ve already seen two useful functions for grabbing input from a user: raw_input() Asks the user for a string of input, and returns the string. If you provide an argument,

More information

Python Tutorial. Day 2

Python Tutorial. Day 2 Python Tutorial Day 2 1 Control: Whitespace in perl and C, blocking is controlled by curly-braces in shell, by matching block delimiters, if...then...fi in Python, blocking is controlled by indentation

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

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

Introductory Linux Course. Python I. Pavlin Mitev UPPMAX. Author: Nina Fischer Dept. for Cell and Molecular Biology, Uppsala University Introductory Linux Course Python I Pavlin Mitev UPPMAX Author: Nina Fischer Dept. for Cell and Molecular Biology, Uppsala University August, 2017 Outline Python introduction Python basics get started with

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

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

Python Reference (The Right Way) Documentation

Python Reference (The Right Way) Documentation Python Reference (The Right Way) Documentation Release 0.1 Jakub Przywóski Sep 30, 2017 Contents 1 Contents 1 1.1 Introduction............................................... 1 1.2 Definitions................................................

More information

1 Decorators. 2 Descriptors. 3 Static Variables. 4 Anonymous Classes. Sandeep Sadanandan (TU, Munich) Python For Fine Programmers July 13, / 19

1 Decorators. 2 Descriptors. 3 Static Variables. 4 Anonymous Classes. Sandeep Sadanandan (TU, Munich) Python For Fine Programmers July 13, / 19 1 Decorators 2 Descriptors 3 Static Variables 4 Anonymous Classes Sandeep Sadanandan (TU, Munich) Python For Fine Programmers July 13, 2009 1 / 19 Decorator Pattern In object-oriented programming, the

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

Duration: Six Weeks Faculty : Mr Sai Kumar, Having 10+ Yrs Experience in IT

Duration: Six Weeks Faculty : Mr Sai Kumar, Having 10+ Yrs Experience in IT Duration: Six Weeks Faculty : Mr Sai Kumar, Having 10+ Yrs Experience in IT Online Classes are also available Recorded class will be given if you miss any day interview tips and quiz at end of every module

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

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

LECTURE 2. Python Basics

LECTURE 2. Python Basics LECTURE 2 Python Basics MODULES ''' Module fib.py ''' from future import print_function def even_fib(n): total = 0 f1, f2 = 1, 2 while f1 < n: if f1 % 2 == 0: total = total + f1 f1, f2 = f2, f1 + f2 return

More information

COMP322 - Introduction to C++ Lecture 02 - Basics of C++

COMP322 - Introduction to C++ Lecture 02 - Basics of C++ COMP322 - Introduction to C++ Lecture 02 - Basics of C++ School of Computer Science 16 January 2012 C++ basics - Arithmetic operators Where possible, C++ will automatically convert among the basic types.

More information

Introduction to Python! Lecture 2

Introduction to Python! Lecture 2 .. Introduction to Python Lecture 2 Summary Summary: Lists Sets Tuples Variables while loop for loop Functions Names and values Passing parameters to functions Lists Characteristics of the Python lists

More information

OOP and Scripting in Python Advanced Features

OOP and Scripting in Python Advanced Features OOP and Scripting in Python Advanced Features Giuliano Armano Emanuele Tamponi Advanced Features Structure of a Python Script More on Defining Functions Default Argument Values Keyword Arguments Arbitrary

More information

Module 3: Strings and Input/Output

Module 3: Strings and Input/Output Module 3: Strings and Input/Output Topics: Strings and their methods Printing to standard output Reading from standard input Readings: ThinkP 8, 10 1 Strings in Python: combining strings in interesting

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

CS S-02 Python 1. Most python references use examples involving spam, parrots (deceased), silly walks, and the like

CS S-02 Python 1. Most python references use examples involving spam, parrots (deceased), silly walks, and the like CS662-2013S-02 Python 1 02-0: Python Name python comes from Monte Python s Flying Circus Most python references use examples involving spam, parrots (deceased), silly walks, and the like Interpreted language

More information

IAP Python - Lecture 2

IAP Python - Lecture 2 IAP Python - Lecture 2 Evan Broder, Andrew Farrell MIT SIPB January 6, 2011 Higher Order Functions A function is a first-class object, so it can be returned from a function. def maketunk(n): def thunk():

More information

Python 3 Quick Reference Card

Python 3 Quick Reference Card Python 3 Quick Reference Card Data types Strings: s = "foo bar" s = 'foo bar' s = r"c:\dir\new" # raw (== 'c:\\dir\\new') s = """Hello world""" s.join(" baz") n = len(s) "Ala ma {} psy i {} koty".format(2,3)

More information

Alastair Burt Andreas Eisele Christian Federmann Torsten Marek Ulrich Schäfer. October 6th, Universität des Saarlandes. Introduction to Python

Alastair Burt Andreas Eisele Christian Federmann Torsten Marek Ulrich Schäfer. October 6th, Universität des Saarlandes. Introduction to Python Outline Alastair Burt Andreas Eisele Christian Federmann Torsten Marek Ulrich Schäfer Universität des Saarlandes October 6th, 2009 Outline Outline Today s Topics: 1 More Examples 2 Cool Stuff 3 Text Processing

More information

COMP-520 GoLite Tutorial

COMP-520 GoLite Tutorial COMP-520 GoLite Tutorial Alexander Krolik Sable Lab McGill University Winter 2019 Plan Target languages Language constructs, emphasis on special cases General execution semantics Declarations Types Statements

More information

ECE 364 Software Engineering Tools Laboratory. Lecture 4 Python: Collections I

ECE 364 Software Engineering Tools Laboratory. Lecture 4 Python: Collections I ECE 364 Software Engineering Tools Laboratory Lecture 4 Python: Collections I 1 Lecture Summary Lists Tuples Sets Dictionaries Printing, More I/O Bitwise Operations 2 Lists list is a built-in Python data

More information

sottotitolo A.A. 2016/17 Federico Reghenzani, Alessandro Barenghi

sottotitolo A.A. 2016/17 Federico Reghenzani, Alessandro Barenghi Titolo presentazione Piattaforme Software per la Rete sottotitolo BASH Scripting Milano, XX mese 20XX A.A. 2016/17, Alessandro Barenghi Outline 1) Introduction to BASH 2) Helper commands 3) Control Flow

More information

Modules and scoping rules

Modules and scoping rules C H A P T E R 1 1 Modules and scoping rules 11.1 What is a module? 106 11.2 A first module 107 11.3 The import statement 109 11.4 The module search path 110 11.5 Private names in modules 112 11.6 Library

More information

Files. Files need to be opened in Python before they can be read from or written into Files are opened in Python using the open() built-in function

Files. Files need to be opened in Python before they can be read from or written into Files are opened in Python using the open() built-in function Files Files File I/O Files need to be opened in Python before they can be read from or written into Files are opened in Python using the open() built-in function open(file, mode='r', buffering=-1, encoding=none,...

More information

The Pyth Language. Administrivia

The Pyth Language. Administrivia Administrivia The Pyth Language Lecture 5 Please make sure you have registered your team, created SSH keys as indicated on the admin page, and also have electronically registered with us as well. Prof.

More information

06/11/2014. Subjects. CS Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / ) Beginning with Python

06/11/2014. Subjects. CS Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / ) Beginning with Python CS95003 - Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / 2014 Subjects 1) Beginning with Python 2) Variables 3) Strings 4) Basic arithmetic operators 5) Flow control 6) Comparison

More information

String Processing CS 1111 Introduction to Programming Fall 2018

String Processing CS 1111 Introduction to Programming Fall 2018 String Processing CS 1111 Introduction to Programming Fall 2018 [The Coder s Apprentice, 10] 1 Collections Ordered, Dup allow List Range String Tuple Unordered, No Dup Dict collection[index] Access an

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

LOON. Language Reference Manual THE LANGUAGE OF OBJECT NOTATION. Kyle Hughes, Jack Ricci, Chelci Houston-Borroughs, Niles Christensen, Habin Lee

LOON. Language Reference Manual THE LANGUAGE OF OBJECT NOTATION. Kyle Hughes, Jack Ricci, Chelci Houston-Borroughs, Niles Christensen, Habin Lee LOON THE LANGUAGE OF OBJECT NOTATION Language Reference Manual Kyle Hughes, Jack Ricci, Chelci Houston-Borroughs, Niles Christensen, Habin Lee October 2017 1 Contents 1 Introduction 3 2 Types 4 2.1 JSON............................................

More information

Download Python from Any version will do for this class

Download Python from  Any version will do for this class Let s Start Python Let s Start! Download Python from www.python.org Any version will do for this class By and large they are all mutually compatible Recommended version: 2.1.1 or 2.2 Oldest version still

More information

COLLEGE OF ENGINEERING, NASHIK-4

COLLEGE OF ENGINEERING, NASHIK-4 Pune Vidyarthi Griha s COLLEGE OF ENGINEERING, NASHIK-4 DEPARTMENT OF COMPUTER ENGINEERING Important PYTHON Questions 1. What is Python? Python is a high-level, interpreted, interactive and object-oriented

More information

CS Introduction to Computational and Data Science. Instructor: Renzhi Cao Computer Science Department Pacific Lutheran University Spring 2017

CS Introduction to Computational and Data Science. Instructor: Renzhi Cao Computer Science Department Pacific Lutheran University Spring 2017 CS 133 - Introduction to Computational and Data Science Instructor: Renzhi Cao Computer Science Department Pacific Lutheran University Spring 2017 Introduction to Python II In the previous class, you have

More information

VALLIAMMAI ENGINEERING COLLEGE

VALLIAMMAI ENGINEERING COLLEGE VALLIAMMAI ENGINEERING COLLEGE SRM Nagar, Kattankulathur 60 20 DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING QUESTION BANK B.E I SEMESTER GE85- Problem Solving and Python Programming Regulation 207 Academic

More information

An Introduction to Python

An Introduction to Python An Introduction to Python Day 3 Renaud Dessalles dessalles@ucla.edu Writing Modules Combining what we ve learnt Yesterday we learnt a lot of different bits of Python. Let s summarize that knowledge by

More information

Programming with Python. May 4, 2017

Programming with Python. May 4, 2017 Programming with Python May 4, 2017 Python and IPython Python is an interpreter. It translates source code into instructions that the processor can understand. Different ways of running python: python

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

L1/L2 NETWORK PROTOCOL TESTING

L1/L2 NETWORK PROTOCOL TESTING L1/L2 NETWORK PROTOCOL TESTING MODULE 1 : BASIC OF NETWORKING OSI Model TCP/IP Layers Service data unit & protocol data unit Protocols and standards Network What is network & Internet Network core circuit

More information

Exam 1 Format, Concepts, What you should be able to do, and Sample Problems

Exam 1 Format, Concepts, What you should be able to do, and Sample Problems CSSE 120 Introduction to Software Development Exam 1 Format, Concepts, What you should be able to do, and Sample Problems Page 1 of 6 Format: The exam will have two sections: Part 1: Paper-and-Pencil o

More information

EE 355 Unit 17. Python. Mark Redekopp

EE 355 Unit 17. Python. Mark Redekopp 1 EE 355 Unit 17 Python Mark Redekopp 2 Credits Many of the examples below are taken from the online Python tutorial at: http://docs.python.org/tutorial/introduction.html 3 Python in Context Interpreted,

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

AI Programming CS S-02 Python

AI Programming CS S-02 Python AI Programming CS662-2013S-02 Python David Galles Department of Computer Science University of San Francisco 02-0: Python Name python comes from Monte Python s Flying Circus Most python references use

More information

Introduction to Python

Introduction to Python May 25, 2010 Basic Operators Logicals Types Tuples, Lists, & Dictionaries and or Building Functions Labs From a non-lab computer visit: http://www.csuglab.cornell.edu/userinfo Running your own python setup,

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

1 Strings (Review) CS151: Problem Solving and Programming

1 Strings (Review) CS151: Problem Solving and Programming 1 Strings (Review) Strings are a collection of characters. quotes. this is a string "this is also a string" In python, strings can be delineated by either single or double If you use one type of quote

More information

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements Review: Exam 1 9/20/06 CS150 Introduction to Computer Science 1 1 Your First C++ Program 1 //*********************************************************** 2 // File name: hello.cpp 3 // Author: Shereen Khoja

More information