Accelerating Information Technology Innovation

Similar documents
Accelerating Information Technology Innovation

Senthil Kumaran S

The current topic: Python. Announcements. Python. Python

Key Differences Between Python and Java

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

Python: common syntax

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

Python for Non-programmers

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

Lists, loops and decisions

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

MEIN 50010: Python Flow Control

Python for C programmers

Some material adapted from Upenn cmpe391 slides and other sources

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

G Programming Languages - Fall 2012

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

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

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

Java Bytecode (binary file)

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

Basic Syntax - First Program 1

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

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

Pace University. Fundamental Concepts of CS121 1

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

Python Programming: Lecture 2 Data Types

Shell / Python Tutorial. CS279 Autumn 2017 Rishi Bedi

Python Class-Lesson1 Instructor: Yao

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

Scripting Languages. Python basics

Part III Appendices 165

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

CIS192 Python Programming. Robert Rand. August 27, 2015

Introduction to Python

Introduction to Bioinformatics

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

Object-oriented programming in...

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

AI Programming CS S-02 Python

Introduction to Java & Fundamental Data Types

Python for ArcGIS. Lab 1.

Object-Oriented Programming in Java

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

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

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

Compound Data Types 1

18.1. CS 102 Unit 18. Python. Mark Redekopp

S206E Lecture 19, 5/24/2016, Python an overview

Running a C program Compilation Python and C Variables and types Data and addresses Functions Performance. John Edgar 2

Large-Scale Networks

Chapter 3. More Flow of Control. Copyright 2008 Pearson Addison-Wesley. All rights reserved.

Accelerating Information Technology Innovation

Ruby: Introduction, Basics

CSI33 Data Structures

CSC Software I: Utilities and Internals. Programming in Python

Programming in Python

CSC326 Python Imperative Core (Lec 2)

Working with JavaScript

The Pyth Language. Administrivia

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

CHAPTER 2: Introduction to Python COMPUTER PROGRAMMING SKILLS

DaMPL. Language Reference Manual. Henrique Grando

ENGR 102 Engineering Lab I - Computation

GridLang: Grid Based Game Development Language Language Reference Manual. Programming Language and Translators - Spring 2017 Prof.

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

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

C++ for Python Programmers

Repetition Structures

Language Reference Manual

CPE 112 Spring 2015 Exam II (100 pts) March 4, Definition Matching (8 Points)

CIS192: Python Programming

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

MATLIP: MATLAB-Like Language for Image Processing

Python in 10 (50) minutes

CSc 120. Introduc/on to Computer Programing II. Adapted from slides by Dr. Saumya Debray. 01- a: Python review

CS 1301 Exam 1 Fall 2010

Coral Programming Language Reference Manual

And Parallelism. Parallelism in Prolog. OR Parallelism

Lecture 1. basic Python programs, defining functions

Table of Contents EVALUATION COPY

Introduction to Python

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

CS 11 java track: lecture 1

x = 3 * y + 1; // x becomes 3 * y + 1 a = b = 0; // multiple assignment: a and b both get the value 0

Introduction to Python

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Programming to Python

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

CS 115 Lecture 8. Selection: the if statement. Neil Moore

Python and Bioinformatics. Pierre Parutto

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

CS 111X - Fall Test 1 - KEY KEY KEY KEY KEY KEY KEY

Programming Fundamentals and Python

Control Structures. Important Semantic Difference

DEBUGGING TIPS. 1 Introduction COMPUTER SCIENCE 61A

LOOPS. Repetition using the while statement

DATABASE AUTOMATION USING VBA (ADVANCED MICROSOFT ACCESS, X405.6)

Java Overview An introduction to the Java Programming Language

Lecture 05: Methods. AITI Nigeria Summer 2012 University of Lagos.

Transcription:

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 Data Structures Introduction to Functions 2

What is Python? 3

Python is interpreted. Languages like C/C++ need to translate high-level code to machine code High-Level Code a = b + c; Compiler Machine Code ld $r1, a ld $r2, b add $r3, $r1, $r2 st a, $r3 4

Python is which means that a program has to be compiled separately for each type of machine: program compiler compiler compiler machine code machine code machine code Win Mac Unix 5

Python is Python code is compiled to an intermediate format called bytecode, which is understood by a virtual machine/interpreter. Python Source (.py) Python Bytecode (.pyc) compiler 6

Python is Win Interpreter Python Program compiler Python bytecode Mac Interpreter Unix Interpreter 7

Why Python? 8

Python because Portable and architecture-agnostic Convenient built-in functions and data structures Syntax is readable and fast to write if (x) { if (y) { a(); } b(); } if x: if y: a() b() 9

Python because Great for rapid prototyping No separate compile step No need to explicitly specify method argument types beforehand (due to dynamic typing) 10

Python for us, because We want each of you to reach millions of users, and don t want to waste time building the pipes and plumbing Python is supported by a number of good frameworks, led by Django Heroku Google AppEngine 11

The (Ideal) Development Cycle Clearly specify the problem: Inputs, input manipulation, outputs Design the solution: E.g. what algorithms, data structures Implementation Test 12

The (Real) Development Cycle As above, but faster. Python, as a dynamically typed, programming language is perfect for rapid prototyping Be prepared to throw away one (or more!) prototypes Often you learn crucial things about the problem as you code which cannot be fixed without starting from scratch. 13

Basic Syntax 14

Syntax Blocks are delimited with whitespace: specifically, four spaces (and no tabs) if x: if y: a() b() count = 0 for i in range(0:5) count += i 15

Syntax Semicolons are only used to separate multiple statements on the same line, which is discouraged: if (x) { a(); b(); } if x: a(); b() if x: a() b() No Yes 16

Syntax Single line comments are denoted with hash (#), multiline with three quotes # This is a comment foo() This is a longer comment foo() 17

Interaction Python has an interactive console which is great for tinkering $ python Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53) [GCC 4.5.2] on linux2 Type help, copyright, credits or license for more information >>> a = 1 >>> a 1 >>> type(a) <type int > >>> etc 18

Variables Strings >>> x = Hello World Numerics >>> x = 3.1415 Booleans >>> x = True Lists >>> x = [ Hello, True, 3.1415] And many more 19

Variables Python is a dynamically typed language A variable s data type is not declared. Statically typed languages like Java must declare a variable s data type String x = Hello World ; Get a variable s data type with the type function >>> x = Hello World >>> type(x) <type 'str'> 20

Strings 21

Strings A string is a piece of text. Encase with quotes Single-quotes >>> x = abc Double-quotes >>> x = abc Triple single-quotes or triple double-quotes >>> x = abc >>> x = abc 22

Strings Use double-quotes to encase text containing single-quotes >>> It s a string with a singlequote! What is wrong with this statement? >>> x = abc 23

String as a sequence You can access the characters one at a time using the bracket [] operator 1 2 3 fruit = banana letter = fruit[1] print letter index b a n a n a 0 1 2 3 4 5 24

String operators Applied to strings, produce strings 1 2 3 4 5 6 str1 = 'kit ' str2 = 'kat ' str3 = str1 + str2 str4 = str3 * 2 c = str1[0] c = str1[4] 'kit kat ' 'kit kat kit kat ' 'k' IndexError: string index out of range str1 index k i t 0 1 2 3 25

The slicing operator [m : n] Returns the part of the string from the "m-th" character to the "nth" character, including the first but excluding the last. fruit S T R A W B E R R Y index 0 1 2 3 4 5 6 7 8 9 10-10 -9-8 -7-6 -5-4 -3-2 -1 1 2 3 4 str1 = fruit[2:5] str1 = fruit[:5] str1 = fruit[5:] str1 = fruit[6:-1] 'RAW' 'STRAW' 'BERRY' 'ERR' 26

User Input 27

User Input raw_input prints a prompt to the user and assigns the input to a variable as a string input can be used when we expect the input to be a number

Control Statements 29

Control statements Conditionals: control which set of statements is executed. if / else Iteration: control how many times a set of statements is executed. while loops for loops 30

The if statement any boolean expression if CONDITION: BODY any set of statements If the condition is True, the body gets executed. Otherwise, nothing happens. indentation is important if x < 0: print 'x is negative' 31

The if/else statement if CONDITION: BODY1 else: BODY2 any set of statements If the condition is True, body1 gets executed. Otherwise, body2 gets executed. if x < 0: print 'x is negative' else: print 'x is positive or zero' 32

Chained conditionals if CONDITION1: BODY1 elif CONDITION2: BODY2 else: BODY3 another boolean expression any set of statements If the condition1 is True, body1 gets executed. Otherwise, if condition2 is True, body2 gets executed. If neither condition is True, body3 gets executed. 33

An example a = False b = True if a and b: print 'I love red.' elif a or b: print 'I love green.' else: print 'I love blue.' print 'I also love purple.' What does this output? I love green. 34

An example a = False b = True if a and b: print 'I love red.' elif a or b: print 'I love green.' else: print 'I love blue.' print 'I also love purple.' What does this output? I love green. I also love purple. 35

Nested conditionals if is_adult: if is_senior_citizen: print 'Admission $2 off.' else: print 'Full price.' else: print 'Admission $5 off.' outer conditional inner conditional Can get confusing. Indentation helps to keep the code readable and the python interpreter happy! 36

The while loop while CONDITION: BODY any boolean expression any set of statements indentation is important As long as the condition is true, the body gets executed repeatedly. The first time the condition is false, execution ends. 37

The while loop i = 0 while i < 3: print i i = i + 1 What does this output? 0 1 2 38

The break statement Immediately exits the innermost loop. while True: line = raw_input('>>> ') if line == 'done': break print line print 'Done!' >>> not done not done >>> done Done! 39

Useful Data Structures 40

Lists A list is a sequence of values. Each element (value) is identified by an index. The elements of the list can be of any type. tens = [10, 20, 30, 40] cities= [ Manila', Cebu', Boracay ] empty = [] Lists can have mixed types in them, even other lists (nested). mixed = ['hello', 2.0, 5, [10, 20]] 41

Creating a list Use the [] brackets list_of_ints = [10,20,30,50] list_of_ints 10 20 30 50 only one name four int values 42

Accessing list elements Individual elements are accessed using the [] operator. list_of_ints[0] = 17 index Lists are mutable! Assigns the first element to 17 list_of_ints 17 20 30 50 0 1 2 3 now has value 17 List indexing starts at 0, not 1! new_var = list_of_ints[0] accesses the value of the first element list_of_ints 17 20 new_var 17 30 50 now also has value 17 43

Printing a list We can use the print function to output the contents of the list: cities = [ Cali, Bogotá, Medellin ] numbers = [17, 123] empty = [] print cities, numbers, empty [ Cali, Bogotá, Medellin ] [17, 123] [ ] 44

Lists vs. Strings Lists are mutable - their contents can be modified Strings are immutable name = 'Lenny' name[0] = 'J' TypeError: object doesn't support item assignment 45

Control Structures 46

The for loop sequence element Sequence of values list, string, etc. for ELEMENT in SEQUENCE: BODY Example: any set of statements indentation is important for i in [0,1,2,3]: print i 0 1 2 3 47

Using range index variable generates sequence of n values starting at 0 and incrementing by 1 for INDEX in range(n): BODY any set of statements What does this output? for i in range(4): sq = i * i print i, sq 0 0 1 1 2 4 3 9 48

Using range index variable generates sequence of values start and step are optional for INDEX in range([start], stop, [step]): BODY What does this output? any set of statements for i in range(1, 7, 2): print i 1 3 5 49

For loop and strings Iterating through the characters of a string str1 = 'stressed' for c in str1: print c, s t r e s s e d 50

For vs While For loop is primarily used for iterating over a sequence of values when we know the number of iterations in advance While loop is primarily used when we don't know the number of iterations in advance (they could be controlled by user input) 51

Introduction to Functions 52

Functions A function is a sequence of statements that has been given a name. function name list of function arguments def NAME (PARAMETERS): STATEMENTS function definition any set of statements function signature 53

Now you are all set to work on Lab 1! 54

Lab 1 1. Calculate Fibonacci number fib(n) 2. Display the day of the week given a date zellers() 3. Implement the Rock Paper Scissors game rock_paper_scissors() 4. Encode a given string using the Caesar cipher cipher() 55

Next Class More on Functions Object Oriented Programming Exceptions Regular Expressions How to be a Python Ninja! 56