Python Lists, Tuples, Dictionaries, and Loops

Size: px
Start display at page:

Download "Python Lists, Tuples, Dictionaries, and Loops"

Transcription

1 Python Lists, Tuples, Dictionaries, and Loops What you need to Know For this lecture you need to know: 1. How to write and run basic python programs 2. How to create and assign data to variables 3. How to use the IF command in python Introduction You have learned how to define and use variables. A Variable is a named place in memory where data can be stored. Most variables have a unique name and hold a single value. However, there are times when you want to identify a set of data items with the same name. For examples, if you wanted to store sales numbers for days of the month, you could create a series of variables named sales1, sales2, sales30 but this is not a very efficient way to store data. As long as you can store the sales value by day number you can locate the sales value. Most programming languages have a storage type that can hold multiple values under a single name. Each item that will be stored in this structure so you can find it again by using an Index. The Index is an identifier used to locate a place in the data structure. In Python this is called a List or Tuple. For example, suppose you had a List named Sales and it contained a number of boxes, each of which has a number, and which can hold some sales data. You might assign sales numbers this way: Sales=[456.66, ,122.44,567.55] The variable named Sales now contains all the numbers listed on the right side of the equal sign. Each element of this List is automatically identified with an index number. Each element can be treated as a variable if you supply both the List name Sales and the index. Note that the index number starts at Zero. X = Sales[0] Sales[1] = There are four items in the Sales list. The first item (456.66) is at index position zero and the last item (567.55) is at index position 3. In the above lines of code the value at position zero is assigned to the variable X and the value at position 1 is changed to Understanding how Lists, Tuples, and Dictionaries work is critical in order to create more interesting programing in Python. Lists, Tuples, Dictionaries Lists In Python a List is an ordered collection of items that can have different kinds of indexes and that is expandable. You can create a list several different ways; by pre-defining the items and slots in the list or by creating an empty list and appending the items you want to add to the list. The important thing is to let Python know that you will be using a List. To pre-define the list and assign values you write the List Name on the left side of an equal sign and on the right side enclose the items you wish to put into the list with [ ] symbols. Each item is separated by a comma: Sales = [456.66, , , , ] This statement does two things; it creates a List variable and assigns data to this list. This command will automatically give each item an Index value starting at zero. For example:

2 Sales[0] is Sales[1] is Sales[2] is Sales[3] is Sales[4] is The index values are 0 to 4 and are used to identify the position of each data item in the List. You can use the List name and the index enclosed in [] symbols and treat each element as a variable, which means it can appear on either side of the equal sign: print( Sales for the first day are, Sales[0] ) Sales[1] = In the first line the print() method prints out the value of Sales[0]. In the second line the value of Sales[1] is changed from to Suppose you wish to add items to this list? Since the list List was created with a set number of values (5 numbers at the index positions 0 to 4) you must use the Append() method. This is a method that is automatically attached to any List you create. This method will append the item to the end of the list. For example: NewSales = [12, 44, 55] print(newsales) NewSales.append(99) print(newsales) This program will print: [12, 44, 55] [12, 44, 55, 99] The append() method has added the value 99 to the end of the list. The print() method will print an entire list. To remove an item from a list you can use the pop() method. This will remove an item from a specific position and return the item or it will return the last item on the list of you don t specify an index. For example: MyList = [40, 50, 60, 70, 80] MyList.append(100) x = MyList.pop(1) y = MyList.pop() This program will print: [40, 50, 60, 70, 80] [40, 50, 60, 70, 80, 100] # after append(100) [40, 60, 70, 80, 100] # after pop(1) [40, 60, 70, 80] # after pop() Notice that the pop(index) command will remove the item at the index (remember that Lists start the index at zero) which the pop() command removes the last item in the list. You can also inset new items into a list at specific positions using the insert( index, value). Existing items are shifted to the right:

3 MyList = [40, 50, 60, 70, 80] MyList.insert(2, 100) This program will print: [40, 50, 60, 70, 80] [40, 50, 100, 60, 70, 80] With the value 100 inserted at index position 2 and everything shifted over. You can put a variety of data items in lists including Strings and even other lists. An example of storing names in a list is: Employees = [ Smith, Edwards, Jones, Franks ] print(employees) You still index the elements the same way: print(employees[1] ) will print Edwards. Another useful method for Lists is the sort method which will rearrange a list in descending sort order. Employees = [ Smith, Edwards, Jones, Franks ] print(employees) Employees.sort() print(employees) This will print [ Smith, Edwards, Jones, Franks ] [ Edwards, Franks, Jones, Smith ] # before sort # after sort You can sort numbers in the same way. Lists can contain both numbers and Strings and most of the List methods still work (except for sort() ) MyData = [ Smith, 55, Jones, 45.55, False] Ranges There are times when you want to create a list of numbers or use a list of numbers. This can be done by manually creating a list containing integer values but Python has a built-in method to return a set of values. This is called a range. The range method has the following syntax: range( start number, one greater than end number) for example, range(0,10) will return a set of numbers from 0 to 9. This can be converted into a list by using: x = list( range(0,10) ) print(x) which will print [0,1,2,3,4,5,6,7,8,9] You can also use ranges in loops:

4 for i in range(0,10): print( value is,i) will print value is 0 value is 1 value is 2 value is 9 Tuples A Tuple looks similar to a list with one important exception; Tuples cannot be modified once they are created. A Tuple is used to store a set of values under a single name but these values cannot be change. Tuples are defined using () rather than []. However, the elements in a Tuple are referenced as read-only using the index notation. For example: MyTuple = (34, 22, 44) print(mytuple) print( MyTuple[1] ) This will print (34, 22, 44) 22 #index item 1 If you try to modify an element in a Tuple Python will return an error: MyTuple[0] = 9999 # this returns an error Tuples are used to store fixed sets of data that won t be changed. For example, X and Y index values or RGB colors. Dictionaries The final structured data item in Python is called a Dictionary. This term refers to the way that index work in an ordered list of items. In both Lists and Tuples the index value is a number starting at zero. We can access an item in a List or Tuple by using the name of the List/Tuple and the index. This works ok, but there are times when the index value itself has informational content. That is, meaningful index are good for locating items in a list. Python has a way to store ordered data and use strings as index values. Defining a Dictionary is different from a List or Tuple because you must also specify the index value along with the data item value. For example, suppose you wanted to store sales data totals my month. It would be useful if the month name was the index value. You don t have to remember that index 0 is January, 2 is March, etc. A Dictionary is defined using the {} symbols which enclose the index string and the value. MonthSales = {"Jan":456.77, "Feb":123.44, "Mar":567.33} You access the elements in this dictionary using the string as the index: print(monthsales[ Jan ] ) MonthSales[ Jan ] = Adding items to a Dictionary is not done using append() but by just setting a new value MonthSales[ Apr ] = print(monthsales)

5 This will print: { Jan :456.77, Feb :123.44, Mar :567.33, Apr : } Using Lists, Tuples, and Dictionaries Lists, Tuples, and Dictionaries are used in a wide variety of applications. The main purpose of such data structures is to be able to handle multiple items that are related in some way. A List of names may be used to organize Students or Employees and a Dictionary may be used to handle pay amounts. The main operations on Lists, Tuples, and Dictionaries are Create Add to and Remove items in list Locate items in list Split and combine lists Loop through lists The last activity will be illustrated when we learn how to create loops in Python. Creating: MyList = list() # create empty list MyList = [123, 555, 9999] MyTuple = (0, 255,0) MyNames = {} # create empty Dictionary MyNames = { Jan :45.55, Feb :23.44, Mar :98.33} Adding and Removing: MyList.append(876.33) # add element to end of list MyList.pop(0) # remove element at position 0 del( MyList[0] ) # remove element at position 0 MyNames[ Apr ] = # adds element to MyNames del( MyNames[ Apr ] ) # removes element from MyNames You can use the in command to locate items in a list. This operator returns True or False if the value (List) or index (Dictionary) is in the list. For example: MyList = [100, 300, 400, 600] if 100 in MyList: print( Value is in list ) x = MyList.index(100) # get index for item 100 print( Value is, MyList[x] ) In this example, a list is created and the if command returns True if the value 100 is one of the values in the list. If this value is in the list then the message Value is in list is printed. Next, the index value of this value is returned into x (or at least the first value that matches if there are more than one elements with the value of 100 ) and used to print the value at this index. Dictionaries are similar but the index string is being searched: MonthSales = { Jan :100, Feb : 200, Mar : 300} if Jan in MonthSales: print( Found index ) print( Value is, MonthSales[ Jan ] You can also split and combine Lists by using ranges of index values:

6 MyList = [100, 200, 300, 400, 500] print( MyList[0:2]) Will print: [100, 200] Notice that the syntax of this command (which is called Splitting the List) is: ListName[ startindex: endindex+1] The endindex+1 is the index value one past where you want to split the list. That is if you want to print index items 0, 1, 2 you would use: print(mylist[0:3] ) because 3 is one greater than the index you wish to print. This range option in the List index field can also be used to split a list and get a copy of a subsection of the List. MyList = [100, 200, 400, 500, 800] List2 = MyList[0:3] print(list2) This would print: [100, 200, 400] Since 400 is at position 2 while the split command is [0:3] Loops Looping in a computer program means your program will execute commands more than once. This is often used as part of the programming logic. A loop must include two components: 1. A way to indicate what lines of code are part of the loop 2. A way to control when the loop ends This second item is important otherwise you may end up writing programs that go into loops and never get out. Python has two kinds of loops, Logical Loops and Data Loops. The first type using a Boolean expression and the while statement. The second uses some data structure and the for statement. Both kinds of loops use the : symbol and tabs to indicate what lines of code will be part of the loop. For example, suppose you want to subtract a number from a value until the value reaches a particular level. WaterLevel = 38 DrainAmount =.5 Count = 0 while (WaterLevel > 10): WaterLevel = WaterLevel DrainAmount Count = Count + 1 print( Water level is, WaterLevel, it took, Count, times through loop ) The command: while( WaterLevel > 10): is the Boolean expression which is being evaluated each time the loop executes. The basic logic is:

7 1. The Boolean expression is evaluated at the start of the loop. 2. If the Boolean expression is True then the loop code is executed 3. If the Boolean expression is False then the loop code is skipped. Notice that the WaterLevel variable is initially set to 38. If this variable was set to 10 (which is not greater than 10) then the loop would be skipped entirely and it would never run. The while(waterlevel>10) Boolean expression is False and so the loop is never run. The second type of loop is a Data loop and it is typically used with a List, Tuple, or Dictionary. This uses the in command to sequence over each item in the List/Tuple/Dictionary MyList = [133, 444, 234, 900] for x in MyList: print( Value is, x) Will print: Value is 133 Value is 444 Value is 234 Value is 900 The For statement is followed by a variable (in this case named x ). The for loop will successively get each value in the list and put it into the X variable. This variable is then used in the code identified as part of the loop. Tuples work the same was as Lists. A Dictionary can be iterated in the same way but what is put into the X value are the index values: MyNames = { Smith : , Jones :234.44, Edwards :890.00} for namex in MyNames: print( Index is, namex, and value is,mynames[namex] ) Since each index is returned into the namex variable this can be used with the Dictionary name to retrieve the value at that location. Using Loops Sample program One Loops are used in many different ways in a computer program. As an example, consider a user-interface program that asks the user to enter how much money they want to withdraw from their checking account. This program has a method named GetAvailable() which will return the available balance the user has in their account. For the purpose of this program the method will return a fixed number, but in a real program this method would likely connect to a central computer and use the user s PIN code to retrieve the balance. Program Description: This program is used to withdraw money from an account. The user is prompted to enter their PIN number and the amount they wish to withdraw. If the PIN is correct and the amount they wish to withdraw is less than the daily balance and less than or equal their checking amount then they can have the money. If they are trying to withdraw more than the daily amount an error message is displayed and the user is asked to exit or try a new amount. If the amount is more than they have in their account they are asked to exit or try a new amount. Program Outline: 1. Ask user to enter PIN code. 2. Read PIN code

8 3. Verify PIN code (call VerifyPin( pin ) ) 4. If PIN code is bad then a. Ask user to either re-enter or exit. b. Get input from user. c. If user chooses re-enter then go back to step 1 d. If user chooses exit then end program 5. If code is good then a. Get Daily Limit (getdailylimit() method) b. Get Checking Amount (getcheckingamount() method) c. Ask user for withdrawal amount d. Get input from user. e. If withdrawal amount > Daily Limit or > checking amount then i. Print error message (either over daily limit or over checking amount) ii. Ask user to either re-enter amount or exit iii. Get input from user iv. If user chooses to re-enter then go back to step 5d v. If user chooses to exit the end program. f. If withdrawal amount valid then i. Deduct amount from checking. ii. Give money to user ( issuemoney( amount) method ) 6. End Program This program outline references four methods that we are not going to write but will be written by another programmer. We can write our own versions of these methods and hard-code in numbers for the purpose of testing, but when our module is integrated with the main program we will have to change our code. Program Code: (Note: the symbol indicates that the following line should be on the same line) author = 'dcraig' import sys # Stub methods for testing purposes - actual methods will be external to this program def VerifyPin( pin ): return True def GetDailyLimit(pin): return def GetCheckingAmount(pin): return def IssueMoney( amount ): return True ################# Main program ################## # Ask user to enter Pin loop

9 EnterPinFlag = False Pin = "" while(enterpinflag==false): Pin = input("enter Pin and press Enter ") if( VerifyPin(Pin)==True): EnterPinFlag = True else: ans = input("invalid Pin - Continue or Exit - Enter C or X ") if( ans=="x"): sys.exit() # Get Daily Limit and Checking Amount DailyLimit = GetDailyLimit(Pin) CheckingAmount = GetCheckingAmount(Pin) # Ask user for amount to withdraw AmountFlag = False CheckingFlag = False AmountWith = 0 while(amountflag==false or CheckingFlag==False): withdrawstr = input("enter Amount to withdraw ") AmountWith = float(withdrawstr) if(amountwith<dailylimit and AmountWith>0.0): AmountFlag = True else: ans = input("error: Over daily withdraw limit -Try again or exit Enter T or X ") if(ans=="x"): print("have a nice day") sys.exit() if(amountwith<=checkingamount): CheckingFlag = True else: ans = input("error: You don't have enough in checking -Try again or exit- Enter T or X ") if(ans=="x"): print("have a nice day") sys.exit() print("you are withdrawing",amountwith) if( IssueMoney(AmountWith)==True): print("transaction Complete") else: print("error - problem with computer")

The Practice of Computing Using PYTHON

The 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 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

Topic 7: Lists, Dictionaries and Strings

Topic 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 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

LECTURE 3 Python Basics Part 2

LECTURE 3 Python Basics Part 2 LECTURE 3 Python Basics Part 2 FUNCTIONAL PROGRAMMING TOOLS Last time, we covered function concepts in depth. We also mentioned that Python allows for the use of a special kind of function, a lambda function.

More information

Dictionaries. Looking up English words in the dictionary. Python sequences and collections. Properties of sequences and collections

Dictionaries. Looking up English words in the dictionary. Python sequences and collections. Properties of sequences and collections Looking up English words in the dictionary Comparing sequences to collections. Sequence : a group of things that come one after the other Collection : a group of (interesting) things brought together for

More information

University of Texas at Arlington, TX, USA

University 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 information

Comp Exam 1 Overview.

Comp Exam 1 Overview. Comp 170-400 Exam 1 Overview. Resources During the Exam The exam will be closed book, no calculators or computers, except as a word processor. In particular no Python interpreter running in a browser or

More information

EXAM Computer Science 1 Part 1

EXAM Computer Science 1 Part 1 Maastricht University Faculty of Humanities and Science Department of Knowledge Engineering EXAM Computer Science 1 Part 1 Block 1.1: Computer Science 1 Code: KEN1120 Examiner: Kurt Driessens Date: Januari

More information

Python Review IPRE

Python 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 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

Python review. 1 Python basics. References. CS 234 Naomi Nishimura

Python review. 1 Python basics. References. CS 234 Naomi Nishimura Python review CS 234 Naomi Nishimura The sections below indicate Python material, the degree to which it will be used in the course, and various resources you can use to review the material. You are not

More information

John Perry. Fall 2009

John Perry. Fall 2009 Lecture 5: Sage University of Southern Mississippi Fall 2009 Outline 1 2 3 4 You should be in worksheet mode to repeat the examples. Collections? Collection: group of objects identified as single object

More information

1. Managing Information in Table

1. Managing Information in Table 1. Managing Information in Table Spreadsheets are great for making lists (such as phone lists, client lists). The researchers discovered that not only was list management the number one spreadsheet activity,

More information

Lecture 10: Boolean Expressions

Lecture 10: Boolean Expressions Lecture 10: Boolean Expressions CS1068+ Introductory Programming in Python Dr Kieran T. Herley Department of Computer Science University College Cork 2017-2018 KH (12/10/17) Lecture 10: Boolean Expressions

More information

Collections. John Perry. Fall 2011

Collections. John Perry. Fall 2011 MAT 305: Collections University of Southern Mississippi Fall 2011 Outline 1 2 3 4 Collections? Collection: group of objects identified as single object indexed tuples a 0, a 1, a 2,...a n points x 0, y

More information

2. Explain the difference between read(), readline(), and readlines(). Give an example of when you might use each.

2. Explain the difference between read(), readline(), and readlines(). Give an example of when you might use each. CMSC 0 Fall 0 Name Final Review Worksheet This worksheet is NOT guaranteed to cover every topic you might see on the exam. It is provided to you as a courtesy, as additional practice problems to help you

More information

Using Lists (Arrays) Notes

Using Lists (Arrays) Notes Using Lists (Arrays) Notes - 27.11.16 Array/List = a data structure that allows for multiplied items or elements to be stored using just one variable name. Each element in a list is accessed using an index

More information

Making a table; problem. The while loop. Making a table; simple solution. INF1100 Lectures, Chapter 2: Lists and Loops. 5mm.

Making a table; problem. The while loop. Making a table; simple solution. INF1100 Lectures, Chapter 2: Lists and Loops. 5mm. 5mm. Making a table; problem INF1100 Lectures, Chapter 2: Lists and Loops Hans Petter Langtangen Simula Research Laboratory University of Oslo, Dept. of Informatics Suppose we want to make a table of Celsius

More information

CS 1803 Pair Homework 4 Greedy Scheduler (Part I) Due: Wednesday, September 29th, before 6 PM Out of 100 points

CS 1803 Pair Homework 4 Greedy Scheduler (Part I) Due: Wednesday, September 29th, before 6 PM Out of 100 points CS 1803 Pair Homework 4 Greedy Scheduler (Part I) Due: Wednesday, September 29th, before 6 PM Out of 100 points Files to submit: 1. HW4.py This is a PAIR PROGRAMMING Assignment: Work with your partner!

More information

Jarek Szlichta

Jarek Szlichta Jarek Szlichta http://data.science.uoit.ca/ Python is a straightforward language very simple syntax It encourages programmers to program without boilerplate (prepared) code 2 Python is completely object

More information

Problem Solving for Intro to Computer Science

Problem Solving for Intro to Computer Science Problem Solving for Intro to Computer Science The purpose of this document is to review some principles for problem solving that are relevant to Intro to Computer Science course. Introduction: A Sample

More information

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

All 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 information

Python Review IPRE

Python 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 information

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

There 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 information

Introduction to Python! Lecture 2

Introduction 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 information

Java. Programming: Chapter Objectives. Why Is Repetition Needed? Chapter 5: Control Structures II. Program Design Including Data Structures

Java. Programming: Chapter Objectives. Why Is Repetition Needed? Chapter 5: Control Structures II. Program Design Including Data Structures Chapter 5: Control Structures II Java Programming: Program Design Including Data Structures Chapter Objectives Learn about repetition (looping) control structures Explore how to construct and use count-controlled,

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

CS2304: Python for Java Programmers. CS2304: Sequences and Collections

CS2304: 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 information

Chapter 1. Data types. Data types. In this chapter you will: learn about data types. learn about tuples, lists and dictionaries

Chapter 1. Data types. Data types. In this chapter you will: learn about data types. learn about tuples, lists and dictionaries Chapter 1 Data types In this chapter you will: learn about data types learn about tuples, lists and dictionaries make a magic card trick app. Data types In Python Basics you were introduced to strings

More information

CS 2316 Individual Homework 4 Greedy Scheduler (Part I) Due: Wednesday, September 18th, before 11:55 PM Out of 100 points

CS 2316 Individual Homework 4 Greedy Scheduler (Part I) Due: Wednesday, September 18th, before 11:55 PM Out of 100 points CS 2316 Individual Homework 4 Greedy Scheduler (Part I) Due: Wednesday, September 18th, before 11:55 PM Out of 100 points Files to submit: 1. HW4.py This is an INDIVIDUAL assignment! Collaboration at a

More information

CS1 Lecture 11 Feb. 9, 2018

CS1 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 information

CS Homework 4 Employee Ranker. Due: Wednesday, February 8th, before 11:55 PM Out of 100 points. Files to submit: 1. HW4.py.

CS Homework 4 Employee Ranker. Due: Wednesday, February 8th, before 11:55 PM Out of 100 points. Files to submit: 1. HW4.py. CS 216 Homework 4 Employee Ranker Due: Wednesday, February 8th, before 11: PM Out of 0 points Files to submit: 1. HW4.py This is an INDIVIDUAL assignment! Collaboration at a reasonable level will not result

More information

Question 1. tmp = Stack() # Transfer every item from stk onto tmp. while not stk.is_empty(): tmp.push(stk.pop())

Question 1. tmp = Stack() # Transfer every item from stk onto tmp. while not stk.is_empty(): tmp.push(stk.pop()) Note to Students: This file contains sample solutions to the term test together with the marking scheme and comments for each question. Please read the solutions and the marking schemes and comments carefully.

More information

Python Lists and for Loops. Learning Outcomes. What s a List 9/19/2012

Python 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 information

CS 1301 Exam 2 Fall 2010

CS 1301 Exam 2 Fall 2010 CS 1301 Exam 2 Fall 2010 Name : Grading TA: Devices: If your cell phone, pager, PDA, beeper, ipod, or similar item goes off during the exam, you will lose 10 points on this exam. Turn all such devices

More information

ENGR 102 Engineering Lab I - Computation

ENGR 102 Engineering Lab I - Computation ENGR 102 Engineering Lab I - Computation Week 07: Arrays and Lists of Data Introduction to Arrays In last week s lecture, 1 we were introduced to the mathematical concept of an array through the equation

More information

CS1 Lecture 12 Feb. 11, 2019

CS1 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 information

Python debugging and beautification

Python debugging and beautification Python debugging and beautification #!/usr/bin/env python # # # THIS CODE DOES NOT WORK import sys def read(a): myfile = open(a,'r'): for i in myfile: yield i myfile.close() def count_chars(a): sum = 0

More information

CMSC201 Computer Science I for Majors

CMSC201 Computer Science I for Majors CMSC201 Computer Science I for Majors Lecture 08 Lists Constants Last Class We Covered More on while loops Sentinel loops Priming Reads Boolean flags 2 Any Questions from Last Time? 3 Today s Objectives

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

Ch.2: Loops and lists

Ch.2: Loops and lists Ch.2: Loops and lists Hans Petter Langtangen 1,2 Joakim Sundnes 1,2 Simula Research Laboratory 1 University of Oslo, Dept. of Informatics 2 Sep 1, 2017 Main topics of Chapter 2 Using loops for repeating

More information

Outline for Today CSE 142. CSE142 Wi03 G-1. withdraw Method for BankAccount. Class Invariants

Outline for Today CSE 142. CSE142 Wi03 G-1. withdraw Method for BankAccount. Class Invariants CSE 142 Outline for Today Conditional statements if Boolean expressions Comparisons (=,!=, ==) Boolean operators (and, or, not - &&,,!) Class invariants Conditional Statements & Boolean Expressions

More information

Try and Error. Python debugging and beautification

Try and Error. Python debugging and beautification Try and Error Python debugging and beautification What happens when something goes wrong Catching exceptions In order to handle errors, you can set up exception handling blocks in your code. The keywords

More information

Loop structures and booleans

Loop structures and booleans Loop structures and booleans Michael Mandel Lecture 7 Methods in Computational Linguistics I The City University of New York, Graduate Center https://github.com/ling78100/lectureexamples/blob/master/lecture07final.ipynb

More information

Fundamentals. Fundamentals. Fundamentals. We build up instructions from three types of materials

Fundamentals. Fundamentals. Fundamentals. We build up instructions from three types of materials Fundamentals We build up instructions from three types of materials Constants Expressions Fundamentals Constants are just that, they are values that don t change as our macros are executing Fundamentals

More information

Chapter 8 : Computer Science. Datastructures: Class XII ( As per CBSE Board) lists, stacks, queues. Visit : python.mykvs.in for regular updates

Chapter 8 : Computer Science. Datastructures: Class XII ( As per CBSE Board) lists, stacks, queues. Visit : python.mykvs.in for regular updates Chapter 8 : Computer Science Class XII ( As per CBSE Board) Datastructures: lists, stacks, queues It a way of organizing and storing data in such a manner so that it can be accessed and work over it can

More information

Week 3. Sun Jun with slides from Hans Petter Langtangen

Week 3. Sun Jun with slides from Hans Petter Langtangen Week 3 Sun Jun with slides from Hans Petter Langtangen Nested lists: list of lists A list can contain any object, also another list Instead of storing a table as two separate lists (one for each column),

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

Classes and Objects 1

Classes and Objects 1 Classes and Objects 1 Built-in objects You are already familiar with several kinds of objects: strings, lists, sets, tuples, and dictionaries An object has two aspects: Some fields (or instance variables)

More information

Lab 3: Decisions and Boolean Logic This lab accompanies Chapter 4 of Starting Out with Programming Logic & Design.

Lab 3: Decisions and Boolean Logic This lab accompanies Chapter 4 of Starting Out with Programming Logic & Design. Starting Out with Programming Logic and Design 1 Lab 3: Decisions and Boolean Logic This lab accompanies Chapter 4 of Starting Out with Programming Logic & Design. Lab 3.1 Evaluating Conditions Critical

More information

What Version Number to Install

What Version Number to Install A Python Primer This chapter provides a quick overview of the Python language. The goal in this chapter is not to teach you the Python language excellent books have been written on that subject, such as

More information

Visualize ComplexCities

Visualize ComplexCities Introduction to Python Chair of Information Architecture ETH Zürich February 22, 2013 First Steps Python Basics Conditionals Statements Loops User Input Functions Programming? Programming is the interaction

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

Conditional Formatting

Conditional Formatting Microsoft Excel 2013: Part 5 Conditional Formatting, Viewing, Sorting, Filtering Data, Tables and Creating Custom Lists Conditional Formatting This command can give you a visual analysis of your raw data

More information

Introduction to Python, Cplex and Gurobi

Introduction to Python, Cplex and Gurobi Introduction to Python, Cplex and Gurobi Introduction Python is a widely used, high level programming language designed by Guido van Rossum and released on 1991. Two stable releases: Python 2.7 Python

More information

CS 234 Python Review Part 2

CS 234 Python Review Part 2 CS 234 Python Review Part 2 Recap import function: define, return boolean, conditional, branching loop: for, range, while file: open, close, readlines string: split Classes Define blueprint for a custom

More information

TUPLES AND RECURSIVE LISTS 5

TUPLES AND RECURSIVE LISTS 5 TUPLES AND RECURSIVE LISTS 5 COMPUTER SCIENCE 61A July 3, 2012 1 Sequences From the Pig project, we discovered the utility of having structures that contain multiple values. Today, we are going to cover

More information

Be careful when deciding whether to represent data as integers or floats, and be sure that you consider all possible behaviors in computation.

Be careful when deciding whether to represent data as integers or floats, and be sure that you consider all possible behaviors in computation. Table of Contents: 1. Integers and floats 2. for vs. while loops 3. Checking boolean conditions with if/else 4. Docstrings 5. Changing collections while iterating over them 6. Directly Accessing Instance

More information

(b) If a heap has n elements, what s the height of the tree?

(b) If a heap has n elements, what s the height of the tree? CISC 5835 Algorithms for Big Data Fall, 2018 Homework Assignment #4 1 Answer the following questions about binary tree and heap: (a) For a complete binary tree of height 4 (we consider a tree with just

More information

CircuitPython 101: Basic Builtin Data Structures

CircuitPython 101: Basic Builtin Data Structures CircuitPython 101: Basic Builtin Data Structures Created by Dave Astels Last updated on 2019-01-05 08:01:45 PM UTC Guide Contents Guide Contents Overview Tools and Materials Tuple List Making songs Dictionary

More information

CMSC 201 Fall 2018 Lab 04 While Loops

CMSC 201 Fall 2018 Lab 04 While Loops CMSC 201 Fall 2018 Lab 04 While Loops Assignment: Lab 04 While Loops Due Date: During discussion, September 24 th through September 27 th Value: 10 points (8 points during lab, 2 points for Pre Lab quiz)

More information

CMSC201 Computer Science I for Majors

CMSC201 Computer Science I for Majors CMSC201 Computer Science I for Majors Lecture 08 Lists Constants Last Class We Covered More on while loops Sentinel loops Boolean flags 2 Any Questions from Last Time? 3 Today s Objectives To learn about

More information

COMP 103. Mid Trimester Test 17 August 2006

COMP 103. Mid Trimester Test 17 August 2006 Name ID: COMP 103 Mid Trimester Test 17 August 2006 Time: 90 minutes Marks: 90 Answer all questions. Non programmable calculators permitted Unannotated foreign language dictionaries permitted 1. Collection

More information

Sharing, mutability, and immutability. Ruth Anderson UW CSE 160 Spring 2018

Sharing, mutability, and immutability. Ruth Anderson UW CSE 160 Spring 2018 Sharing, mutability, and immutability Ruth Anderson UW CSE 160 Spring 2018 1 Copying and mutation See in python tutor list1 = ["e1", "e2", "e3", "e4"] list2 = list1 list3 = list(list1) # make a copy; also

More information

CS 112: Intro to Comp Prog

CS 112: Intro to Comp Prog CS 112: Intro to Comp Prog Importing modules Branching Loops Program Planning Arithmetic Program Lab Assignment #2 Upcoming Assignment #1 Solution CODE: # lab1.py # Student Name: John Noname # Assignment:

More information

Python Tutorial. CS/CME/BioE/Biophys/BMI 279 Oct. 17, 2017 Rishi Bedi

Python Tutorial. CS/CME/BioE/Biophys/BMI 279 Oct. 17, 2017 Rishi Bedi Python Tutorial CS/CME/BioE/Biophys/BMI 279 Oct. 17, 2017 Rishi Bedi 1 Python2 vs Python3 Python syntax Data structures Functions Debugging Classes The NumPy Library Outline 2 Many examples adapted from

More information

GE PROBLEM SOVING AND PYTHON PROGRAMMING. Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING

GE PROBLEM SOVING AND PYTHON PROGRAMMING. Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING GE8151 - PROBLEM SOVING AND PYTHON PROGRAMMING Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING 1) Define Computer 2) Define algorithm 3) What are the two phases in algorithmic problem solving? 4) Why

More information

CSc 110, Spring Lecture 24: print revisited, tuples cont.

CSc 110, Spring Lecture 24: print revisited, tuples cont. CSc 110, Spring 2017 Lecture 24: print revisited, tuples cont. 1 print 2 print revisited We often convert to strings when printing variables: print("the sum is " + str(sum)) This is not always necessary.

More information

COMP284 Scripting Languages Lecture 3: Perl (Part 2) Handouts

COMP284 Scripting Languages Lecture 3: Perl (Part 2) Handouts COMP284 Scripting Languages Lecture 3: Perl (Part 2) Handouts Ullrich Hustadt Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University of Liverpool

More information

CS Summer 2013

CS 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 information

Programming to Python

Programming to Python Programming to Python Sept., 5 th Slides by M. Stepp, M. Goldstein, M. DiRamio, and S. Shah Compiling and interpreting Many languages require you to compile (translate) your program into a form that the

More information

Strings, Lists, and Sequences

Strings, Lists, and Sequences Strings, Lists, and Sequences It turns out that strings are really a special kind of sequence, so these operations also apply to sequences! >>> [1,2] + [3,4] [1, 2, 3, 4] >>> [1,2]*3 [1, 2, 1, 2, 1, 2]

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

The Hong Kong Polytechnic University

The Hong Kong Polytechnic University COMP1001-Problem Solving in IT Top-Down Design Objective: Upon completion of this lab, you will be able to: How to use top down design to design an Automatic teller machine (ATM) Structure of Top-Down

More information

6.149 Checkoff 2. What to complete. Recall: Creating a file and running a program in IDLE.

6.149 Checkoff 2. What to complete. Recall: Creating a file and running a program in IDLE. 6.149 Checkoff 2 http://web.mit.edu/6.149/www/materials.html What to complete Due: Wednesday, January 14, 2015 @ 5 p.m. 1. checkoff2 user input.py, which will contain your code for 2.1 - User input 2.

More information

Quiz 1 Practice Problems

Quiz 1 Practice Problems Introduction to Algorithms: 6.006 Massachusetts Institute of Technology March 7, 2008 Professors Srini Devadas and Erik Demaine Handout 6 1 Asymptotic Notation Quiz 1 Practice Problems Decide whether these

More information

POS Register Instructions

POS Register Instructions POS Register Instructions Updated April 29, 2016 Prepared by Tina Leinbaugh I. Daily Start-Up... 1 A. Receipt Printer ON... 1 B. The Screen should be ON... 1 C. Turn the Computer ON... 1 II. Start of Shift...

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

Spring INF Principles of Programming for Informatics. Manipulating Lists

Spring INF Principles of Programming for Informatics. Manipulating Lists Manipulating Lists Copyright 2017, Pedro C. Diniz, all rights reserved. Students enrolled in the INF 510 class at the University of Southern California (USC) have explicit permission to make copies of

More information

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

CS 11 python track: lecture 3. n Today: Useful coding idioms CS 11 python track: lecture 3 Today: Useful coding idioms Useful coding idioms "Idiom" Standard ways of accomplishing a common task Using standard idioms won't make your code more correct, but more concise

More information

Basic Python 3 Programming (Theory & Practical)

Basic Python 3 Programming (Theory & Practical) Basic Python 3 Programming (Theory & Practical) Length Delivery Method : 5 Days : Instructor-led (Classroom) Course Overview This Python 3 Programming training leads the student from the basics of writing

More information

PYTHON. Varun Jain & Senior Software Engineer. Pratap, Mysore Narasimha Raju & TEST AUTOMATION ARCHITECT. CenturyLink Technologies India PVT LTD

PYTHON. Varun Jain & Senior Software Engineer. Pratap, Mysore Narasimha Raju & TEST AUTOMATION ARCHITECT. CenturyLink Technologies India PVT LTD PYTHON Varun Jain & Senior Software Engineer Pratap, Mysore Narasimha Raju & TEST AUTOMATION ARCHITECT CenturyLink Technologies India PVT LTD 1 About Python Python is a general-purpose interpreted, interactive,

More information

DM550/DM857 Introduction to Programming. Peter Schneider-Kamp

DM550/DM857 Introduction to Programming. Peter Schneider-Kamp DM550/DM857 Introduction to Programming Peter Schneider-Kamp petersk@imada.sdu.dk http://imada.sdu.dk/~petersk/dm550/ http://imada.sdu.dk/~petersk/dm857/ HANDLING TEXT FILES 2 Reading Files open files

More information

CSE 341 Section Handout #6 Cheat Sheet

CSE 341 Section Handout #6 Cheat Sheet Cheat Sheet Types numbers: integers (3, 802), reals (3.4), rationals (3/4), complex (2+3.4i) symbols: x, y, hello, r2d2 booleans: #t, #f strings: "hello", "how are you?" lists: (list 3 4 5) (list 98.5

More information

Lecture 02 Making Decisions: Conditional Execution

Lecture 02 Making Decisions: Conditional Execution Lecture 02 Making Decisions: Conditional Execution 1 Flow of Control Flow of control = order in which statements are executed By default, a program's statements are executed sequentially, from top to bottom.

More information

CIS192: Python Programming

CIS192: Python Programming CIS192: Python Programming Introduction Harry Smith University of Pennsylvania January 18, 2017 Harry Smith (University of Pennsylvania) CIS 192 Lecture 1 January 18, 2017 1 / 34 Outline 1 Logistics Rooms

More information

1. Managing Information in Table

1. Managing Information in Table 1. Managing Information in Table Spreadsheets are great for making lists (such as phone lists, client lists). The researchers discovered that not only was list management the number one spreadsheet activity,

More information

Computational Programming with Python

Computational 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 information

CSC Software I: Utilities and Internals. Programming in Python

CSC Software I: Utilities and Internals. Programming in Python CSC 271 - Software I: Utilities and Internals Lecture #8 An Introduction to Python Programming in Python Python is a general purpose interpreted language. There are two main versions of Python; Python

More information

Quiz 1 Practice Problems

Quiz 1 Practice Problems Introduction to Algorithms: 6.006 Massachusetts Institute of Technology March 7, 2008 Professors Srini Devadas and Erik Demaine Handout 6 1 Asymptotic Notation Quiz 1 Practice Problems Decide whether these

More information

Microsoft Access XP (2002) - Advanced Queries

Microsoft Access XP (2002) - Advanced Queries Microsoft Access XP (2002) - Advanced Queries Group/Summary Operations Change Join Properties Not Equal Query Parameter Queries Working with Text IIF Queries Expression Builder Backing up Tables Action

More information

CS Homework 4 Lifeguard Employee Ranker. Due: Tuesday, June 3rd, before 11:55 PM Out of 100 points. Files to submit: 1. HW4.py.

CS Homework 4 Lifeguard Employee Ranker. Due: Tuesday, June 3rd, before 11:55 PM Out of 100 points. Files to submit: 1. HW4.py. CS 2316 Homework 4 Lifeguard Employee Ranker Due: Tuesday, June 3rd, before 11: PM Out of 100 points Files to submit: 1. HW4.py This is an PAIR assignment! This is a pair programming problem! You are expected

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Object Oriented Programming Harry Smith University of Pennsylvania February 15, 2016 Harry Smith (University of Pennsylvania) CIS 192 Lecture 5 February 15, 2016 1 / 26 Outline

More information

Lecture Notes for Chapter 2: Getting Started

Lecture Notes for Chapter 2: Getting Started Instant download and all chapters Instructor's Manual Introduction To Algorithms 2nd Edition Thomas H. Cormen, Clara Lee, Erica Lin https://testbankdata.com/download/instructors-manual-introduction-algorithms-2ndedition-thomas-h-cormen-clara-lee-erica-lin/

More information

Composite Types. You will learn how to create new variables that are collections of other entities. Types Of Variables.

Composite Types. You will learn how to create new variables that are collections of other entities. Types Of Variables. Composite Types You will learn how to create new variables that are collections of other entities Types Of Variables Python variables Example composite A string (collection of characters) can be decomposed

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

Text Input and Conditionals

Text Input and Conditionals Text Input and Conditionals Text Input Many programs allow the user to enter information, like a username and password. Python makes taking input from the user seamless with a single line of code: input()

More information

Python Tutorial. Day 2

Python Tutorial. Day 2 Python Tutorial Day 2 1 Control: Whitespace in perl and C, blocking is controlled by curly-braces in shell, by matching block delimiters, if...then...fi in Python, blocking is controlled by indentation

More information

Introduction to Python

Introduction to Python Introduction to Python خانه ریاضیات اصفهان فرزانه کاظمی زمستان 93 1 Why Python? Python is free. Python easy to lean and use. Reduce time and length of coding. Huge standard library Simple (Python code

More information