CSC326 Python Imperative Core (Lec 2)

Similar documents
Functions. Python Part 3

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

Functions and Recursion

Pace University. Fundamental Concepts of CS121 1

Full file at C How to Program, 6/e Multiple Choice Test Bank

Working with JavaScript

Language Reference Manual

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

FUNCTION PARAMETER AND ARGUMENT

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

CS 1301 Exam 1 Answers Fall 2009

Language Proposal: tail

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

Introduction to Bioinformatics

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

Introduction to Python

Programming in Python 3


Python for Informatics

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

Coral Programming Language Reference Manual

Algorithms and Programming I. Lecture#12 Spring 2015

Variables, expressions and statements

Python Boot Camp. Day 3

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

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

CHAPTER 2: Introduction to Python COMPUTER PROGRAMMING SKILLS

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

7/8/10 KEY CONCEPTS. Problem COMP 10 EXPLORING COMPUTER SCIENCE. Algorithm. Lecture 2 Variables, Types, and Programs. Program PROBLEM SOLVING

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Full file at

Introduction to Computer Programming CSCI-UA 2. Review Midterm Exam 1

Fundamentals of Programming (Python) Getting Started with Programming

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

Getting Started with Python

C and C++ I. Spring 2014 Carola Wenk

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

Chapter 2: Introduction to C++

PROGRAMMING FUNDAMENTALS

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

Language Design COMS W4115. Prof. Stephen A. Edwards Spring 2003 Columbia University Department of Computer Science

AN OVERVIEW OF C, PART 3. CSE 130: Introduction to Programming in C Stony Brook University

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

Downloaded from Chapter 2. Functions

9/5/2018. Overview. The C Programming Language. Transitioning to C from Python. Why C? Hello, world! Programming in C

Computer Components. Software{ User Programs. Operating System. Hardware

DM536 Introduction to Programming. Peter Schneider-Kamp.

The C Programming Language. (with material from Dr. Bin Ren, William & Mary Computer Science)

COP4020 Programming Assignment 1 - Spring 2011

DEBUGGING TIPS. 1 Introduction COMPUTER SCIENCE 61A

Accelerating Information Technology Innovation

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators

Python Programming Exercises 1

LECTURE 02 INTRODUCTION TO C++

Chapter 2 Basic Elements of C++

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG

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

corgi Language Reference Manual COMS W4115

Java Bytecode (binary file)

Introduction to Python (All the Basic Stuff)

Key Differences Between Python and Java

Lecture 2 Tao Wang 1

Chapter 4: Control Structures I (Selection) Objectives. Objectives (cont d.) Control Structures. Control Structures (cont d.

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

CSI33 Data Structures

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

Recap: Assignment as an Operator CS 112 Introduction to Programming

1 Lexical Considerations

>>> * *(25**0.16) *10*(25**0.16)

Act like a code monkey Coding Basics

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE?

Fundamentals of Programming Session 13

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

8. Control statements

C++ Support Classes (Data and Variables)

Your First C++ Program. September 1, 2010

Python for C programmers

Objectives. In this chapter, you will:

Accelerating Information Technology Innovation

Creating a C++ Program

Computer Components. Software{ User Programs. Operating System. Hardware

27-Sep CSCI 2132 Software Development Lecture 10: Formatted Input and Output. Faculty of Computer Science, Dalhousie University. Lecture 10 p.

Senthil Kumaran S

Java for Python Programmers. Comparison of Python and Java Constructs Reading: L&C, App B

Introduction to Programming Using Java (98-388)

CS 112 Introduction to Programming

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

Lecture Numbers. Richard E Sarkis CSC 161: The Art of Programming

Scripting Languages. Python basics

egrapher Language Reference Manual

CSE101-lec#12. Designing Structured Programs Introduction to Functions. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU

Python for Analytics. Python Fundamentals RSI Chapters 1 and 2

Chapter 2. Lexical Elements & Operators

Conditionals and Recursion. Python Part 4

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

DaMPL. Language Reference Manual. Henrique Grando

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

Module 01: Introduction to Programming in Python

Syntax and Variables

Transcription:

i CSC326 Python Imperative Core (Lec

ii REVISION HISTORY NUMBER DATE DESCRIPTION NAME 1.0 2011-09 JZ

iii Contents 1 Agenda 1 2 Invoking Python 1 3 Value, Type, Variable 1 4 Keywords 2 5 Statement 2 6 Expression 2 7 Comment 3 8 Module 3 9 Defining Functions 4 10 Conditional 5 11 Recursion 6 12 Incremental Development 7 13 Recap 8

1 / 8 1 Agenda Python imperative core value, type, variable expression, statement module Incremental development w/t Python 2 Invoking Python Interactive mode >python Python 2.6.1 (r261, Mar 18 2009, 15:53:57) [GCC 3.2.2] on sunos5 Type "help", "copyright", "credits" or "license" for more information. >>> Script mode >python foo.py 3 Value, Type, Variable Value: Basic unit of data program manipulates Type: A category of values (or a set of values) A type itself is also a value! Variable: name that refers to a value >>> print Hello, World! Hello, World >>>print 4 4 >>> type(4) <type int > >>> type( 4 ) <type str > >>> type( 3.2 ) <type float > >>> message = hi >>> n = 17 >>> pi = 3.14 >>> print n 17 >>> print pi 3.14 >>> type(pi) <type float >

2 / 8 Note String could be single quoted and double quoted To print "hey" In C printf ("\"hey\" ); print "hey" No ; after a statement! Hex/Oct number representation the same as C >>>zipcode = 02492 SyntaxError: invalid token 4 Keywords 31 keywords 5 Statement print statement (obsolete for 3.0) assignment more to come 6 Expression functions (same as C) type(.) was a function function application function composition a( b(v1) ) operators special symbols representing builtin functions apply on operands (unary or binary) arithmetic: + - / ˆ % (just like C) 5*2: exponentiation (Not in C) relational: ==!= > < >= logical: and, or, not operator precedence

3 / 8 () Exponentiation * /... operator valid for strings (Not in C) +: concetation *: repetition print hello + world => helloworld print Spam *3 => SpamSpamSpam type conversion foo( v ), where foo is a type between numbers: int(3.9) 3, float(-2.3) -2 between number and string: float(3.14) 3.14 7 Comment Single line: # (// as in C++) #here is a commented statement v = 5 #assign 4 to v 8 Module Modular programming Encapsulate functions and variables Prevent name conflit with. notation Similar to C++ namespace Build Library to extend functionality: Batteries! >>> import math >>> type( math ) <type module > >>> print math <module math from blahblahblah./math.so > >>> ratio = signal_power / noise_power >>> decibels = 10 * math.log10( ratio ) Note math is a value of type module!

4 / 8 9 Defining Functions We see how to use functions Let s create our own def print_lyrics() : print "I am a lumberjack, and I am OK." print "I sleep all night and I work all day." Note def is a keyword paranthesis enclose function parameters header (first line end with colon) body end a function with empty line (if interactive mode) function is nothing but a value Important body has to be indented! use space, not tab to avoid confusion No curly braces! (if indented anyway for readibility, why the waste?) >>> print print_lyrics <function print_lyrics at 0xb8e99e9c> >>> print type(print_lyrics) <type function > >>> print_lyrics() Function can call functions def repeat_lyrics() : print_lyrics() print_lyrics() Function taking parameters def print_twice( bruce ) : print bruce print bruce Local variables

5 / 8 def cat_twice( part1, part2 ) : cat = part1 + part2 print_twice( cat ) variables do NOT need to be declared at all variables types are inferred However, has to be DEFINED (assigned a value) before USED scoping rule applies (just like C) 10 Conditional Conditional header followed by indented body at least ONE statements in body If you don t have one, or wants to come back later, use pass statement if x > 0 : print x is positive if x < 0 : pass if 0 < x and x < 10 : pass # does nothing! if x % 2 : print x is even print x is odd Chained conditional if choice == a : draw_a() elif choise == b : draw_b() elif choice == c : draw_c() Nested conditional avoid if you could use chained conditional if x == y : pass if x < y : pass pass

6 / 8 11 Recursion Define base case Recurse Avoid infinite recursion! def count_down( n ) : if n <= 0 : print Blastoff! print n countdown( n-1 ) compute factorial: 0! = 1 n! = n ( n - 1 )! def factorial( n ) : if n == 0 : return 1 # basecase recurse = factorial( n - 1 ) result = n * recurse Add debugging def factorial( n ) : space = * (4*n) # amount of identation with repeat operator print space, calling, n if n == 0 : print space, returning 1 return 1 recurse = factorial( n - 1 ) result = n * recurse print space, returning, result What would happen if we have factorial( 1.5 ) Add type checking def factorial( n ) : if not isinstance(n,int) : #runtime type checking, not in C return None if n == 0 : return 1 recurse = factorial( n - 1 ) result = n * recurse

7 / 8 Note Contract based programming with preconditions def factorial( n ) : assert isinstance(n,int) if n == 0 : return 1 recurse = factorial( n - 1 ) result = n * recurse Computing fibnacci series def fibonacci( n ) : if n < 2 : return n recurse1 = fibonacci( n - 1 ) recurse2 = fibonacci( n - 2 ) return recurse1 + recurse2 12 Incremental Development We have seen how to use pass In general, code could be developed incrementally compute Euclidean disstance = sqrt( (x2-x1) 2 + (y2-y1) 2 ) Make it run first! (it does not have to be right) def distance( x1, y1, x2, y2 ) : return 0.0 Now you could at least use it with right parameters Advantage of interpretive language: no recompile >>> distance( 1, 2, 4, 6 ) 0.0 Add more code (including debugging code) def distance( x1, y1, x2, y2 ) : dx = x2 - x1 dy = y2 - y1 print dx is, dx print dy is, dy return 0.0 Add more code (including debugging code: scaffolding)

8 / 8 def distance( x1, y1, x2, y2 ) : dx = x2 - x1 dy = y2 - y1 print dx is, dx print dy is, dy dsquared = dx**2 + dy**2 print dsquared is, dsquared result = math.sqrt( dsquared ) Finalize (remove debug code) def distance( x1, y1, x2, y2 ) : dx = x2 - x1 dy = y2 - y1 dsquared = dx**2 + dy**2 result = math.sqrt( dsquared ) 13 Recap Imperative core We have covered a small set of Python variables: to hold values expression: to compute statement: state transition Turing completeness But according to Turing, it is complete Infinite tape: function recursion Important Anything could be computed with this sub-language! Development Interperative language: no compilation-link-run cycle Coding style "enforced": intentatation is part of syntax Encourage incremental development interface first (contract with outside) test first algorithm skeleton first (use pass) scaffolding: insert debug code