Lecture 24: print revisited, tuples cont.

Slides:



Advertisements
Similar presentations
Making Choices in C if/else statement logical operators break and continue statements switch statement the conditional operator.
Advertisements

Dictionaries: Keeping track of pairs
Lists CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Chubaka Producciones Presenta :.
2012 JANUARY Sun Mon Tue Wed Thu Fri Sat
MONDAYTUESDAYWEDNESDAYTHURSDAYFRIDAYSAT/SUN Note: You can print this template to use as a wall calendar. You can also copy the slide for any month to add.
2007 Monthly Calendar You can print this template to use it as a wall calendar, or you can copy the page for any month to add it to your own presentation.
More on Functions CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language.
CISC474 - JavaScript 03/02/2011. Some Background… Great JavaScript Guides: –
Lists CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Introduction to Computing Using Python Straight-line code  In chapter 2, code was “straight-line”; the Python statements in a file (or entered into the.
Lecture 21 - Tuples COMPSCI 101 Principles of Programming.
Lists CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
WORD JUMBLE. Months of the year Word in jumbled form e r r f b u y a Word in jumbled form e r r f b u y a february Click for the answer Next Question.
Introduction to Computing Using Python for loop / def- ining a new function  Execution control structures ( if, for, function call)  def -ining a new.
Exam 1 Review Instructor – Gokcen Cilingir Cpt S 111, Sections 6-7 (Sept 19, 2011) Washington State University.
DATE POWER 2 INCOME JANUARY 100member X 25.00P2, FEBRUARY 200member X 25.00P5, MARCH 400member X 25.00P10, APRIL 800member.
1 CSC 221: Introduction to Programming Fall 2011 Lists  lists as sequences  list operations +, *, len, indexing, slicing, for-in, in  example: dice.
Last Week Modules Save functions to a file, e.g., filename.py The file filename.py is a module We can use the functions in filename.py by importing it.
2011 Calendar Important Dates/Events/Homework. SunSatFriThursWedTuesMon January
I NTRODUCTION TO PYTHON - GETTING STARTED ( CONT )
July 2007 SundayMondayTuesdayWednesdayThursdayFridaySaturday
Python Files and Lists. Files  Chapter 9 actually introduces you to opening up files for reading  Chapter 14 has more on file I/O  Python can read.
 Python for-statements can be treated the same as for-each loops in Java Syntax: for variable in listOrstring: body statements Example) x = "string"
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 next week. See next slide. Both versions of assignment 3 are posted. Due today.
Quiz 4 Topics Aid sheet is supplied with quiz. Functions, loops, conditionals, lists – STILL. New topics: –Default and Keyword Arguments. –Sets. –Strings.
Lists/Dictionaries. What we are covering Data structure basics Lists Dictionaries Json.
Indentations makes the scope/block Function definition def print_message (): print “hello” Function usages print_message () hubo.move ()// hubo is a class.
CSc 120 Introduction to Computer Programing II Adapted from slides by
CSc 120 Introduction to Computer Programing II Adapted from slides by
Introduction to Python
Computer Programming Fundamentals
Containers and Lists CIS 40 – Introduction to Programming in Python
CSc 120 Introduction to Computer Programing II
An introduction to outlining in PowerPoint
Subroutines in Computer Programming
Dictation practice 2nd Form Ms. Micaela-Ms. Verónica.
TIMELINES PHOTOS This is an example text
TIMELINES PHOTOS This is an example text
McDonald’s Kalender 2009.
McDonald’s Kalender 2009.
Python Primer 2: Functions and Control Flow
Lecture 23: Tuples Adapted from slides by Marty Stepp and Stuart Reges
CSc 110, Autumn 2017 Lecture 27: Lists that change size and Tuples
CISC101 Reminders Assn 3 due tomorrow, 7pm.
McDonald’s Kalender 2009.
Lecture 23: Tuples Adapted from slides by Marty Stepp and Stuart Reges
2300 (11PM) September 21 Blue line is meridian..
5. Functions Rocky K. C. Chang 30 October 2018
CSc 110, Spring 2018 Lecture 5: Loop Figures and Constants
Java Classes and Objects
CMSC 202 Classes and Objects.
CSc 110, Spring 2018 Lecture 8: input and Parameters
McDonald’s calendar 2007.
G. Pullaiah College of Engineering and Technology
CISC101 Reminders All assignments are now posted.
Dictionaries: Keeping track of pairs
CHAPTER 4: Lists, Tuples and Dictionaries
CISC101 Reminders Assignment 3 due next Friday. Winter 2019
COMPUTER PROGRAMMING SKILLS
Adapted from slides by Marty Stepp and Stuart Reges
MONTHS OF THE YEAR January February April March June May July August
CISC101 Reminders Assignment 3 due today.
McDonald’s calendar 2007.
 A function is a named sequence of statement(s) that performs a computation. It contains  line of code(s) that are executed sequentially from top.
Habitat Changes and Fish Migration
2015 January February March April May June July August September
Habitat Changes and Fish Migration
Presentation transcript:

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

print

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)

print revisited Examples: >>> 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 "="

print revisited >>> alist = ['ab', 'cd', 'ef'] 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']

help

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

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

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'

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.

Using tuples Items are accessed via subscripting: t = ("Tucson", 90, 60) x_coord = t[1] You can loop through tuples the same as lists and strings operation cal result len() len((1, 2, 3)) 3 + (1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) * ('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 min() min((1, 3)) max() max((1, 3))

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)

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:

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:

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:

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?

Club solution 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: ")) 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)

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

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

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