Introduction to Python - Part I CNV Lab

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

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

Pace University. Fundamental Concepts of CS121 1

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration

Downloaded from Chapter 2. Functions

Senthil Kumaran S

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

DSC 201: Data Analysis & Visualization

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

CSCE 110 Programming I

Introduction to Python

CS 102 Lab 3 Fall 2012

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

Introduction to Java Applications

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

Introduction to: Computers & Programming: Review prior to 1 st Midterm

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

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

Table of Contents EVALUATION COPY

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

CHAPTER 2: Introduction to Python COMPUTER PROGRAMMING SKILLS

COMP519 Web Programming Lecture 17: Python (Part 1) Handouts

CSC Software I: Utilities and Internals. Programming in Python

Introduction to Python

LISTS WITH PYTHON. José M. Garrido Department of Computer Science. May College of Computing and Software Engineering Kennesaw State University

Some material adapted from Upenn cmpe391 slides and other sources

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

Key Differences Between Python and Java

And Parallelism. Parallelism in Prolog. OR Parallelism

Babu Madhav Institute of Information Technology, UTU 2015

15-122: Principles of Imperative Computation

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

Shell / Python Tutorial. CS279 Autumn 2017 Rishi Bedi

CIS192: Python Programming

JavaScript Basics. The Big Picture

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

Basic Syntax - First Program 1

ENGR 101 Engineering Design Workshop

CMSC 201 Fall 2015 Lab 12 Tuples and Dictionaries

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

TEXT MINING INTRO TO PYTHON

Midterm 1 Review. Important control structures. Important things to review. Functions Loops Conditionals

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

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

Introduction to Python

Statements 2. a operator= b a = a operator b

Lists, loops and decisions

PRG PROGRAMMING ESSENTIALS. Lecture 2 Program flow, Conditionals, Loops

age = 23 age = age + 1 data types Integers Floating-point numbers Strings Booleans loosely typed age = In my 20s

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

Introduction to Python. Fang (Cherry) Liu Ph.D. Scien5fic Compu5ng Consultant PACE GATECH

Python: common syntax

Variables, expressions and statements

Lecture 4. Defining Functions

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

CS2304: Python for Java Programmers. CS2304: Sequences and Collections

Accelerating Information Technology Innovation

Java Programming Fundamentals - Day Instructor: Jason Yoon Website:

Advanced Algorithms and Computational Models (module A)

Accelerating Information Technology Innovation

Python Programming Exercises 1

Basic Python 3 Programming (Theory & Practical)

COMP 2718: Shell Scripts: Part 1. By: Dr. Andrew Vardy

C++ for Python Programmers

Compound Data Types 1

EXPRESSIONS, STATEMENTS, AND FUNCTIONS 1

Lecture 1. basic Python programs, defining functions

Simple Java Programming Constructs 4

Python Input, output and variables

Python for Non-programmers

Lecture 6. Assignments. Summary - Variables. Summary Program Parts 1/29/18. Reading: 3.1, 3.2, 3.3, 3.4

Python Programming, bridging course 2011

8. Control statements

Python Input, output and variables. Lecture 22 COMPSCI111/111G SS 2016

Using IDLE for

R programming I expressions, variables, and data types. Luigi Cerulo University of Sannio

Copied from: on 3/20/2017

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

Control Structures. CIS 118 Intro to LINUX

Flow Control: Branches and loops

An Interactive Desk Calculator. Project P2 of. Common Lisp: An Interactive Approach. Stuart C. Shapiro. Department of Computer Science

CPS122 Lecture: From Python to Java last revised January 4, Objectives:

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Getting Started. Office Hours. CSE 231, Rich Enbody. After class By appointment send an . Michigan State University CSE 231, Fall 2013

Chapter 2. Editing And Compiling

Welcome to Python 3. Some history

Programming for Engineers in Python. Autumn

The current topic: Python. Announcements. Python. Python

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

Chapter 2 Programming in Python

Haskell: Lists. CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Friday, February 24, Glenn G.

CSCA20 Worksheet Strings

Introduction to Python, Cplex and Gurobi

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

example: name1=jan name2=mike export name1 In this example, name1 is an environmental variable while name2 is a local variable.

Lecture 12 Programming for automation of common data management tasks

The Three Rules. Program. What is a Computer Program? 5/30/2018. Interpreted. Your First Program QuickStart 1. Chapter 1

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

corgi Language Reference Manual COMS W4115

CPS122 Lecture: From Python to Java

Transcription:

Introduction to Python - Part I CNV Lab Paolo Besana 22-26 January 2007 This quick overview of Python is a reduced and altered version of the online tutorial written by Guido Van Rossum (the creator of Python), that can be found at the URL: http://docs.python.org/tut/tut.html 1 Interpreter A great advantage of Python is the option of launching the interpreter and directly executing commands. This can save a lot of time when you are developing software: when you are not sure about something, you can often test it directly from the interpreter, without the overhead of having a small program to launch from the command line. The interpreter is launched by typing the following command in the shell: python Once the interpreter has been launched, lines previously inserted in the interpreter shell can be recalled pressing the cursor button. To exit the interpreter, press Control-D. To launch a program written in Python, type the following command from the shell: python programname.py Open a terminal window. Create a new directory called " MyPython ": s0xxxxx: mkdir MyPython Go to this directory: s0xxxxx: cd MyPython Launch Python Interpreter: s0xxxxx: python 2 Basic Programming Unlikely most other programming languages, in Python, the formatting of the code has a meaning: there are no braces or begin/end delimiters around blocks of code: groups of statements are indented under a header. Blocks of code can be nested, using increasing indentation. There are no end-of-line symbols, like the semicolon (;) in Java or C: the new line marks the end of a line. 1

2.1 Basic Types Numbers The interpreter can be used as a simple calculator. Enter the following expression in the python interpreter you have just launched: >>> 2+2 >>> 3*2 Strings Strings can be enclosed in single or double quotes. >>> 'hello' >>> 'how\'s going?' >>> "how's going?" Strings can be enclosed in pairs of triple quotes, either """ or '. In this case it is not necessary to escape end of lines. >>> print """ This is a string that when printed mantains its format. """ Strings can be concatenated using the + operator, and can be repeated with the operator *. >>> 'Hello ' + ', ' + 'how are you' >>> 'help' + '!'*5 The individual characters of a string can be accessed using indices. The rst character has index 0. Substrings can be specied with slice notation: two indices separated by colon. When using slices, indices can be thought as pointing between character, instead of pointing to characters: the left edge of the rst character is 0 and so on. >>> word="hello" >>> word[0] >>> word[2] >>> word[2:4] 2

>>> word[:2] >>> word[2:] Negative indices start to count from the right. >>> word[-1] >>> word[-2:] upper() and lower() convert the characters of a string into upper case and lower case: >>> 'Hello!'.upper() >>> 'Hello!'.lower() strip() function removes the spaces at the beginning and at the end of the string: >>> ' Hello! '.strip() Strings cannot be modied once they are created. Trying to modify a substring results in an error. However, it is easy to create a new string concatenating substrings from other strings. Lists There are dierent types of compound structures in Python. The most versatile is the list. >>> L = ['mon','tue','wed','thu','fri'] >>> L List items can also be accessed using indices. They can be sliced and concatenated like strings. 3

>>> L[0] >>> L[3] >>> L[1:3] >>> L + ['sat','sun'] It is possible to check the membership of an element in a list using the keyword in. >>> 'wed' in L >>> 'sun' in L Items can be added at the end of a list using the method append(item) of the list object. >>> L3 = [] >>> L3.append(1) >>> L3.append(2) >>> L3 It is possible to measure the length of a list using the built-in function len(list). >>> len(l) 2.2 Control Structures Python oers the usual control ow statements, as other languages like Java or C. The for loop is more powerful than in most of the other languages. if [When asked, insert a binary sequence (such as 00101 or 10010)] >>> x=rawinput("enter a binary sequence : ") >>> if (x[0]=='0'): print "Starts with 0" elif (x[0] == '1'): print "Starts with 1" else: print "Error" It is possible to create more complex conditions using the keywords and for conjunction and or for disjunction. 4

while The while statement repeats the indented block of code as long as the condition is true: >>> x = 10 >>> while (x > 0): print x x = x - 1 for The for statement iterates over the items of any sequence (such as strings or lists). [the variable L has already been assigned by you (see page 3)] >>> for x in L: print x To iterate over a sequence of numbers the built-in function range() is used to automatically generate them. >>> range(5,10) >>> for x in range(3): print x >>> for x in xrange(3): print x (Here xrange() is a variant of range() that is optimized for use in for loops; it generates each element as it is needed rather than requiring a big chunk of memory at the start.) Exercise 1 Type: >>> Lst = ['how', 'why', 'however', 'where', 'never'] Write a loop in the python interpreter (which should still be open) that prints for every element in the list: a star symbol * the rst two letters from the element the whole element 5

producing something like: * ho how * wh why Exercise 2 Modify the previous loop to print a star ('*') in front of the elements that start with wh and a plain space ` ' in front of the others, producing something like: ho how * wh why 2.3 Functions A function is introduced by the keyword def. It must be followed by the function name and by the list of parameters in parenthesis. The statements that form the function body start the next line, and are indented. The rst line can be an optional string that describes the function. This string can be used by automatic generators of documentation. >>> def square(value): """Return the square of the value""" return value*value >>> square(4) Exercise 3 Write a function checkprefix(list, prefix) in the python interpreter (which should still be open). The function wraps the loop created in the previous exercise: when called it must print the content of the list, adding a star in front of the elements that start with the prex. 2.4 List Comprehensions List comprehensions provide a concise and clear way to create lists, which is often quite important for writing readable and maintainable Python code. Each list comprehension consists of an expression followed by a for clause, then zero or more for or if clauses. The result will be a list resulting from evaluating the expression in the context of the forandifclauses that follow it. If the expression would evaluate to a tuple, it must be parenthesized. >>> freshfruit = [' banana', ' loganberry ', 'passion fruit '] >>> [w.strip() for w in freshfruit] 6

>>> v = [2, 4, 6] >>> [3*x for x in v] The if clause is used to lter the elements that have to appear in the generated list: >>> [3*x for x in v if x > 3] >>> [3*x for x in v if x < 2] >>> [[x,x**2] for x in v] >>> [(x, x**2) for x in v] It possible to combine items from dierent lists, obtaining a Cartesian product of elements, using a for clause for each list : >>> v1 = [2, 4, 6] >>> v2 = [4, 3, -9] >>> [x*y for x in v1 for y in v2] >>> [x+y for x in v1 for y in v2] >>> [v1[i]*v2[i] for i in range(len(v1))] >>> [str(round(355/113.0, i)) for i in range(1,6)] Exercise 4 Using list comprehension: Write code that converts the elements in the following list: L4 = ['hello', 'how', 'are', 'you'] into upper case Write code that generates a list containing only the even numbers, divided by 2, from the following list: L5 = [3, 52, 21, 43, 12, 18, 17] Hint: a number is even if the remainder of a division by 2 is equal to 0 (the remainder is obtained using %: 4%2==0, 5%2==1) 7

Write code that generates, from the following list, a list containing pairs composed of the values and their parity values: L5 = [3, 52, 21, 43, 12, 18, 17] Each pair is a list composed of two elements: the value itself, and true if value is even or false otherwise 2.5 Modules Programs can become long, and it is a good approach to divide them into more manageable units. In Python, programs can be divided into modules. The modules can be imported directly into the interpreter or into other programs. Python has a very large library of predened functions and classes that can be imported and used. >>> import math When we call the function, it is necessary to prex it with the module name, to avoid name conicts: >>> math.pi >>> math.pow(2,5) We can also import only the function we need, and in this case it is not necessary to prex it with the module name. >>> from math import pow >>> pow(2,5) If you modify a le, you need to reload the module using reload(modulename), although this doesn't always do what you might expect because itdoes not reload anything the module depends on. End your interpreter session (CTRL+D) 8