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

Similar documents
Programming in Python 3

CSE 115. Introduction to Computer Science I

Introduction to Python! Lecture 2

EXAMINATIONS 2012 MID-YEAR NWEN 241 SYSTEMS PROGRAMMING. The examination contains 5 questions. You must answer ALL questions

Example. Section: PS 709 Examples of Calculations of Reduced Hours of Work Last Revised: February 2017 Last Reviewed: February 2017 Next Review:

CSC148 Fall 2017 Ramp Up Session Reference

Dictionaries. By- Neha Tyagi PGT CS KV 5 Jaipur II Shift Jaipur Region. Based on CBSE Curriculum Class -11. Neha Tyagi, KV 5 Jaipur II Shift

Data Structures. Lists, Tuples, Sets, Dictionaries

Strings, Lists, and Sequences

10/30/2010. Introduction to Control Statements. The if and if-else Statements (cont.) Principal forms: JAVA CONTROL STATEMENTS SELECTION STATEMENTS

Introduction to programming using Python

61A Lecture 2. Friday, August 28, 2015

Lecture 10: Boolean Expressions

Python for Non-programmers

CHIROPRACTIC MARKETING CENTER

Sequential Search (Searching Supplement: 1-2)

AIMMS Function Reference - Date Time Related Identifiers

FILE HANDLING AND EXCEPTIONS

Lecture 1: First Acquaintance with Python

CSc 120 Introduction to Computer Programing II Adapted from slides by Dr. Saumya Debray

Introduction to Computer Programming for Non-Majors

1 Strings (Review) CS151: Problem Solving and Programming

Marketing Opportunities

CIS192 Python Programming

Programming Logic and Design Sixth Edition

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

Fundamentals of Programming (Python) Getting Started with Programming

Student Number: Comments are not required except where indicated, although they may help us mark your answers.

LECTURE 4 Python Basics Part 3

CSE 115. Introduction to Computer Science I

Python and Bioinformatics. Pierre Parutto

Starting. Read: Chapter 1, Appendix B from textbook.

MAP OF OUR REGION. About

hereby recognizes that Timotej Verbovsek has successfully completed the web course 3D Analysis of Surfaces and Features Using ArcGIS 10

Getting Started with Python

ITT8060: Advanced Programming (in F#)

CIS192 Python Programming

CONDITIONAL EXECUTION: PART 2

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

Arrays. What if you have a 1000 line file? Arrays

Computer Science 217

Read and fill in this page now. Your instructional login (e.g., cs3-ab): Your lab section days and time: Name of the person sitting to your left:

Python Tutorial. Day 2

Introduction to Computer Programming for Non-Majors

CSc 120. Introduc/on to Computer Programing II. Adapted from slides by Dr. Saumya Debray. 01- a: Python review

Advanced Python. Executive Summary, Session 1

TREES Lecture 12 CS2110 Spring 2019

Collections. Lists, Tuples, Sets, Dictionaries

MAP OF OUR REGION. About

CPD for GCSE Computing: Practical Sheet 6 February 14

PLEASE HAND IN UNIVERSITY OF TORONTO Faculty of Arts and Science

HPE Secur & HPE Secur Cloud

Python for Non-programmers

COMPUTER SCIENCE 123. Foundations of Computer Science. 5. Strings

COMPUTER TRAINING CENTER

Basic Device Management

Arrays. Arrays (8.1) Arrays. One variable that can store a group of values of the same type. Storing a number of related values.

PYTHON. Values and Variables

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

Exceptions and File I/O

Student Number: Comments are not required except where indicated, although they may help us mark your answers.

Arrays, Strings, & Pointers

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

PLEASE HAND IN UNIVERSITY OF TORONTO Faculty of Arts and Science

Comp Exam 1 Overview.

Lecture 12 TREES II CS2110 Spring 2018

Dashboard. 16 Jun Jun 2009 Comparing to: 16 Jun Jun % Bounce Rate. 62,921 Visits. 407,003 Page Views

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

Introduction to Python

Python Tutorial Exercises with Answers

A Beginner s Guide to Programming Logic, Introductory. Chapter 6 Arrays

TUPLES AND RECURSIVE LISTS 5

02157 Functional Programming. Michael R. Ha. Disjoint Unions and Higher-order list functions. Michael R. Hansen

CIS192 Python Programming

Python. Executive Summary

Perceptive Enterprise Deployment Suite

Do not turn to the next page until the start of the exam.

44 Tricks with the 4mat Procedure

CSC 148 Lecture 3. Dynamic Typing, Scoping, and Namespaces. Recursion

MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY SATURDAY SUNDAY

EACH MONTH CUTTING EDGE PEER REVIEW RESEARCH ARTICLES ARE PUBLISHED

Software Testing. 1. Testing is the process of demonstrating that errors are not present.

02157 Functional Programming Tagged values and Higher-order list functions

Guernsey Post 2013/14. Quality of Service Report

Chapter 2. Python Programming for Physicists. Soon-Hyung Yook. March 31, Soon-Hyung Yook Chapter 2 March 31, / 52

Introduction to Python (All the Basic Stuff)

CONFERENCE ROOM SCHEDULER

Read and fill in this page now. Your lab section day and time: Name of the person sitting to your left: Name of the person sitting to your right:

Statements 2. a operator= b a = a operator b

CSC A20H3 S 2011 Test 1 Duration 90 minutes Aids allowed: none. Student Number:

More Lists, File Input, and Text Processing

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

Python Programming. Introduction Part II

Introduction To Python

Tutorial 8 (Array I)

Organizing and Summarizing Data

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

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

Outline. Simple types in Python Collections Processing collections Strings Tips. 1 On Python language. 2 How to use Python. 3 Syntax of Python

Student Number: Instructor: Brian Harrington

Transcription:

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. Definition of built-in function print: print(value,..., sep=' ', end='\n') Prints the values to the console. Optional keyword arguments: sep: string inserted between values, default a space. end: string appended after the last value, default a newline. Can use this instead: print("the sum is", sum) 3

print revisited Examples: >>> x = 10 >>> y = 20 >>> print(x, y) 10 20 >>> print("x =", x) x = 10 >>> print("x =", x, "y =", y) x = 10 y = 20 >>> print("x =", x, " and ", "y =", y) x = 10 and y = 20 >>> Note that the default value for the sep= option is providing the space after the "=" 4

print revisited This works for lists and tuples also: >>> alist = ['ab', 'cd', 'ef'] >>> print(alist) ['ab', 'cd', 'ef'] >>> t = ("Fundamental Algorithms", "Knuth", 1968) >>> print(t) ('Fundamental Algorithms', 'Knuth', 1968) >>> >>> print(x,y, alist) 10 20 ['ab', 'cd', 'ef'] We can use the sep= option to specify the separator: >>> print(x, y, alist, sep='--') 10--20--['ab', 'cd', 'ef'] 5

help 6

help help(): a function in Python that gives information on built-in functions and methods. Looking at documentation is a skill that programmers need to develop. You may not understand the documentation completely, but try it. >>> help(print) Help on built-in function print in module builtins: print(...) print(value,..., sep=' ', end='\n', file=sys.stdout, flush=false) Prints the values to a stream, or to sys.stdout by default. Optional keyword arguments: file: a file-like object (stream); defaults to the current sys.stdout. sep: string inserted between values, default a space. end: string appended after the last value, default a newline. flush: whether to forcibly flush the stream. >>> 7

help help(): for built-in methods, specify the type and method name using the dot notation. >>> help(str.split) Help on method_descriptor: split(...) S.split(sep=None, maxsplit=-1) -> list of strings Return a list of the words in S, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done. If sep is not specified or is None, any whitespace string is a separator and empty strings are removed from the result. >>> 8

Creating Tuples a note Syntax for creating a tuple: (value0, value1,,valuen) Example: ("Tucson", 90, 60) The parenthesis are optional. The comma is the tuple constructor: >>> t = "Tucson", 90, 60 >>> t ('Tucson', 90, 60) >>> t[0] 'Tucson' 9

Tuples This can lead to confusing bugs: >>> val = 40, >>> sum += val Traceback (most recent call last): File "<pyshell#58>", line 1, in <module> sum += val TypeError: unsupported operand type(s) for +=: 'int' and 'tuple' >>> If you get an unexpected type error, look for an unexpected comma. 10

Using tuples Items are accessed via subscripting: t = ("Tucson", 90, 60) x_coord = t[1] operation cal result len() len((1, 2, 3)) 3 + (1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) You can loop through tuples the same as lists and strings * ('Hi', 1) * 2 ('Hi', 1, 'Hi', 1) in 3 in (1, 2, 3) True for for x in (1,2,3): print(x) 1 2 3 min() min((1, 3)) 1 max() max((1, 3)) 3 11

Lists of tuples Given the list below: >>> all_months =[('january', 31),('february', 28), ('march',31), ('april', 30), ('may', 31),('june', 30), ('july', 31), ('august', 31), ('september', 30), ('october', 31), ('november', 30), ('december',31)] Write code for two different ways to print each tuple in all_months: 1) 2) 12

Lists of tuples Given the list below: >>> all_months =[('january', 31),('february', 28), ('march',31), ('april', 30), ('may', 31),('june', 30), ('july', 31), ('august', 31), ('september', 30), ('october', 31), ('november', 30), ('december',31)] 1) Write the code to print the days of all the tuples in all_months: 13

Club problem Write a program that maintains information about members of a club. The club maintains the name, the birthday month, and a count of attendance for each member. The membership file is kept in "members.txt" The program provides the user with the three options shown below. Select one of the following options: 1. Generate a birthday list: 2. Remove a member: 3. Update attendance: Select 1, 2, or 3: 14

Club problem If option 1 is selected, the program prompts the user for a birthday month and then writes the names of all users with that birthday month to a file called "birthdays.txt". If option 2 is selected, the program prompts for the name of the member to be removed and removes that member from membership list. If option 3 is selected, the program updates the attendance count for all members. The file "members.txt" is updated afterwards to reflect the changes made. Select one of the following options: 1. Generate a birthday file: 2. Remove a member: 3. Update attendance: Select 1, 2, or 3: 15

Club problem Assume that the user input will be correct (no error checking needed). The format of "members.txt" is shown below: mary october 31 sue april 46 tom march 52 kylie april 24 ben june 45 sally april 22 harry june 48 ann march 44 steve august 55 What data structure best suits this problem? 16

def main(): member_list = get_members("members.txt") print("select one of the following options:") print("1. Generate a birthday list:") print("2. Remove a member:") print("3. Update attendance:") n = int(input("select 1, 2, or 3: ")) Club solution if (n == 1): # generate birthday list file month = input("enter birthday month: ") generate_bdays(member_list, month.lower(), "birthdays.txt") elif (n == 2): # remove member name = input("enter name of member to remove: ") remove_member(member_list, name.lower()) else: # update attendance of all members update_attendance(member_list) update("members.txt", member_list) 17

Club solution # Read in the current members of a club from the file name given as # a parameter. Return a list of tuples containing # the name, birthday month, and days attended. def get_members(fname): f = open(fname) lines = f.readlines() members = [] #initialize the list for line in lines: info = line.split() name = info[0] bd_month = info[1] days_attended = info[2] members.append((name, bd_month, days_attended)) # add a tuple of info return members 18

Club solution Let's write the code for option 3: update attendance for each member. def update_attendance(mlist): 19

Club solution # Increment the attendance count of all members by one. def update_attendance(mlist): for i in range(0, len(mlist)): member = mlist[i] # get the ith member - a tuple # replace the ith element with a new tuple mlist[i] = (member[0], member[1], int(member[2]) + 1) return 20