Lab 3: for and while Loops, Indexing. Ling 1330/2330: Computational Linguistics Na-Rae Han

Size: px
Start display at page:

Download "Lab 3: for and while Loops, Indexing. Ling 1330/2330: Computational Linguistics Na-Rae Han"

Transcription

1 Lab 3: for and while Loops, Indexing Ling 1330/2330: Computational Linguistics Na-Rae Han

2 Objectives Split vs. join Loops for loop while loop Indexing List and string indexing & slicing Tips How to program efficiently, aka "Code in shell" Ctrl + c for terminating a process Indenting and de-indenting a block 9/4/2018 2

3 Speed-coding fox_in_sox.py Video of me completing the script, in 5x speed! Watch closely! This may well be the most important video yet It will change your life. 9/4/2018 3

4 How to program efficiently The rookie way: You are doing all your coding in the script window, blindly. You only use the IDLE shell to verify the output of your script. 9/4/2018 4

5 How to program efficiently The seasoned Python programmer way: After a script is run, all the variables and the objects in it are still available in IDLE shell for you to tinker with. Experimenting in SHELL is much quicker instant feedback! You should go back and forth between SCRIPT and SHELL windows, successively building up your script. 9/4/2018 5

6 .join() operation How do you turn a list into a string?.join() kids = ['Bart', 'Lisa', 'Nelson', 'Milhouse'] '-'.join(kids) 'Bart-Lisa-Nelson-Milhouse' ' and '.join(kids) 'Bart and Lisa and Nelson and Milhouse' creatures = ['man', 'bear', 'pig'] ''.join(creatures) 'manbearpig' Joins on an empty string ('') 9/4/2018 6

7 .join() syntax How do you turn a list into a string?.join() kids = ['Bart', 'Lisa', 'Nelson', 'Milhouse'] '-'.join(kids) 'Bart-Lisa-Nelson-Milhouse' Note the syntax!.join() method is called on the "joiner" string and not the list "joiner" string List to be joined 9/4/2018 7

8 Using.split() and.join() Split a phrase/sentence (string) into words (list), and then join them back with a space mary = 'Mary had a little lamb' mwords = mary.split() mwords ['Mary', 'had', 'a', 'little', 'lamb'] ' '.join(mwords) 'Mary had a little lamb' List-ify a word (string) into characters (list), and then join them back with an empty string '' v = 'victory' list(v) ['v', 'i', 'c', 't', 'o', 'r', 'y'] ''.join(list(v)) 'victory' Splitting on empty string '' v.split('') does NOT work! 9/4/2018 8

9 Try it out 1 minute Split a phrase/sentence (string) into words (list), and then join them back with a space mary = 'Mary had a little lamb' mwords = mary.split() mwords ['Mary', 'had', 'a', 'little', 'lamb'] ' '.join(mwords) 'Mary had a little lamb' List-ify a word (string) into characters (list), and then join them back with an empty string '' v = 'victory' list(v) ['v', 'i', 'c', 't', 'o', 'r', 'y'] ''.join(list(v)) 'victory' 9/4/2018 9

10 for loop for x in SEQ : iterates through a sequence (list, str, tuple) for doing something to each element simpsons = ['Homer', 'Marge', 'Bart', 'Lisa', 'Maggie'] for s in simpsons : print(s, 'is a Simpson.') Press ENTER at the end of each line Homer is a Simpson. Marge is a Simpson. Bart is a Simpson. Lisa is a Simpson. Maggie is a Simpson. Iterates through every element s of the simpsons list and prints the value of s followed by 'is a Simpson.'. 9/4/

11 for loop over a string for l in 'victory' : print('give me a', l) Give me a v Give me a i Give me a c Give me a t Give me a o Give me a r Give me a y In a loop environment, string is interpreted as a sequence of characters for l in list('victory') : produces the exact same result. 9/4/

12 for loop over a list for n in [75, 80, 95, 55, 80]: print(n) Looping though a list of numbers How to calculate a total? 9/4/

13 Updating value while looping total = 0 for n in [75, 80, 95, 55, 80]: total += n print(n, 'Total is now', total) 75 Total is now Total is now Total is now Total is now Total is now 385 total 385 New variable created with initial value of 0 Add each n to total while looping The final value of total *You can also use sum() 9/4/

14 for loop over words chom = 'Colorless green ideas sleep furiously' for w in chom.split() : print('"'+w+'"', 'is', len(w), 'characters long.') "Colorless" is 9 characters long. "green" is 5 characters long. "ideas" is 5 characters long. "sleep" is 5 characters long. "furiously" is 9 characters long. 9/4/

15 for loop over words chom = 'Colorless green ideas sleep furiously' for w in chom.split() : print('"'+w+'"', 'is', len(w), 'characters long.') "Colorless" is 9 characters long. "green" is 5 characters long. "ideas" is 5 characters long. "sleep" is 5 characters long. "furiously" is 9 characters long. chom string must be first turned into a list of words through.split() chom.split() ['Colorless', 'green', 'ideas', 'sleep', 'furiously'] How to calculate the average word length? 9/4/

16 Average word length chom = 'Colorless green ideas sleep furiously' total = 0 for w in chom.split() : print('"'+w+'"', 'is', len(w), 'characters long.') total += len(w) "Colorless" is 9 characters long. "green" is 5 characters long. "ideas" is 5 characters long. "sleep" is 5 characters long. "furiously" is 9 characters long. total 33 total / len(chom.split()) 6.6 9/4/

17 for loop to build a new string 2 minutes wd = 'penguin' new = '' for x in wd : new = new + x + x print(new) ppeenngguuiinn wd = 'penguin' new = '' for x in wd : new = x + new + x print(new) niugneppenguin wd = 'penguin' new = '' for x in wd : new = x + new print(new) niugnep 9/4/

18 for loop to build a new string 2 minutes wd = 'penguin' new = '' for x in wd : new = new + x + x print(new) ppeenngguuiinn wd = 'penguin' new = '' for x in wd : new = x + new + x print(new) niugneppenguin wd = 'penguin' new = '' for x in wd : new = x + new print(new) niugnep Works as a string-reversing routine! 9/4/

19 while loop Before Loop test False True Loop body We need a looping mechanism that keeps going until a certain condition holds: "Keep counting until 10" "Keep adding 5 as long as the sum is less than 100" "Keep trying until you have the correct answer" After 9/4/

20 while loop: count from 1 to 10 number = 1 number = 1 initial condition number <= 10 False True print(number) number += 1 while number <= 10 : print(number) number += 1 tests condition print('done! ) print('done!') changes condition 9/4/

21 Terminating a process Aborting a process: Ctrl+c 1 minute Try this in IDLE shell: Bad things can happen when you forget to include a condition-changing operation in the while loop. Ctrl+c when things go haywire. 9/4/

22 Guess the secret animal secret = 'panda' g = input("what's the secret animal? ") if g == secret : print('correct!', secret, 'is the secret animal.') else : print('wrong guess. Try again.') secret.py ================================ RESTART What's the secret animal? fox Wrong guess. Try again. ================================ RESTART What's the secret animal? panda CORRECT! panda is the secret animal. Let's make it persistent: keep prompting (loop back!) until correct. 9/4/

23 Guess until correct! ================================ RESTART What's the secret animal? fox Wrong guess. Try again. What's the secret animal? dog Wrong guess. Try again. What's the secret animal? cat Wrong guess. Try again. What's the secret animal? panda CORRECT! panda is the secret animal. 9/4/

24 Method 1: which part in loop? secret = 'panda' g = input("what's the secret animal? ") if g == secret : print('correct!', secret, 'is the secret animal.') else : print('wrong guess. Try again.') 1. Figure out which part should be repeated. 2. Put the part in the while loop block. 9/4/

25 Method 1: which part in loop? secret = 'panda' g = input("what's the secret animal? ") if g == secret : print('correct!', secret, 'is the secret animal.') else : print('wrong guess. Try again.') 1. Figure out which part should be repeated. 2. Put the part in the while loop block. 9/4/

26 Method 1: while...? secret = 'panda' while g!=? secret : g = input("what's the secret animal? ") if g == secret : print('correct!', secret, 'is the secret animal.') else : print('wrong guess. Try again.') 1. Figure out which part should be repeated. 2. Put the part in the while loop block. 3. What's the condition for looping back? 9/4/

27 Method 1: set initial value for g secret = 'panda' g = '' while g!= secret : g = input("what's the secret animal? ") if g == secret : print('correct!', secret, 'is the secret animal.') else : print('wrong guess. Try again.') 1. Figure out which part should be repeated. 2. Put the part in the while loop block. 3. What's the condition for looping back? 4. Before looping begins, the initial value of g must be set 9/4/

28 Method 2: using Boolean variable secret = 'panda' g correct = '' = False while g not!= correct secret : g = input("what's the secret animal? ") A new True/False variable which functions as the loop condition if g == secret : print('correct!', secret, 'is the secret animal.') else : print('wrong guess. Try again.') 9/4/

29 Method 2: using Boolean variable secret = 'panda' correct = False while not correct : g = input("what's the secret animal? ") if g == secret : print('correct!', secret, 'is the secret animal.') else : print('wrong guess. Try again.') But there's something wrong here. What is it? 9/4/

30 Method 2: using Boolean variable secret = 'panda' correct = False while not correct : g = input("what's the secret animal? ") if g == secret : print('correct!', secret, 'is the secret animal.') correct = True else : print('wrong guess. Try again.') Variable value must be explicitly set to True in loop body. Otherwise the loop will never terminate! 9/4/

31 Method 2: try it out 2 minutes secret = 'panda' correct = False while not correct : g = input("what's the secret animal? ") if g == secret : print('correct!', secret, 'is the secret animal.') correct = True else : print('wrong guess. Try again.') secret2.py Copy/download the original script here and edit: 9/4/

32 Indenting and de-indenting a block Select your lines, and then use the commands for changing indentation levels: Indent Region: Ctrl + ] Dedent Region: Ctrl + [ Beware of TAB vs. SPACE mismatch! (If you are copy-pasting) 9/4/

33 Summary: method 1 secret = 'panda' g = '' while g!= secret : g = input("what's the secret animal? ") if g == secret : print('correct!', secret, 'is the secret animal.') else : print('wrong guess. Try again.') secret1.py initial loop condition loop condition test loop condition-changing operation 9/4/

34 Summary: method 2 secret = 'panda' correct = False while not correct : g = input("what's the secret animal? ") if g == secret : print('correct!', secret, 'is the secret animal.') correct = True else : print('wrong guess. Try again.') initial loop condition loop condition test loop condition-changing operation secret2.py 9/4/

35 Indexing Individual items of a string, list, or tuple can be accessed using square bracket "array" notation: [index] Index starts from 0! 'e' 2 'Marge' st = 'Hello, world!' st[1] li = [1, 2, 'ab', 3.14] li[1] tu = ('Homer', 'Marge', 'Bart', 'Lisa') tu[1] 9/4/

36 Positive vs. negative indices st = 'Hello!' li = ['Mary', 'had', 'a', 'little', 'lamb'] Positive index: count from the left, starting with 0 st[1] 'e' li[1] 'had' Negative index: count from right, starting with -1 st[-1] '!' li[-1] 'lamb' H e l l o! /4/

37 Slicing returns a copy of a subset Slicing syntax: s[start:end] Returns the elements beginning at start and extending up to but not including end Copying starts at the first index, and stops copying before the second index! 'ell' st = 'Hello!' st[1:4] li[2:4] ['ab', 3.14] li = [1, 2, 'ab', 3.14, 'c'] You can also use negative indices when slicing: st[1:-1] 'ello' li[1:-2] [2, 'ab'] 9/4/

38 Slicing st = 'Hello!' li = [1, 2, 'ab', 3.14, 'c'] Omit the first index [:5] to make a copy starting from the beginning: st[:4] 'Hell' li[:3] [1, 2, 'ab'] Omit the second index [2:] to make a copy till the end: st[1:] 'ello!' li[-3:] ['ab', 3.14, 'c'] 9/4/

39 String indexing/slicing examples 'a' 'e' 'e' 'an' 'ora' w = 'orange' w[2] w[5] w[6] Traceback (most recent call last): File "<pyshell#8>", line 1, in <module> w[6] IndexError: string index out of range w[-1] w[2:4] w[0:3] w[2:] 'ange' w[-2:] 'ge' o r a n g e w[:4] 'oran' w[:-1] 'orang' w[2:100] 'ange' w[:2] + w[2:] 'orange' w[:3] + w[3:] 'orange' w[:] 'orange' w[4:4] '' 39

40 List indexing/slicing examples 30 li = [10, 20, 30, 40, 50] li[2] li[5] Traceback (most recent call last): File "<pyshell#17>", line 1, in <module> li[5] IndexError: list index out of range li[-3] 30 li[2:4] [30, 40] li[:4] [10, 20, 30, 40] li[3:] [40, 50] li[2:3] [30] li[2:2] [] li[:3] + li[3:] [10, 20, 30, 40, 50] li[:] [10, 20, 30, 40, 50] Not 30! 9/4/

41 What makes Apple product names? Apple products: iphone ipad imessage itunes iwatch NOT: eprime McAfee ihop IMAX iamyourfather First character is 'i' Second character is uppercase The rest are lowercase 9/4/

42 Practice: Apple product? 2 minutes Write a script that: prompts for a string input prints YES/NO for being an Apple product name name = input('give me an Apple name: ') if name[0] == 'i' and name[1].isupper() and name[2:].islower() : print('yes!') else : print('no.') apple.py ============ RESTART: C:/Users/ /apple.py ==== Give me an Apple name: iphone NO. ============ RESTART: C:/Users/ /apple.py ==== Give me an Apple name: imessage YES! Use these functions: 'abc'.islower() True 'AB'.isupper() True 9/4/

43 Practice: Apple product? 2 minutes Write a script that: prompts for a string input prints YES/NO for being an Apple product name name = input('give me an Apple name: ') if name[0] == 'i' and name[1].isupper() and name[2:].islower() : print('yes!') else : print('no.') apple.py ============ RESTART: C:/Users/ /apple.py ==== Give me an Apple name: iphone NO. ============ RESTART: C:/Users/ /apple.py ==== Give me an Apple name: imessage YES! Use these functions: 'abc'.islower() True 'AB'.isupper() True 9/4/

44 Utilizing screen shots Screen shots are handy. Good for note taking and asking questions. Win/OS-X native solutions: Third-party applications: Greenshot (Windows only) Jing (Windows & Mac) They offer added convenience: annotate screenshots, video screencasts (Jing) 9/4/

45 Wrap-up Next class: Lab: more on Python Lecture: Character encoding (Lang & Computer ch.1) Exercise 3 Palindrome script in 3 stages: naive, smart, insistent We will send you ANSWER KEY for first 2. Follow instructions: START EARLY!! Plenty of office hours tomorrow. 9/4/

Lesson 4: Type Conversion, Mutability, Sequence Indexing. Fundamentals of Text Processing for Linguists Na-Rae Han

Lesson 4: Type Conversion, Mutability, Sequence Indexing. Fundamentals of Text Processing for Linguists Na-Rae Han Lesson 4: Type Conversion, Mutability, Sequence Indexing Fundamentals of Text Processing for Linguists Na-Rae Han Objectives Python data types Mutable vs. immutable object types How variable assignment

More information

Lab 6: Data Types, Mutability, Sorting. Ling 1330/2330: Computational Linguistics Na-Rae Han

Lab 6: Data Types, Mutability, Sorting. Ling 1330/2330: Computational Linguistics Na-Rae Han Lab 6: Data Types, Mutability, Sorting Ling 1330/2330: Computational Linguistics Na-Rae Han Objectives Data types and conversion Tuple Mutability Sorting: additional parameters Text processing overview

More information

Lab 8: File I/O, Mutability vs. Assignment. Ling 1330/2330: Intro to Computational Linguistics Na-Rae Han

Lab 8: File I/O, Mutability vs. Assignment. Ling 1330/2330: Intro to Computational Linguistics Na-Rae Han Lab 8: File I/O, Mutability vs. Assignment Ling 1330/2330: Intro to Computational Linguistics Na-Rae Han Objectives File I/O Writing to a file File I/O pitfalls File reference and absolute path Mutability

More information

Lab 2: input(), if else, String Operations, Variable Assignment. Ling 1330/2330: Computational Linguistics Na-Rae Han

Lab 2: input(), if else, String Operations, Variable Assignment. Ling 1330/2330: Computational Linguistics Na-Rae Han Lab 2: input(), if else, String Operations, Variable Assignment Ling 1330/2330: Computational Linguistics Na-Rae Han Objectives Learn Python basics Taking input from keyboard with input() Commenting Comparison

More information

Lab 1: Course Intro, Getting Started with Python IDLE. Ling 1330/2330 Computational Linguistics Na-Rae Han

Lab 1: Course Intro, Getting Started with Python IDLE. Ling 1330/2330 Computational Linguistics Na-Rae Han Lab 1: Course Intro, Getting Started with Python IDLE Ling 1330/2330 Computational Linguistics Na-Rae Han Objectives Course Introduction http://www.pitt.edu/~naraehan/ling1330/index.html Student survey

More information

Programming Fundamentals and Python

Programming Fundamentals and Python Chapter 2 Programming Fundamentals and Python This chapter provides a non-technical overview of Python and will cover the basic programming knowledge needed for the rest of the chapters in Part 1. It contains

More information

Lab 18: Regular Expressions in Python. Ling 1330/2330: Intro to Computational Linguistics Na-Rae Han

Lab 18: Regular Expressions in Python. Ling 1330/2330: Intro to Computational Linguistics Na-Rae Han Lab 18: Regular Expressions in Python Ling 1330/2330: Intro to Computational Linguistics Na-Rae Han Learning to use regex in Python Na-Rae's tutorials: http://www.pitt.edu/~naraehan/python3/re.html http://www.pitt.edu/~naraehan/python3/more_list_comp.html

More information

Lab 20: Regular Expressions in Python. Ling 1330/2330: Computational Linguistics Na-Rae Han

Lab 20: Regular Expressions in Python. Ling 1330/2330: Computational Linguistics Na-Rae Han Lab 20: Regular Expressions in Python Ling 1330/2330: Computational Linguistics Na-Rae Han Exercise 10: regexing Jobs [x X] [xx] (x X) Within [... ], all characters are already considered forming a set,

More information

Getting Started. Excerpted from Hello World! Computer Programming for Kids and Other Beginners

Getting Started. Excerpted from Hello World! Computer Programming for Kids and Other Beginners Getting Started Excerpted from Hello World! Computer Programming for Kids and Other Beginners EARLY ACCESS EDITION Warren D. Sande and Carter Sande MEAP Release: May 2008 Softbound print: November 2008

More information

The second statement selects character number 1 from and assigns it to.

The second statement selects character number 1 from and assigns it to. Chapter 8 Strings 8.1 A string is a sequence A string is a sequence of characters. You can access the characters one at a time with the bracket operator: The second statement selects character number 1

More information

Lab 7: Reading Files, Importing, Bigram Function. Ling 1330/2330: Computational Linguistics Na-Rae Han

Lab 7: Reading Files, Importing, Bigram Function. Ling 1330/2330: Computational Linguistics Na-Rae Han Lab 7: Reading Files, Importing, Bigram Function Ling 1330/2330: Computational Linguistics Na-Rae Han Objectives Importing Reading text files range() Bigram function More sorting with sorted() sorted()

More information

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

Python I. Some material adapted from Upenn cmpe391 slides and other sources Python I Some material adapted from Upenn cmpe391 slides and other sources Overview Names & Assignment Data types Sequences types: Lists, Tuples, and Strings Mutability Understanding Reference Semantics

More information

Some material adapted from Upenn cmpe391 slides and other sources

Some material adapted from Upenn cmpe391 slides and other sources Some material adapted from Upenn cmpe391 slides and other sources History Installing & Running Python Names & Assignment Sequences types: Lists, Tuples, and Strings Mutability Understanding Reference Semantics

More information

Hello World! Computer Programming for Kids and Other Beginners. Chapter 1. by Warren Sande and Carter Sande. Copyright 2009 Manning Publications

Hello World! Computer Programming for Kids and Other Beginners. Chapter 1. by Warren Sande and Carter Sande. Copyright 2009 Manning Publications Hello World! Computer Programming for Kids and Other Beginners by Warren Sande and Carter Sande Chapter 1 Copyright 2009 Manning Publications brief contents Preface xiii Acknowledgments xix About this

More information

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

History Installing & Running Python Names & Assignment Sequences types: Lists, Tuples, and Strings Mutability History Installing & Running Python Names & Assignment Sequences types: Lists, Tuples, and Strings Mutability Some material adapted from Upenn cmpe391 slides and other sources Invented in the Netherlands,

More information

COMP 204: Sets, Commenting & Exceptions

COMP 204: Sets, Commenting & Exceptions COMP 204: Sets, Commenting & Exceptions Yue Li based on material from Mathieu Blanchette, Carlos Oliver Gonzalez and Christopher Cameron 1/29 Outline Quiz 14 review Set Commenting code Bugs 2/29 Quiz 15

More information

Python Programming Exercises 3

Python Programming Exercises 3 Python Programming Exercises 3 Notes: These exercises assume that you are comfortable with the contents of the two previous sets of exercises including variables, types, arithmetic expressions, logical

More information

Compound Data Types 1

Compound Data Types 1 Compound Data Types 1 Chapters 8, 10 Prof. Mauro Gaspari: mauro.gaspari@unibo.it Compound Data Types Strings are compound data types: they are sequences of characters. Int and float are scalar data types:

More information

Ch.2: Loops and lists

Ch.2: Loops and lists Ch.2: Loops and lists Joakim Sundnes 1,2 Hans Petter Langtangen 1,2 Simula Research Laboratory 1 University of Oslo, Dept. of Informatics 2 Aug 29, 2018 Plan for 28 August Short quiz on topics from last

More information

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

Sequence types. str and bytes are sequence types Sequence types have several operations defined for them. Sequence Types. Python Python Sequence Types Sequence types str and bytes are sequence types Sequence types have several operations defined for them Indexing Python Sequence Types Each element in a sequence can be extracted

More information

Programming for Engineers in Python. Autumn

Programming for Engineers in Python. Autumn Programming for Engineers in Python Autumn 2011-12 Plan Administration: Course site Homework submission guidelines Working environment Python: Variables Editor vs. shell Homework 0 Python Cont. Conditional

More information

Accelerating Information Technology Innovation

Accelerating Information Technology Innovation 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

More information

Programming for Engineers in Python. Recitation 1

Programming for Engineers in Python. Recitation 1 Programming for Engineers in Python Recitation 1 Plan Administration: Course site Homework submission guidelines Working environment Python: Variables Editor vs. shell Homework 0 Python Cont. Conditional

More information

18.1. CS 102 Unit 18. Python. Mark Redekopp

18.1. CS 102 Unit 18. Python. Mark Redekopp 18.1 CS 102 Unit 18 Python Mark Redekopp 18.2 Credits Many of the examples below are taken from the online Python tutorial at: http://docs.python.org/tutorial/introduction.html 18.3 Python in Context Two

More information

Lists, loops and decisions

Lists, loops and decisions Caltech/LEAD Summer 2012 Computer Science Lecture 4: July 11, 2012 Lists, loops and decisions Lists Today Looping with the for statement Making decisions with the if statement Lists A list is a sequence

More information

Introduction to Python

Introduction to Python Introduction to Python Reading assignment: Perkovic text, Ch. 1 and 2.1-2.5 Python Python is an interactive language. Java or C++: compile, run Also, a main function or method Python: type expressions

More information

CMSC201 Computer Science I for Majors

CMSC201 Computer Science I for Majors CMSC201 Computer Science I for Majors Lecture 12 Tuples All materials copyright UMBC and Dr. Katherine Gibson unless otherwise noted Modularity Meaning Benefits Program design Last Class We Covered Top

More information

Introduction to Python

Introduction to Python Introduction to Python Why is Python? Object-oriented Free (open source) Portable Powerful Mixable Easy to use Easy to learn Running Python Immediate mode Script mode Integrated Development Environment

More information

CPD for GCSE Computing: Practical Sheet 6 February 14

CPD for GCSE Computing: Practical Sheet 6 February 14 Aims Programming Sheet 6 Arrays in Python Section Aim 1 Arrays A variable with many values Understand the idea of an array as a way to combine many values that are assigned to as single variable. 2 While

More information

In addition to numbers and strings, Python also lets us represent lists of things (just like in AppInventor).

In addition to numbers and strings, Python also lets us represent lists of things (just like in AppInventor). Python Part 2 h Lists In addition to numbers and strings, Python also lets us represent lists of things (just like in AppInventor). Syntax of lists: the listed is delimited by square brackets: [ ] list

More information

COMP1730/COMP6730 Programming for Scientists. Strings

COMP1730/COMP6730 Programming for Scientists. Strings COMP1730/COMP6730 Programming for Scientists Strings Lecture outline * Sequence Data Types * Character encoding & strings * Indexing & slicing * Iteration over sequences Sequences * A sequence contains

More information

DEBUGGING TIPS. 1 Introduction COMPUTER SCIENCE 61A

DEBUGGING TIPS. 1 Introduction COMPUTER SCIENCE 61A DEBUGGING TIPS COMPUTER SCIENCE 61A 1 Introduction Every time a function is called, Python creates what is called a stack frame for that specific function to hold local variables and other information.

More information

Not-So-Mini-Lecture 6. Modules & Scripts

Not-So-Mini-Lecture 6. Modules & Scripts Not-So-Mini-Lecture 6 Modules & Scripts Interactive Shell vs. Modules Launch in command line Type each line separately Python executes as you type Write in a code editor We use Atom Editor But anything

More information

Accelerating Information Technology Innovation

Accelerating Information Technology Innovation Accelerating Information Technology Innovation http://aiti.mit.edu/program/philippines-summer-2012/ Philippines Summer 2012 Lecture 1 Introduction to Python June 19, 2012 Agenda About the Course What is

More information

Errors. And How to Handle Them

Errors. And How to Handle Them Errors And How to Handle Them 1 GIGO There is a saying in computer science: Garbage in, garbage out. Is this true, or is it just an excuse for bad programming? Answer: Both. Here s what you want: Can you

More information

Lists How lists are like strings

Lists How lists are like strings Lists How lists are like strings A Python list is a new type. Lists allow many of the same operations as strings. (See the table in Section 4.6 of the Python Standard Library Reference for operations supported

More information

LING 510, Lab 3 September 23, 2013

LING 510, Lab 3 September 23, 2013 LING 510, Lab 3 September 23, 2013 Agenda: Go over Homework 1 Go over JYW, if there are questions Go over function application (what we ended with on Thursday) 1. Frequently missed questions on Homework

More information

Data Structures. Lists, Tuples, Sets, Dictionaries

Data Structures. Lists, Tuples, Sets, Dictionaries Data Structures Lists, Tuples, Sets, Dictionaries Collections Programs work with simple values: integers, floats, booleans, strings Often, however, we need to work with collections of values (customers,

More information

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

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming Intro to Programming Unit 7 Intro to Programming 1 What is Programming? 1. Programming Languages 2. Markup vs. Programming 1. Introduction 2. Print Statement 3. Strings 4. Types and Values 5. Math Externals

More information

Unit 7. 'while' Loops

Unit 7. 'while' Loops 1 Unit 7 'while' Loops 2 Control Structures We need ways of making decisions in our program To repeat code until we want it to stop To only execute certain code if a condition is true To execute one segment

More information

Scripting Languages. Python basics

Scripting Languages. Python basics Scripting Languages Python basics Interpreter Session: python Direct conversation with python (>>>) Python 3.5.2 (default, Nov 23 2017, 16:37:01) [GCC 5.4.0 20160609] on linux Type "help", "copyright",

More information

MEIN 50010: Python Flow Control

MEIN 50010: Python Flow Control : Python Fabian Sievers Higgins Lab, Conway Institute University College Dublin Wednesday, 2017-10-11 Program Overview Program Code Block Statements Expressions Expressions & Statements An expression has

More information

Professor: Sana Odeh Lecture 3 Python 3.1 Variables, Primitive Data Types & arithmetic operators

Professor: Sana Odeh Lecture 3 Python 3.1 Variables, Primitive Data Types & arithmetic operators 1 Professor: Sana Odeh odeh@courant.nyu.edu Lecture 3 Python 3.1 Variables, Primitive Data Types & arithmetic operators Review What s wrong with this line of code? print( He said Hello ) What s wrong with

More information

An introduction to Python

An introduction to Python supported by Abstract This guide provides a simple introduction to Python with examples and exercises to assist learning. Python is a high level object-oriented programming language. Data and functions

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 Intro GIS Week 1. Jake K. Carr

Python Intro GIS Week 1. Jake K. Carr GIS 5222 Week 1 Why Python It s simple and easy to learn It s free - open source! It s cross platform IT S expandable!! Why Python: Example Consider having to convert 1,000 shapefiles into feature classes

More information

MICROPROCESSOR SYSTEMS INTRODUCTION TO PYTHON

MICROPROCESSOR SYSTEMS INTRODUCTION TO PYTHON MICROPROCESSOR SYSTEMS INTRODUCTION TO PYTHON Table of contents 2 1. Learning Outcomes 2. Introduction 3. The first program: hello world! 4. The second program: hello (your name)! 5. More data types 6.

More information

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

Introduction to: Computers & Programming: Review prior to 1 st Midterm Introduction to: Computers & Programming: Review prior to 1 st Midterm Adam Meyers New York University Summary Some Procedural Matters Summary of what you need to Know For the Test and To Go Further in

More information

Collections. Lists, Tuples, Sets, Dictionaries

Collections. Lists, Tuples, Sets, Dictionaries Collections Lists, Tuples, Sets, Dictionaries Homework notes Homework 1 grades on canvas People mostly lost points for not reading the document carefully Didn t play again Didn t use Y/N for playing again

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

Types, lists & functions

Types, lists & functions Week 2 Types, lists & functions Data types If you want to write a program that allows the user to input something, you can use the command input: name = input (" What is your name? ") print (" Hello "+

More information

Working with Sequences: Section 8.1 and 8.2. Bonita Sharif

Working with Sequences: Section 8.1 and 8.2. Bonita Sharif Chapter 8 Working with Sequences: Strings and Lists Section 8.1 and 8.2 Bonita Sharif 1 Sequences A sequence is an object that consists of multiple data items These items are stored consecutively Examples

More information

Shell Programming (Part 2)

Shell Programming (Part 2) i i Systems and Internet Infrastructure Security Institute for Networking and Security Research Department of Computer Science and Engineering Pennsylvania State University, University Park, PA Shell Programming

More information

St. Benedict s High School. Computing Science. Software Design & Development. (Part 1 Computer Programming) National 5

St. Benedict s High School. Computing Science. Software Design & Development. (Part 1 Computer Programming) National 5 Computing Science Software Design & Development (Part 1 Computer Programming) National 5 VARIABLES & DATA TYPES Variables provide temporary storage for information that will be needed while a program is

More information

Introduction to Python

Introduction to Python Introduction to Python Efstratios RAPPOS efstratios.rappos@heig-vd.ch Slide 1 2016 HEIG-VD SNU Summer School Background Easy and popular programming language Interpreted: must have python installed to

More information

To add something to the end of a list, we can use the append function:

To add something to the end of a list, we can use the append function: 4.2 Lists Creating an Empty List A list is a sequence of items. In python, a list is an ordered sequence of items, not necessarily of the same type, but typically, most lists contain items all of the same

More information

3 The Building Blocks: Data Types, Literals, and Variables

3 The Building Blocks: Data Types, Literals, and Variables chapter 3 The Building Blocks: Data Types, Literals, and Variables 3.1 Data Types A program can do many things, including calculations, sorting names, preparing phone lists, displaying images, validating

More information

The current topic: Python. Announcements. Python. Python

The current topic: Python. Announcements. Python. Python The current topic: Python Announcements! Introduction! reasons for studying languages! language classifications! simple syntax specification Object-oriented programming: Python Types and values Syntax

More information

Programming. We will be introducing various new elements of Python and using them to solve increasingly interesting and complex problems.

Programming. We will be introducing various new elements of Python and using them to solve increasingly interesting and complex problems. Plan for the rest of the semester: Programming We will be introducing various new elements of Python and using them to solve increasingly interesting and complex problems. We saw earlier that computers

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

ISE 101 Introduction to Information Systems. Lecture 3 Objectives: While loops Strings

ISE 101 Introduction to Information Systems. Lecture 3 Objectives: While loops Strings ISE 101 Introduction to Information Systems Lecture 3 Objectives: While loops Strings While Loops Write a Python script that computes the sum of squares from 1 to 5. sum = 0; sum = sum + 1**2; sum = sum

More information

Lists in Python CS 8: Introduction to Computer Science, Winter 2018 Lecture #10

Lists in Python CS 8: Introduction to Computer Science, Winter 2018 Lecture #10 Lists in Python CS 8: Introduction to Computer Science, Winter 2018 Lecture #10 Ziad Matni Dept. of Computer Science, UCSB Administrative Homework #5 is due today Homework #6 is out and DUE on MONDAY (3/5)

More information

Exercise: The basics - variables and types

Exercise: The basics - variables and types Exercise: The basics - variables and types Aim: Introduce python variables and types. Issues covered: Using the python interactive shell In the python interactive shell you don t need print Creating variables

More information

COMP 204: Sets, Commenting & Exceptions

COMP 204: Sets, Commenting & Exceptions COMP 204: Sets, Commenting & Exceptions Material from Carlos G. Oliver, Christopher J.F. Cameron October 12, 2018 1/31 Reminder CSUS is holding a midterm review session on Monday, October 15th, from 6-9pm.

More information

CS1 Lecture 3 Jan. 22, 2018

CS1 Lecture 3 Jan. 22, 2018 CS1 Lecture 3 Jan. 22, 2018 Office hours for me and for TAs have been posted, locations will change check class website regularly First homework available, due Mon., 9:00am. Discussion sections tomorrow

More information

SAMS Programming A/B. Lecture #1 Introductions July 3, Mark Stehlik

SAMS Programming A/B. Lecture #1 Introductions July 3, Mark Stehlik SAMS Programming A/B Lecture #1 Introductions July 3, 2017 Mark Stehlik Outline for Today Overview of Course A Python intro to be continued in lab on Wednesday (group A) and Thursday (group B) 7/3/2017

More information

Python for Non-programmers

Python for Non-programmers Python for Non-programmers A Gentle Introduction 2 Yann Tambouret Scientific Computing and Visualization Information Services & Technology Boston University 111 Cummington St. yannpaul@bu.edu Winter 2013

More information

How Do Robots Find Their Way?

How Do Robots Find Their Way? How Do Robots Find Their Way? Conditionals and Repetition http://en.wikipedia.org/wiki/file:cyclope_robot.jpg http://www.youtube.com/watch?v=_l9rklaskwu Learning Objectives Learn basic programming concepts

More information

Python language: Basics

Python language: Basics Python language: Basics The FOSSEE Group Department of Aerospace Engineering IIT Bombay Mumbai, India FOSSEE Team (FOSSEE IITB) Basic Python 1 / 45 Outline 1 Data types Numbers Booleans Strings 2 Operators

More information

Introduction to String Manipulation

Introduction to String Manipulation Introduction to Computer Programming Introduction to String Manipulation CSCI-UA.0002 What is a String? A String is a data type in the Python programming language A String can be described as a "sequence

More information

MUTABLE LISTS AND DICTIONARIES 4

MUTABLE LISTS AND DICTIONARIES 4 MUTABLE LISTS AND DICTIONARIES 4 COMPUTER SCIENCE 61A Sept. 24, 2012 1 Lists Lists are similar to tuples: the order of the data matters, their indices start at 0. The big difference is that lists are mutable

More information

PYTHON TRAINING COURSE CONTENT

PYTHON TRAINING COURSE CONTENT SECTION 1: INTRODUCTION What s python? Why do people use python? Some quotable quotes A python history lesson Advocacy news What s python good for? What s python not good for? The compulsory features list

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

CS 302: INTRODUCTION TO PROGRAMMING. Lectures 7&8

CS 302: INTRODUCTION TO PROGRAMMING. Lectures 7&8 CS 302: INTRODUCTION TO PROGRAMMING Lectures 7&8 Hopefully the Programming Assignment #1 released by tomorrow REVIEW The switch statement is an alternative way of writing what? How do you end a case in

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

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

CS 303E Fall 2011 Exam 2 Solutions and Criteria November 2, Good Luck!

CS 303E Fall 2011 Exam 2 Solutions and Criteria November 2, Good Luck! CS 303E Fall 2011 Exam 2 Solutions and Criteria November 2, 2011 Name: EID: Section Number: Friday discussion time (circle one): 9-10 10-11 11-12 12-1 2-3 Friday discussion TA(circle one): Wei Ashley Answer

More information

Unit 7: Algorithms and Python CS 101, Fall 2018

Unit 7: Algorithms and Python CS 101, Fall 2018 Unit 7: Algorithms and Python CS 101, Fall 2018 Learning Objectives After completing this unit, you should be able to: Identify whether a sequence of steps is an algorithm in the strict sense. Explain

More information

Python: common syntax

Python: common syntax Lab 09 Python! Python Intro Main Differences from C++: True and False are capitals Python floors (always down) with int division (matters with negatives): -3 / 2 = -2 No variable data types or variable

More information

You Need an Interpreter! Comp Spring /28/08 L10 - An Interpreter

You Need an Interpreter! Comp Spring /28/08 L10 - An Interpreter You Need an Interpreter! Closing the GAP Thus far, we ve been struggling to speak to computers in their language, maybe its time we spoke to them in ours How high can we rasie the level of discourse? We

More information

CSCI 121: Anatomy of a Python Script

CSCI 121: Anatomy of a Python Script CSCI 121: Anatomy of a Python Script Python Scripts We start by a Python script: A text file containing lines of Python code. Each line is a Python statement. The Python interpreter (the python3 command)

More information

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

x = 3 * y + 1; // x becomes 3 * y + 1 a = b = 0; // multiple assignment: a and b both get the value 0 6 Statements 43 6 Statements The statements of C# do not differ very much from those of other programming languages. In addition to assignments and method calls there are various sorts of selections and

More information

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming 2017 Table of contents 1 2 Integers and floats Integer int and float float are elementary numeric types in. integer >>> a=1 >>> a 1 >>> type (a) Integers and floats Integer int and float

More information

CE151 ASSIGNMENT

CE151 ASSIGNMENT Set by: Mike Sanderson Credit: 20% of total module mark Deadline: 11.59.59, Monday 8 December Submission of this assignment will be via the online submission system; your programs may be tested during

More information

Computer and Programming: Lab 1

Computer and Programming: Lab 1 01204111 Computer and Programming: Lab 1 Name ID Section Goals To get familiar with Wing IDE and learn common mistakes with programming in Python To practice using Python interactively through Python Shell

More information

CMSC 201 Computer Science I for Majors

CMSC 201 Computer Science I for Majors CMSC 201 Computer Science I for Majors Lecture 02 Intro to Python Syllabus Last Class We Covered Grading scheme Academic Integrity Policy (Collaboration Policy) Getting Help Office hours Programming Mindset

More information

An Introduction to Python

An Introduction to Python An Introduction to Python Day 2 Renaud Dessalles dessalles@ucla.edu Python s Data Structures - Lists * Lists can store lots of information. * The data doesn t have to all be the same type! (unlike many

More information

Algorithms and Programming I. Lecture#12 Spring 2015

Algorithms and Programming I. Lecture#12 Spring 2015 Algorithms and Programming I Lecture#12 Spring 2015 Think Python How to Think Like a Computer Scientist By :Allen Downey Installing Python Follow the instructions on installing Python and IDLE on your

More information

Loops and Conditionals. HORT Lecture 11 Instructor: Kranthi Varala

Loops and Conditionals. HORT Lecture 11 Instructor: Kranthi Varala Loops and Conditionals HORT 59000 Lecture 11 Instructor: Kranthi Varala Relational Operators These operators compare the value of two expressions and returns a Boolean value. Beware of comparing across

More information

MEIN 50010: Python Strings

MEIN 50010: Python Strings : Python Strings Fabian Sievers Higgins Lab, Conway Institute University College Dublin Wednesday, 2017-10-25 Lecture Basic string manipulation Converting between different variable types strings Command-line

More information

Girls Programming Network. Markov Chains Workbook 1

Girls Programming Network. Markov Chains Workbook 1 Girls Programming Network Markov Chains Workbook 1 This project was created by GPN Australia for GPN sites all around Australia! This workbook and related materials were created by tutors at: Sydney, Canberra

More information

Lecture 4. while and for loops if else test Tuples Functions. Let us start Python Ssh (putty) to UNIX/Linux computer puccini.che.pitt.

Lecture 4. while and for loops if else test Tuples Functions. Let us start Python Ssh (putty) to UNIX/Linux computer puccini.che.pitt. Lecture 4 while and for loops if else test Tuples Functions Let us start Python Ssh (putty) to UNIX/Linux computer puccini.che.pitt.edu Launching Python > python Quick Reminder: while Loop Example >>>

More information

Shell / Python Tutorial. CS279 Autumn 2017 Rishi Bedi

Shell / Python Tutorial. CS279 Autumn 2017 Rishi Bedi Shell / Python Tutorial CS279 Autumn 2017 Rishi Bedi Shell (== console, == terminal, == command prompt) You might also hear it called bash, which is the most widely used shell program macos Windows 10+

More information

Comp 151. Control structures.

Comp 151. Control structures. Comp 151 Control structures. admin For these slides read chapter 7 Yes out of order. Simple Decisions So far, we ve viewed programs as sequences of instructions that are followed one after the other. While

More information

Announcements For This Lecture

Announcements For This Lecture Lecture 5 Strings Announcements For This Lecture Assignment 1 Will post it on Sunday Need one more lecture But start reading it Dues Wed Sep. 19 th Revise until correct This is Yom Kippur This is as late

More information

Python is available at: https://www.python.org/ Why Python is awesome: https://www.python.org/about/success/

Python is available at: https://www.python.org/ Why Python is awesome: https://www.python.org/about/success/ The Python IDLE: Introduction This tutorial assumes you have a PYTHON 3 version of the programming language installed. (Current version at of this writing is Python 3.6) Python is available at: https://www.python.org/

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

Programming in Python

Programming in Python 3. Sequences: Strings, Tuples, Lists 15.10.2009 Comments and hello.py hello.py # Our code examples are starting to get larger. # I will display "real" programs like this, not as a # dialog with the Python

More information

Level 3 Computing Year 2 Lecturer: Phil Smith

Level 3 Computing Year 2 Lecturer: Phil Smith Level 3 Computing Year 2 Lecturer: Phil Smith Previously We learnt what a computer program does. What a procedural program does. What a procedure is. We had a first look at IDLE. Now Learning Outcomes

More information

CME 193: Introduction to Scientific Python Lecture 1: Introduction

CME 193: Introduction to Scientific Python Lecture 1: Introduction CME 193: Introduction to Scientific Python Lecture 1: Introduction Nolan Skochdopole stanford.edu/class/cme193 1: Introduction 1-1 Contents Administration Introduction Basics Variables Control statements

More information