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

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

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

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

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

ENGR 101 Engineering Design Workshop

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

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

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

The current topic: Python. Announcements. Python. Python

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

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

Introduction to Python

Some material adapted from Upenn cmpe391 slides and other sources

Programming in Python 3

Getting Started Values, Expressions, and Statements CS GMU

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

Programming to Python

Advanced Python. Executive Summary, Session 1

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

And Parallelism. Parallelism in Prolog. OR Parallelism

Introduction to Bioinformatics

All programs can be represented in terms of sequence, selection and iteration.

Lists, loops and decisions

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

Python for Non-programmers

Data Structures. Lists, Tuples, Sets, Dictionaries

Python for C programmers

Python Tutorial. CSE 3461: Computer Networking

Getting Started with Python

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

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

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

Play with Python: An intro to Data Science

Fundamentals of Programming (Python) Getting Started with Programming

Babu Madhav Institute of Information Technology, UTU 2015

Full file at

Python: common syntax

18.1. CS 102 Unit 18. Python. Mark Redekopp

Table of Contents EVALUATION COPY

Coral Programming Language Reference Manual

UNIVERSITÀ DI PADOVA. < 2014 March >

Python Intro GIS Week 1. Jake K. Carr

CS Advanced Unix Tools & Scripting

Sequence types. str and bytes are sequence types Sequence types have several operations defined for them. Sequence Types. Python

Introduction to Python

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

Python debugging and beautification

Chapter 2 Getting Started with Python

Introduction to Programming in Python (1)

Strings and Testing string methods, formatting testing approaches CS GMU

Algorithms and Programming I. Lecture#12 Spring 2015

Introduction to Python. Genome 559: Introduction to Statistical and Computational Genomics Prof. James H. Thomas

Introduction to Python. Genome 559: Introduction to Statistical and Computational Genomics Prof. James H. Thomas

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

Try and Error. Python debugging and beautification

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

Java Bytecode (binary file)

python 01 September 16, 2016

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

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

Lecture 3. Strings, Functions, & Modules

PHP. Interactive Web Systems

egrapher Language Reference Manual

Part III Appendices 165

Python Review IPRE

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

Worksheet 6: Basic Methods Methods The Format Method Formatting Floats Formatting Different Types Formatting Keywords

Introduction to Python

Lecture 3. Functions & Modules

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

COMP-520 GoLite Tutorial

STSCI Python Introduction. Class URL

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

CSI33 Data Structures

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

Monty Python and the Holy Grail (1975) BBM 101. Introduction to Programming I. Lecture #03 Introduction to Python and Programming, Control Flow

CIS192: Python Programming

CPSC 217 Midterm (Python 3 version)

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

Flow Control: Branches and loops

CS 25200: Systems Programming. Lecture 10: Shell Scripting in Bash

Scripting Languages. Python basics

Control Structures 1 / 17

Python. Karin Lagesen.

Python. Executive Summary

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

Language Reference Manual

Variables and literals

Lecture 2 Tao Wang 1

MITOCW watch?v=rvrkt-jxvko

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

The Pyth Language. Administrivia

Constants. Variables, Expressions, and Statements. Variables. x = 12.2 y = 14 x = 100. Chapter

OOP and Scripting in Python Advanced Features

A Little Python Part 1. Introducing Programming with Python

Python Lists. Stéphane Vialette. LIGM, Université Paris-Est Marne-la-Vallée. October 5, 2011

CS 11 python track: lecture 3. n Today: Useful coding idioms

A new data type: Lists. March 5, 2018 Sprenkle - CSCI Ø How can we convert from the numerical representa9on to the character?

6. Data Types and Dynamic Typing (Cont.)

Flow Control. So Far: Writing simple statements that get executed one after another.

Transcription:

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

Introduction to Python Common Data Types If Statements For and While Loops Basic I/O Lecture Summary 2

What is Python? Python is a flexible programming language Procedural like C Object-oriented like C++, Java and C# Functional like LISP, Haskell, Scheme, Scala Python is a high-level language Has a rich set of high-level data types and functions (standard library) Runs on many platforms and operating systems Windows, Linux/Unix, Mac OS and much more 3

What is Python? Python is designed to be simplistic Very simple and consistent syntax Easy to read and write Interactive like a shell 4

What is Python? Most Python implementations have an interactive mode Some implementations provide more interactive features than others Examples: IDLE, IPython 5

No braces { } Syntax and Features Indentation is used to indicate code blocks No semicolon at the end of a statement Unless needed to separate multiple statements on one line No $ preceding variable names 6

Making a Python Script Put the Shebang: #! on the first line #! /usr/bin/env python3.4 This line invokes the env program to get the path to python Comments are indicated using a # mark. 7

The Traceback When Python crashes, you will see a message like Traceback (most recent call last): File "./tables.py", line 12, in <module> x_start = float(sys.argv[3]) ValueError: invalid literal for float(): c Read it carefully, starting from the bottom and working upwards. It is usually very accurate in pinpointing errors It can save you a lot of time debugging Debugging Python is easy compared to Bash 8

Interactive Mode Interactive Python: Useful for testing out things you're not sure about Useful for prototyping algorithms Invoke at the command line with: python ipython idle (graphical version) Comes with a built in help function: >>> help(list) >>> import sys >>> help(sys) 9

Data Types and Dynamic Typing Unlike C, variables are not declared with types The C language uses static typing All variables must be given an explicit type during before you can compile your program Semantics are defined by the set of functions and properties of the object No need to define variable, nor define their type. If it looks like a duck and quacks like a duck, it must be a duck 1 Check the data-type of any variable using the type() function 1. Source: http://docs.python.org/glossary.html#term-duck-typing 10

Built-in Constants Python defines several constants True true value False false value None indicates the absence of value, like NULL Do NOT mistake with strings: 'True', 'False', 'None' 11

Built-in Numeric Data Types int Unlimited magnitude integer 1234567890123456789012345678901234567 Size only limited by available memory (and your time) float - Floating point number 64-bit double precision numbers complex Complex numbers Represented as two floating point values Z = 1.2 + 7.5j 12

Truthiness Python will evaluate any object for truth in the context of a conditional or Boolean operation The following values will evaluate to False False None 0, 0.0, 0j (), [], '' 13

Truthiness (2) Anything that does not evaluate to False evaluates to True Just because it evaluates to False does not mean it is False An empty tuple () is not an empty list [] None evaluates to False but False!= None But 0.0 is 0 14

Comparison Operators Operator A == B A!= B A < B A <= B A > B A >= B A in B A not in B A is B Function True if A is equal to B True if A is not equal to B True if A is less than B True if A is less than or equal to B True if A is greater than B True if A is greater than or equal to B True if A is an element in B True if A is not an element in B True if A has the object identity B Note: the in operator only works with collections 15

Boolean Operators Operator A and B A or B not A Function True if A and B are both True True if either A or B is True True if A is False Do NOT confuse with bitwise operators: &,, and ~ 16

Operator Precedence Precedence is listed from highest to lowest *, /, % +, - <, <=, >, >=,!=, == in, not in not and or Parenthesis are used to change the evaluation order, or improve readability. 17

Strings Single quotes in pairs allow " without escaping Double quotes in pairs allow ' without escaping Triple quotes (single or double) in pairs allow either single or double quotes and newlines with escaping There are no other differences in quote types. X = "This isn't \"funny\" -- \\' not needed" X = 'This isn\'t "funny" -- \\\' needed' Y = "Don't quote \"me\" -- \\\" needed" Y = 'Don\'t quote "me" -- \\" not needed' Z = """Don't quote "me"""" Z = '''Don't quote "me"''' 18

Strings (1) str A string of characters My_string = "Hello World!" Name = "Goldfarb" Use the len() function to get the length of any string len(my_string) # 12 len(name) # 8 19

Strings (2) Strings can be easily concatenated using the addition (+) operator Var1 = "Hello" + " World" Var2 = Var1 + ", how is the weather?" 20

StrVar.rstrip() Strings (3) returns a new copy of the string with whitespace removed from the right side. StrVar.lstrip() returns a new copy of the string with whitespace removed from the left side. StrVar.strip() returns a new copy of the string with whitespace removed from both sides. 21

StrVar.split() Strings (4) splits StrVar into a list on whitespace Q: What is the difference between: StrVar.split() and StrVar.split(" ")? StrVar.split(delim) splits StrVar into a list on the string delim StrVar.split(delim, n) splits StrVar into a list on the first n occurrences of the string delim 22

Strings (5) Data = " mgoldfar,ee364a01,10.6 " # Clean off any extra whitespace Data = Data.strip() # Split into list of strings Cols = Data.split(",") # Cols[0] is 'mgoldfar' # Cols[1] is 'ee364a01' # Cols[2] is the string '10.6' 23

Strings (6) delim.join(strlist) returns a string with each string in StrList separated by the string delim Sep = "?" Items = ["Baz", "Foo", "Bar"] ItemsStr = Sep.join(Items) # ItemsStr is "Baz?Foo?Bar" # You can inline the separator string also! ItemsStr = ",".join(items) # ItemsStr is "Baz,Foo,Bar" 24

Lists list is a built-in Python data type Much more powerful than plain old arrays Can also be used to implement stacks and queues Lists are containers of things (objects) Items need not be of the same data type A = [1, 2, 3, 4] B = [1, "Big Deal", [1, 2], 6.7J] 25

Lists (2) Lists are mutable, elements can be reassigned: A = [1, 2, 3] A[0] = "First" Use the len(x) function to return the length of a list len(a) # Returns 3 Lists are not sparse an index must exist A[9] = "foo" # Illegal - causes a runtime error 26

Indexing Negative indices are allowed in Python X = ["1st", "2nd", "3rd"] X[0] = X[-3] = "1st" X[1] = X[-2] = "2nd" X[2] = X[-1] = "3rd" 0 is the index of the leftmost item -1 is the index of the rightmost item 27

Slicing Slicing is a way to extract multiple elements from lists, tuples and strings. A[M:N] A[M:N:S] A[M:] A[:N] A[:] A slice of elements starting from index M and ending at index N-1 A slice of elements starting from index M and ending at index N-1, with a step S A slice of elements starting from index M A slice of elements starting from index 0 and ending at index N-1 A slice containing all elements of A 28

Slicing (2) Many things in Python can be sliced. List, tuples and strings just to name a few A = [1, 2, 3, 4, 5] B = "ECE 364 is only 1 credit hour." A[2:4] is [3, 4] B[4:7] is '364' A[:3] is [1, 2, 3] 29

List Functions list.append(x): Add an item to the end of the list. l = [2, 5] l.append(13) # l = [2, 5, 13] list.extend(l): Extend the list by appending all the items in the given list. l = [2, 5] g = [7, -6] l.extend(g) # l = [2, 5, 7, -6] Another way to extend a list is to use the addition operator (+) Note: You must use a list on both sides of the operator! T = ["Mike", "Greg"] T = T + ["Sudhir"] # Or T += ["Sudhir"] # T is ['Mike', 'Greg', 'Sudhir'] 30

List Functions (2) list.insert(i, x): Insert an item at a given position. list.remove(x): Remove the first item from the list whose value is x. It is an error if there is no such item. list.clear():remove all items from the list. Equivalent to del a[:]. list.index(x): Return the index in the list of the first item whose value is x. It is an error if there is no such item. You can use the in operator to test for membership. m = [3, 2, 6, 11, 2, 15, 77] 9 in m # Result in False 11 in m # Result in True list.count(x): Return the number of times x appears in the list. 31

List Functions (3) list.sort(): Sort the items of the list in place. list.reverse(): Reverse the elements of the list in place. list.copy(): Return a copy of the list. Equivalent to b=a[:]. Note: copy creates a shallow copy. # If you do c = l instead of using copy(), then c & l both # point to ['IN', 'MI', 'OH', 'IL', 'CA']. # If you change l, c will also change. del ListVar[i:j]: Removes the items i to j-1 from the list. (You can also use del with/without indexing. 32

File I/O The preferred method to open files is using the with keyword. The with keyword is a shorthand for a lot of work in the background to ensure resources are claimed by the system when done. Can be used for both reading and writing. 33

File I/O (2) Example 1: Reading the file as a list of lines. # This is called a "with-block" # The "myfile" below is called the file alias. # 'lines' is a list of strings. with open('textfile.txt', 'r') as myfile: lines = myfile.readlines() Example 2: Reading the file as a single string. # 'content' is a single string of the whole file. with open('textfile.txt', 'r') as myfile: content = myfile.read() 34

File I/O (3) Example 3: Writing a list of strings. # The list of strings must already contain the "\n" with open('textfile.txt', 'w') as myfile: myfile.writelines(lines) Example 4: Writing a single string. # Construct the string before you write it. with open('textfile.txt', 'w') as myfile: myfile.write(content) 35

Type Conversion There is no casting from one type to another in Python New values can be created from other values of different types If a new value can not be created python will raise an exception int(x) Attempts to create a new integer from x float(x) Attempts to create a new float from x str(x) Attempts to create a new string from x complex (re, im) Attempts to create a complex number. 36

Type Conversion (2) str(var) Create a new string from Var. int(strvar) Create a new integer from StrVar. int(strvar, base) Create a new integer from StrVar in base base float(strvar) Create a new floating point number from StrVar 37

if Statement Behaves just like any other if statement you have encountered Colons are required at the end of each conditional expression if <condition1>: statements elif <condition2>: statements else: statements Note: Python does not have a switch statement. 38

for Loops Python supports only one style of for loop: for <variable> in <sequence>: statements Example: Sum = 0 for Item in [2, 4, -2, 5]: Sum = Sum + Item print(sum) Loop execution can be modified with break and continue 39

while Loops while <condition>: statements when condition is true j = 10 while j > 0: print(j) j -= 1 Avoid using while loops in place of for loops, as it is harder to debug. 40

range Function Range can generate a lists of integers range(n) Generates a list of integers between 0 and N-1 range(6) [0, 1, 2, 3, 4, 5] range(m, N) Generates a list of integers between M and N-1 range(5, 10) [5, 6, 7, 8, 9] range(m,n,s) Generates a list of integers between M and N-1 with a stride of S. range(10,50,10) [10, 20, 30, 40] 41

range Function (2) Try your absolute best NOT to use the index, and operate on the elements directly. This is the Pythonic Style. Works with all collection types: for item in somelist: # Do Something with the item. Works only with lists & tuples. (NOT Recommended): for index in range(10): # Get the item from the list. # Do Something. 42

Printing Use print(somestring) to write data to stdout print("hello World!") New way to control printing is by using format() Old Style (with %) can still be used, but not recommended. Examples: Print one or more elements in order. >>> print('i am "{}" and I am "{}".'.format('smart', 'Happy')) I am "Smart" and I am "Happy". Print one or more elements out of order. >>> print('i am "{1}" and I am "{0}".'.format('Smart', 'Happy')) I am "Happy" and I am "Smart". 43

Printing (2) Examples: Printing with keywords. >>> print('today is "{day}" and it is "{weather}"!'.format(weather='sunny', day='monday')) Today is "Monday" and it is "Sunny". Print one or more elements out of order. >>> print('i am "{1}" and I am "{0}".'.format('Smart', 'Happy')) I am "Happy" and I am "Smart". Print an integer with leading 0s. >>> print("{:05d}".format(23)) '00023' Check string formatting specs for more details: https://docs.python.org/3/library/string.html#formatstrings 44

Python Modules Python has a few built-in functions Many more are found in modules A module is like a header file, it provides access to new functions Common modules: sys, string, os, and math When you want to use a function from a module, you must first import that module import sys import os, math from enum import Enum from pprint import pprint as pp 45

Python Modules (2) A common problem is not importing a module when it is used Python will raise an error if you forget to import something Example: (Solution: add import sys) Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'sys' is not defined 46