CMPT 120 Lists and Strings. Summer 2012 Instructor: Hassan Khosravi
|
|
- Nigel Cobb
- 5 years ago
- Views:
Transcription
1 CMPT 120 Lists and Strings Summer 2012 Instructor: Hassan Khosravi
2 All of the variables that we have used have held a single item One integer, floating point value, or string often you find that you want to store a collection of values in your programs. a list of values that have been entered by the user or a collection of values that are needed to draw a graph. In Python, lists can be used to store a collection of values. Python can hold values of any type; they are written as a commaseparated list enclosed in square brackets: numlist = [23, 10, -100, 2] words = [ zero, one, two ] junk = [0, 1, two, [1,1,1], 4.0] 1.2
3 To get a particular value out of a list, it can be subscripted testlist = [0, 10, 20, 30, 40, 50] print testlist[2] 20 print testlist[0] 0 print testlist[10] IndexError: list index out of range Like strings, the first element in a list is element 0 1.3
4 You can determine the length of a list with the len function: print len(testlist) 6 for i in range(len(testlist)): print testlist[i],
5 Lists can be joined (concatenated) with the + operator: testlist + [60, 70, 80] [0, 10, 20, 30, 40, 50, 60, 70, 80] [ one, two, three ] + [1, 2, 3] [ one, two, three, 1, 2, 3] It is also possible to delete an element from a list colours = [ red, yellow, blue ] del colours[1] print colours [ red, blue ] del colours[1] print colours [ red ] 1.5
6 You can also add a new element to the end of a list with the append colours = [ red, yellow, blue ] colours.append( orange ) colours.append( green ) print colours [ red, yellow, blue, orange, green ] In order to do something similar with a string, a new string must be built with the + operator: letters = abc letters = letters + d letters = letters + e print letters abcde 1.6
7 print "Enter some numbers, 0 to stop:" numbers = [] x=1 while x!=0: x = int(raw_input()) if x!=0: numbers.append(x) print "The numbers you entered are:" print numbers 1.7
8 Lists and for loops range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] range(1,17,3) [1, 4, 7, 10, 13, 16] Range(13,1,2) [] Range(13,1,-2) [13, 11, 9, 7, 5, 3] for i in range(10): # do something with I For loop in Python can iterate over any list not just those produced by the range function. 1.8
9 There, the for loop iterates over each element in the list words. words = ["up", "down", "green", "cabbage"] for word in words: print "Here s a word: " + word Here s a word: up Here s a word: down Here s a word: green Here s a word: cabbage 1.9
10 Slicing and Dicing colours = [ red, yellow, blue ] colours[1] = green # set an element with indexing Print colours[1] green print colours[2] # index to retrieve an element blue colours = [ red, yellow, green, blue ] print colours[1:3] [ yellow, green ] In general, the slice [a:b] extracts elements a to b-1 Same as range 1.10
11 Special Slice Positions Negative values count from the end of a list. -1 refers to the last item in the list -2 to the second-last, and so on colours = [ red, yellow, green, blue ] print colours[0:-1] [ red, yellow, green ] If you leave out one of the values in the slice, it will default to the start or end of the list. [:num] refers to elements 0 to num-1. [2:] gives elements from 2 to the end of the list. 1.11
12 Examples colours = [ red, yellow, green, blue, orange ] print colours[2:] [ green, blue, orange ] print colours[:3] [ red, yellow, green ] print colours[:-1] [ red, yellow, green, blue ] e [:-1] will always give you everything except the last element; [1:] will give everything but the first element. 1.12
13 Examples Fibonacci Store the first 20 values in the Fibonacci series in a list such that the index i of the list stores the ith element. Fibonacci series are the numbers in the following integer sequence: 0,1,1,2,3,5, F n = F n-1 + F n-2 F 0 = 0, F 1 =1 1.13
14 Example Fibonacci fib = [] fib.append('garbage') fib.append(0) fib.append(1) for i in range(3,20): new = fib[i-1] + fib[i-2] fib.append(new) print fib 1.14
15 Example Fibonacci Store the first 20 values in the Fibonacci series in a list such that the index i of the list stores the ith element. Fibonacci series are the numbers in the following integer sequence: 0,1,1,2,3,5, F n = F n-1 + F n-2 F 0 = 0, F 1 =1 For the odd elements of the series calculate their average For even elements of the series calcuate their sum 1.15
16 Example Fibonacci def average(list): length = len(list) j=0 sum=0 for i in range(1,length,2): j=j+1 sum = sum+list[i] print list[i] average = float(sum)/j return average def sumforfib(list): length = len(list) sum=0 for i in range(length,2): sum = sum+list[i] print list[i] return sum 1.16
17 Example Duplicate Store a list of 10 words and determine whether any word has been entered more than once. words= [] for i in range(10): words.append( raw_input("enter word please: ")) flag = False for i in range(10): for j in range(i+1,10): if words[i] == words[j]: print "duplicated" flag = True if flag == False: print "No duplicates" 1.17
18 Words containing s Store a list of 10 words and determine whether each contains the letter s or not. words= [] for i in range(10): words.append( raw_input("enter word please: ")) for w in words: flag = False for let in w: if let == 's': print w, "contains s" flag = True if flag == False: print w, "does not contain s" 1.18
19 Store a list of 10 words and determine whether each contains the letter s or not. Remove all occurrences of letter s from all words words= [] for i in range(4): words.append( raw_input("enter word please: ")) length = len(words) for i in range(length): temp = "" for let in words[i]: if let!= 's': temp = temp + let words[i]= temp print words 1.19
20 Manipulating Slices You can actually do almost anything with list slices colours = [ red, yellow, green, blue ] colours[1:3] = [ yellowish, greenish ] print colours [ red, yellowish, greenish, blue ] colours[1:3] = [ pink, purple, ecru ] print colours [ red, pink, purple, ecru, blue ] we assigned a list of three elements to a slice of length two The list expands to make room or the new elements [ yellowish, greenish] is replaced with [ pink, purple, ecru ]. 1.20
21 Manipulating Slices If the list assigned is shorter than the slice, the list would shrink colours = ['red', 'yellow', 'green', 'blue'] colours[1:3] = "red" print colours ['red', 'r', 'e', 'd', 'blue'] colours = ['red', 'yellow', 'green', 'blue'] colours[1:3] = ['red'] print colours ['red', 'red', 'blue'] 1.21
22 Deleting Slices You can also remove any slice from a list: colours = [ red, yellow, green, blue ] del colours[1:3] print colours [ red, blue ] 1.22
23 Strings Strings are a sequence of characters; lists are a sequence of any combination of types. Any type that represents a collection of values can be used as the list in a for loop. Since a string represents a sequence of characters, it can be used. for char in "abc": print "A character:", char A character: a A character: b A character: c 1.23
24 Slicing Strings Slices in strings are read only sentence = "Look, I m a string! print sentence[:5] Look print sentence[6:11] I m a print sentence[-7:] string! 1.24
25 But, you can t modify a string slice sentence = "Look, I m a string! sentence[:5] = "Wow" TypeError: object doesn t support slice assignment del sentence[6:10] TypeError: object doesn t support slice assignment 1.25
26 Mutability dots = dots + "." # statement #1 The right side of = is evaluated and put into dots. The old value of dots is lost in the assignment values = values + [n] # statement #2 Same with this method of modifying lists values.append(n) # statement #3 The output of this statement is the same as statement 2. Statement 3 requires a lot less work. The whole list in not rebuilt. Data structures that can be changed in-place like lists are called mutable. Strings and numbers are not mutable: they are immutable. Objects depends how they are written, but they have the capability to be mutable 1.26
27 References There are several cases where the contents of one variable are copied to another. # x copied into y: y = x You probably don t think of copying the contents of a variable as a difficult operation, but consider the case where x is a list with millions of elements. Python avoids making copies where possible To understand this, we need to understand references. 1.27
28 Every variable in Python is actually a reference to the place in memory where its contents are stored. Conceptually, you should think of a variable referencing its contents like an arrow pointing to the contents in memory. 1.28
29 When you use a variable in an expression, Python follows the reference to find its contents. Usually, the expression on the right side of an assignment creates a new object in memory. Total = a+b calculates a+b, stores this in memory, and sets total to reference that value. The exception to this is when the right side of an assignment is simply a variable reference (like total=a). In this case, the result is already in memory and the variable can just reference the existing contents 1.29
30 Aliases When two variables refer to the same contents, they are aliases of each other. it s generally good since it doesn t require copying the contents to another location in memory. When you assign to a variable, you are changing it so the variable now references different contents. (The old contents are thrown away since they are no longer being referenced.) 1.30
31 Mutable data structures and aliases Mutable data structures (lists and some objects), aliases complicate things. Mutable data structures can be changed without totally rebuilding them, we can change the contents without moving the reference to a new object in memory It s possible to change a variable, and the changes will affect any other variables that reference the same contents. my_list and list_copy are aliases of the same contents. When either one is changed, both are affected. I 1.31
32 Any expression (that s more complicated than a variable reference) will result in a new reference being created. If this is assigned to a variable, then there is no aliasing. 1.32
33 Really Copying If you want to make a copy of a variable that isn t a reference, it s necessary to force Python to actually copy its contents to a new place in memory. This is called cloning. Cloning is more expensive than aliasing, There are three methods for this The slice operator can be used to create a clone. You could also make a copy of a list with the list function that creates a new list (out of the old one). So, list(my_list) would give the same result as my_list[:]. the copy module contains a copy function. This function will take any Python object and clone its contents import copy new_obj = copy.copy(obj) 1.33
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 informationCS1 Lecture 11 Feb. 9, 2018
CS1 Lecture 11 Feb. 9, 2018 HW3 due Monday morning, 9:00am for #1 I don t care if you use 1, 2, or 3 loops. Most important is clear correct code for #3, make sure all legal situations are handled. Think
More informationMITOCW watch?v=rvrkt-jxvko
MITOCW watch?v=rvrkt-jxvko The following content is provided under a Creative Commons license. Your support will help MIT OpenCourseWare continue to offer high quality educational resources for free. To
More informationTopic 7: Lists, Dictionaries and Strings
Topic 7: Lists, Dictionaries and Strings The human animal differs from the lesser primates in his passion for lists of Ten Best H. Allen Smith 1 Textbook Strongly Recommended Exercises The Python Workbook:
More informationCMPT 120 Control Structures in Python. Summer 2012 Instructor: Hassan Khosravi
CMPT 120 Control Structures in Python Summer 2012 Instructor: Hassan Khosravi The If statement The most common way to make decisions in Python is by using the if statement. The if statement allows you
More informationThe Practice of Computing Using PYTHON
The Practice of Computing Using PYTHON William Punch Richard Enbody Chapter 6 Lists and Tuples 1 Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Data Structures 2 Data Structures
More informationSCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015
SCHEME 7 COMPUTER SCIENCE 61A October 29, 2015 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,
More informationLists 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 informationCompound 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 informationHomework notes. Homework 2 grades posted on canvas. Homework 3 due tomorrow. Homework 4 posted on canvas. Due Tuesday, Oct. 3
References Homework notes Homework 2 grades posted on canvas Homework 3 due tomorrow Homework 4 posted on canvas Due Tuesday, Oct. 3 Style notes Comment your code! A short line of comments per logical
More informationAlgorithmic Thinking: Computing with Lists
Algorithmic Thinking: Computing with Lists So Far in Python Data types: int, float, Boolean, string Assignments, function definitions Control structures: For loops, while loops, conditionals Last Lecture
More informationCMPT 120 Basics of Python. Summer 2012 Instructor: Hassan Khosravi
CMPT 120 Basics of Python Summer 2012 Instructor: Hassan Khosravi Python A simple programming language to implement your ideas Design philosophy emphasizes code readability Implementation of Python was
More informationPython Lists. What is not a Collection. A List is a kind of Collection. friends = [ 'Joseph', 'Glenn', 'Sally' ]
Python Lists Chapter 8 Unless otherwise noted, the content of this course material is licensed under a Creative Commons Attribution.0 License. http://creativecommons.org/licenses/by/.0/. Copyright 2010,
More information06/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 informationData 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 informationPython Review IPRE
Python Review Jay Summet 2005-12-31 IPRE Outline Compound Data Types: Strings, Tuples, Lists & Dictionaries Immutable types: Strings Tuples Accessing Elements Cloning Slices Mutable Types: Lists Dictionaries
More informationSequences and Loops. Indices: accessing characters in a string. Old friend: isvowel. Motivation: How to count the number of vowels in a word?
Motivation: How to count the number of vowels in a word? Sequences and Loops o You re given words like 'boston', 'wellesley', 'needham', 'lynn', etc. o Tasks: o count the number of vowels in a word. o
More informationAlgorithmic Thinking: Computing with Lists
Algorithmic Thinking: Computing with Lists Announcements Tonight: Lab 3 PA 3 OLI Tomorrow Lab 4 Any Confusion Print vs Return: def?????? (a, b): result = a + b print (result) def?????? (a, b): result =
More informationLists, 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 informationPython 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 informationAll programs can be represented in terms of sequence, selection and iteration.
Python Lesson 3 Lists, for loops and while loops Suffolk One, Ipswich, 4:30 to 6:00 Tuesday Jan 28 Nicky Hughes All programs can be represented in terms of sequence, selection and iteration. 1 Computational
More informationProgramming 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 informationSequences and Loops. Indices: accessing characters in a string. Old friend: isvowel. Motivation: How to count the number of vowels in a word?
Motivation: How to count the number of vowels in a word? Sequences and Loops o You re given words like 'Boston', 'Wellesley', 'abracadabra', 'bureaucracies', etc. o Tasks: o count the number of vowels
More informationPython and Bioinformatics. Pierre Parutto
Python and Bioinformatics Pierre Parutto October 9, 2016 Contents 1 Common Data Structures 2 1.1 Sequences............................... 2 1.1.1 Manipulating Sequences................... 2 1.1.2 String.............................
More informationPython Review IPRE
Python Review 2 Jay Summet 2005-12-31 IPRE Outline Compound Data Types: Strings, Tuples, Lists & Dictionaries Immutable types: Strings Tuples Accessing Elements Cloning Slices Mutable Types: Lists Dictionaries
More informationUniversity of Texas at Arlington, TX, USA
Dept. of Computer Science and Engineering University of Texas at Arlington, TX, USA Part of the science in computer science is the design and use of data structures and algorithms. As you go on in CS,
More informationPython 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 informationIntro 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 informationCS2304: Python for Java Programmers. CS2304: Sequences and Collections
CS2304: Sequences and Collections Sequences In Python A sequence type in python supports: The in membership operator. The len() function. Slicing like we saw with strings, s[1:3]. And is iterable (for
More informationSummer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define
CS 6A Scheme Summer 207 Discussion 0: July 25, 207 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,
More informationMUTABLE 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 informationCompound Data Types 2
Compound Data Types 2 Chapters 10, 11, 12 Prof. Mauro Gaspari: gaspari@cs.unibo.it Objects and Values We know that a and b both refer to a string, but we don t know whether they refer to the same string.
More informationSCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017
SCHEME 8 COMPUTER SCIENCE 61A March 2, 2017 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,
More informationSpring 2018 Discussion 7: March 21, Introduction. 2 Primitives
CS 61A Scheme Spring 2018 Discussion 7: March 21, 2018 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme
More informationIntro. Scheme Basics. scm> 5 5. scm>
Intro Let s take some time to talk about LISP. It stands for LISt Processing a way of coding using only lists! It sounds pretty radical, and it is. There are lots of cool things to know about LISP; if
More informationTypes, 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 informationFall 2017 Discussion 7: October 25, 2017 Solutions. 1 Introduction. 2 Primitives
CS 6A Scheme Fall 207 Discussion 7: October 25, 207 Solutions Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write
More informationCMPT 120 Introduction To Computing Science And Programming I. Pseudocode. Summer 2012 Instructor: Hassan Khosravi
CMPT 120 Introduction To Computing Science And Programming I Pseudocode Summer 2012 Instructor: Hassan Khosravi Guessing game 1. Tell the user to pick a secret number between 1 and 100. 2. The smallest
More informationWorking 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 informationPython for loops. Girls Programming Network School of Information Technologies University of Sydney. Mini-lecture 7
Python for loops Girls Programming Network School of Information Technologies University of Sydney Mini-lecture 7 Lists for loops More Strings Summary 2 Outline 1 Lists 2 for loops 3 More Strings 4 Summary
More informationUnit 2. Srinidhi H Asst Professor
Unit 2 Srinidhi H Asst Professor 1 Iterations 2 Python for Loop Statements for iterating_var in sequence: statements(s) 3 Python for While Statements while «expression»: «block» 4 The Collatz 3n + 1 sequence
More informationLists. There are several ways to create a new list; the simplest is to enclose the elements in square brackets ( [ and ]):
Lists A list is an ordered set of values, where each value is identified by an index. The values that make up a list are called its elements. Lists are similar to strings, which are ordered sets of characters,
More informationThere are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals:
Numeric Types There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals: 1-123 +456 2. Long integers, of unlimited
More informationPart 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 informationEpisode 3 Lists and Strings
Episode 3 Lists and Strings Lists and strings are two of the most important types in Python. For these, one variable name stands for several items, so we call them compound types. Lists Lists are much
More information1 Strings (Review) CS151: Problem Solving and Programming
1 Strings (Review) Strings are a collection of characters. quotes. this is a string "this is also a string" In python, strings can be delineated by either single or double If you use one type of quote
More informationIntroduction 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 informationDecisions, Decisions. Testing, testing C H A P T E R 7
C H A P T E R 7 In the first few chapters, we saw some of the basic building blocks of a program. We can now make a program with input, processing, and output. We can even make our input and output a little
More informationCS Summer 2013
CS 1110 - Summer 2013 intro to programming -- how to think like a robot :) we use the Python* language (www.python.org) programming environments (many choices): Eclipse (free from www.eclipse.org), or
More informationAbstract Data Types. CS 234, Fall Types, Data Types Abstraction Abstract Data Types Preconditions, Postconditions ADT Examples
Abstract Data Types CS 234, Fall 2017 Types, Data Types Abstraction Abstract Data Types Preconditions, Postconditions ADT Examples Data Types Data is stored in a computer as a sequence of binary digits:
More information18.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 informationCSC326 Python Sequences i. CSC326 Python Sequences
i CSC326 Python Sequences ii REVISION HISTORY NUMBER DATE DESCRIPTION NAME 1.0 2011-09 JZ iii Contents 1 Agenda 1 2 while Statement 1 3 Sequence Overview 2 4 String 2 5 Lists 4 6 Dictionary 5 7 Tuples
More informationIntroduction to programming using Python
Introduction to programming using Python Matthieu Choplin matthieu.choplin@city.ac.uk http://moodle.city.ac.uk/ Session 4 1 Objectives To come back on the notion of object and type. To introduce to the
More informationCS1 Lecture 12 Feb. 11, 2019
CS1 Lecture 12 Feb. 11, 2019 HW4 available tomorrow, due next Wed. Discussion sections this week will be closely tied to one of the homework problems. Exam 1, Thursday evening, 2/21, 6:30-8:00pm HW2 scores
More informationFunctions and Decomposition
Unit 4 Functions and Decomposition Learning Outcomes Design and implement functions to carry out a particular task. Begin to evaluate when it is necessary to split some work into functions. Locate the
More information\n is used in a string to indicate the newline character. An expression produces data. The simplest expression
Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of
More informationAdvanced Python. Executive Summary, Session 1
Advanced Python Executive Summary, Session 1 OBJECT: a unit of data of a particular type with characteristic functionality (i.e., methods and/or use with operators). Everything in Python is an object.
More informationProgramming 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 informationChapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.
Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of
More informationIntroduction to Python! Lecture 2
.. Introduction to Python Lecture 2 Summary Summary: Lists Sets Tuples Variables while loop for loop Functions Names and values Passing parameters to functions Lists Characteristics of the Python lists
More informationBasic Python Revision Notes With help from Nitish Mittal
Basic Python Revision Notes With help from Nitish Mittal HELP from Documentation dir(module) help() Important Characters and Sets of Characters tab \t new line \n backslash \\ string " " or ' ' docstring
More information3.4. FOR-LOOPS 65. for <v a r i a b l e > in < sequence >:
3.4. FOR-LOOPS 65 3.4 For-loops In the previous section we looked at while-loops, Python s basic looping structure. There is a second loop construct in Python called a for-loop. This is more specialized.
More informationData type built into Python. Dictionaries are sometimes found in other languages as associative memories or associative arrays.
NETB 329 Lecture 4 Data Structures in Python Dictionaries Data type built into Python. Dictionaries are sometimes found in other languages as associative memories or associative arrays. 1 of 70 Unlike
More informationCS150 Sample Final. Name: Section: A / B
CS150 Sample Final Name: Section: A / B Date: Start time: End time: Honor Code: Signature: This exam is closed book, closed notes, closed computer, closed calculator, etc. You may only use (1) the final
More informationCIS192: Python Programming Data Types & Comprehensions Harry Smith University of Pennsylvania September 6, 2017 Harry Smith (University of Pennsylvani
CIS192: Python Programming Data Types & Comprehensions Harry Smith University of Pennsylvania September 6, 2017 Harry Smith (University of Pennsylvania) CIS 192 Fall Lecture 2 September 6, 2017 1 / 34
More informationCollections. 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 informationPython Lists and for Loops. Learning Outcomes. What s a List 9/19/2012
Python Lists and for Loops CMSC 201 Fall 2012 Instructor: John Park Lecture Section 01 Discussion Sections 02-08, 16, 17 1 Learning Outcomes Be aware that multiple items can be stored in a list. Become
More informationPython 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 informationGrade 6 Math Circles November 6 & Relations, Functions, and Morphisms
Faculty of Mathematics Waterloo, Ontario N2L 3G1 Centre for Education in Mathematics and Computing Relations Let s talk about relations! Grade 6 Math Circles November 6 & 7 2018 Relations, Functions, and
More informationPython allows variables to hold string values, just like any other type (Boolean, int, float). So, the following assignment statements are valid:
1 STRINGS Objectives: How text data is internally represented as a string Accessing individual characters by a positive or negative index String slices Operations on strings: concatenation, comparison,
More informationCS61A Lecture 16. Amir Kamil UC Berkeley February 27, 2013
CS61A Lecture 16 Amir Kamil UC Berkeley February 27, 2013 Announcements HW5 due tonight Trends project due on Tuesday Partners are required; find one in lab or on Piazza Will not work in IDLE New bug submission
More informationInteractive 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 informationCIS192 Python Programming
CIS192 Python Programming Data Types Joseph Cappadona University of Pennsylvania September 03, 2015 Joseph Cappadona (University of Pennsylvania) CIS 192 September 03, 2015 1 / 32 Outline 1 Data Types
More informationAccelerating 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 informationIf Statements, For Loops, Functions
Fundamentals of Programming If Statements, For Loops, Functions Table of Contents Hello World Types of Variables Integers and Floats String Boolean Relational Operators Lists Conditionals If and Else Statements
More informationInteractive 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 information6.00 Notes On Big-O Notation
6.00 Notes On Big-O Notation April 13, 2011 Sarina Canelake See also http://en.wikipedia.org/wiki/big O notation We use big-o notation in the analysis of algorithms to describe an algorithm s usage of
More informationModule 04: Lists. Topics: Lists and their methods Mutating lists Abstract list functions Readings: ThinkP 8, 10. CS116 Fall : Lists
Module 04: Lists Topics: Lists and their methods Mutating lists Abstract list functions Readings: ThinkP 8, 10 1 Consider the string method split >>> name = "Harry James Potter" >>> name.split() ['Harry',
More informationPython Programming: Lecture 2 Data Types
Python Programming: Lecture 2 Data Types Lili Dworkin University of Pennsylvania Last Week s Quiz 1..pyc files contain byte code 2. The type of math.sqrt(9)/3 is float 3. The type of isinstance(5.5, float)
More informationA Brief Introduction to Python
A Brief Introduction to Python Python is an interpreted language, meaning that a program, i.e., the interpreter, is used to execute your commands one after the other. The commands can be entered interactively
More informationdef F a c t o r i a l ( n ) : i f n == 1 : return 1 else : return n F a c t o r i a l ( n 1) def main ( ) : print ( F a c t o r i a l ( 4 ) )
116 4.5 Recursion One of the most powerful programming techniques involves a function calling itself; this is called recursion. It is not immediately obvious that this is useful; take that on faith for
More informationIntroduction to Python
Introduction to Python Development Environments what IDE to use? 1. PyDev with Eclipse 2. Sublime Text Editor 3. Emacs 4. Vim 5. Atom 6. Gedit 7. Idle 8. PIDA (Linux)(VIM Based) 9. NotePad++ (Windows)
More informationCS61A Lecture 16. Amir Kamil UC Berkeley February 27, 2013
CS61A Lecture 16 Amir Kamil UC Berkeley February 27, 2013 Announcements HW5 due tonight Trends project due on Tuesday Partners are required; find one in lab or on Piazza Will not work in IDLE New bug submission
More informationAdmin. How's the project coming? After these slides, read chapter 13 in your book. Quizzes will return
Recursion CS 1 Admin How's the project coming? After these slides, read chapter 13 in your book Yes that is out of order, but we can read it stand alone Quizzes will return Tuesday Nov 29 th see calendar
More informationAccelerating 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 informationPython: 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 informationCS150 - Sample Final
CS150 - Sample Final Name: Honor code: You may use the following material on this exam: The final exam cheat sheet which I have provided The matlab basics handout (without any additional notes) Up to two
More informationComputational Programming with Python
Numerical Analysis, Lund University, 2017 1 Computational Programming with Python Lecture 1: First steps - A bit of everything. Numerical Analysis, Lund University Lecturer: Claus Führer, Alexandros Sopasakis
More informationAlgorithm Design and Recursion. Search and Sort Algorithms
Algorithm Design and Recursion Search and Sort Algorithms Objectives To understand the basic techniques for analyzing the efficiency of algorithms. To know what searching is and understand the algorithms
More informationReview Sheet for Midterm #1 COMPSCI 119 Professor William T. Verts
Review Sheet for Midterm #1 COMPSCI 119 Professor William T. Verts Simple Data Types There are a number of data types that are considered primitive in that they contain only a single value. These data
More informationFor strings (and tuples, when we get to them), its easiest to think of them like primitives directly stored in the variable table.
Page 1 6.189 Notes Session 8 Day 6: Immutable Objects Earlier, we made a big deal about the fact that lists are mutable. The reason this is important is because certain objects are immutable once created,
More informationSCHEME 10 COMPUTER SCIENCE 61A. July 26, Warm Up: Conditional Expressions. 1. What does Scheme print? scm> (if (or #t (/ 1 0)) 1 (/ 1 0))
SCHEME 0 COMPUTER SCIENCE 6A July 26, 206 0. Warm Up: Conditional Expressions. What does Scheme print? scm> (if (or #t (/ 0 (/ 0 scm> (if (> 4 3 (+ 2 3 4 (+ 3 4 (* 3 2 scm> ((if (< 4 3 + - 4 00 scm> (if
More informationExam 1 Format, Concepts, What you should be able to do, and Sample Problems
CSSE 120 Introduction to Software Development Exam 1 Format, Concepts, What you should be able to do, and Sample Problems Page 1 of 6 Format: The exam will have two sections: Part 1: Paper-and-Pencil o
More informationOverview of List Syntax
Lists and Sequences Overview of List Syntax x = [0, 0, 0, 0] Create list of length 4 with all zeroes x 4300112 x.append(2) 3 in x x[2] = 5 x[0] = 4 k = 3 Append 2 to end of list x (now length 5) Evaluates
More informationIntroduction 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 information1.2 Adding Integers. Contents: Numbers on the Number Lines Adding Signed Numbers on the Number Line
1.2 Adding Integers Contents: Numbers on the Number Lines Adding Signed Numbers on the Number Line Finding Sums Mentally The Commutative Property Finding Sums using And Patterns and Rules of Adding Signed
More informationCS 115 Lecture 13. Strings. Neil Moore. Department of Computer Science University of Kentucky Lexington, Kentucky
CS 115 Lecture 13 Strings Neil Moore Department of Computer Science University of Kentucky Lexington, Kentucky 40506 neil@cs.uky.edu 29 October 2015 Strings We ve been using strings for a while. What can
More informationEE 355 Unit 17. Python. Mark Redekopp
1 EE 355 Unit 17 Python Mark Redekopp 2 Credits Many of the examples below are taken from the online Python tutorial at: http://docs.python.org/tutorial/introduction.html 3 Python in Context Interpreted,
More informationAn 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 informationdef order(food): food = food.upper() print( Could I have a big + food + please? ) return fresh + food
CSCI 1101B Lists Warm-up Exercise def order(food): food = food.upper() print( Could I have a big + food + please? ) return fresh + food food = order( pasta ) After this program runs 1. What is the global
More information