Last Week if statement print statement input builtin function strings and methods for loop.

Slides:



Advertisements
Similar presentations
String and Lists Dr. Benito Mendoza. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list List.
Advertisements

Adapted from John Zelle’s Book Slides
Python Programming: An Introduction to Computer Science
C Language Elements (II) H&K Chapter 2 Instructor – Gokcen Cilingir Cpt S 121 (June 22, 2011) Washington State University.
Display a 12-Month Calendar CS-2301 D-term Programming Assignment #2 12-Month Calendar CS-2301 System Programming C-term 2009 (Slides include materials.
Introduction to Python
Basic Input/Output and Variables Ethan Cerami New York
Assignment #2, 12- month Calendar CS-2301, B-Term Programming Assignment #2 12-Month Calendar CS-2301, System Programming for Non-Majors (Slides.
Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language.
Last Week Doctests Lists List methods Nested Lists Aliasing.
COMPUTER SCIENCE FEBRUARY 2011 Lists in Python. Introduction to Lists Lists (aka arrays): an ordered set of elements  A compound data type, like strings.
Computer Science 111 Fundamentals of Programming I Number Systems.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
CS 127 Writing Simple Programs.  Stages involved  Analyze the problem  Understand as much as possible what is trying to be solved  Determine Specifications.
CS190/295 Programming in Python for Life Sciences: Lecture 3 Instructor: Xiaohui Xie University of California, Irvine.
Input, Output, and Processing
What is an Array? An array is a collection of variables. Arrays have three important properties: –group of related items(for example, temperature for.
Lecture 2: Introduction to C Programming. OBJECTIVES In this lecture you will learn:  To use simple input and output statements.  The fundamental data.
Chapter 3: Formatted Input/Output Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 3 Formatted Input/Output.
CHAPTER 7 arrays I NTRODUCTION T O C OMPUTER P ROGRAMMING (CSC425)
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Data Collections: Lists CSC 161: The Art of Programming Prof. Henry Kautz 11/2/2009.
CS161 Topic #16 1 Today in CS161 Lecture #16 Prepare for the Final Reviewing all Topics this term Variables If Statements Loops (do while, while, for)
C++ Lecture 1 Friday, 4 July History of C++ l Built on top of C l C was developed in early 70s from B and BCPL l Object oriented programming paradigm.
CSC1201: Programming Language 2 Lecture 1 Level 2 Course Nouf Aljaffan (C) CSC 1201 Course at KSU1.
Course A201: Introduction to Programming 09/30/2010.
More about Strings. String Formatting  So far we have used comma separators to print messages  This is fine until our messages become quite complex:
9/21/2015BCHB Edwards Python Data Structures: Lists BCHB Lecture 6.
C Programming – Part 3 Arrays and Strings.  Collection of variables of the same type  Individual array elements are identified by an integer index 
1 CSC 221: Introduction to Programming Fall 2011 Lists  lists as sequences  list operations +, *, len, indexing, slicing, for-in, in  example: dice.
Loops & List Intro2CS – week 3 1. Loops -- Motivation Sometimes we want to repeat a certain set of instructions more than once. The number of repetitions.
Introduction to Python Dr. José M. Reyes Álamo. 2 Three Rules of Programming Rule 1: Think before you program Rule 2: A program is a human-readable set.
Jim Havrilla. Invoking Python Just type “python –m script.py [arg]” or “python –c command [arg]” To exit, quit() or Control-D is used To just use the.
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.
2. WRITING SIMPLE PROGRAMS Rocky K. C. Chang September 10, 2015 (Adapted from John Zelle’s slides)
Python Mini-Course University of Oklahoma Department of Psychology Day 3 – Lesson 11 Using strings and sequences 5/02/09 Python Mini-Course: Day 3 – Lesson.
Data Types and Conversions, Input from the Keyboard CS303E: Elements of Computers and Programming.
UniMAP Sem2-10/11 DKT121: Fundamental of Computer Programming1 Arrays.
Midterm Review Important control structures Functions Loops Conditionals Important things to review Binary Boolean operators (and, or, not) Libraries (import.
Data Types and Conversions, Input from the Keyboard If you can't write it down in English, you can't code it. -- Peter Halpern If you lie to the computer,
Midterm Exam Topics (Prof. Chang's section) CMSC 201.
C++ Programming Lecture 14 Arrays – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Loops and Simple Functions COSC Review: While Loops Typically used when the number of times the loop will execute is indefinite Typically used when.
Sudeshna Sarkar, IIT Kharagpur 1 Programming and Data Structure Sudeshna Sarkar Lecture 3.
Python Strings. String  A String is a sequence of characters  Access characters one at a time with a bracket operator and an offset index >>> fruit.
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.
Lecture 14 – lists, for in loops to iterate through the elements of a list COMPSCI 1 1 Principles of Programming.
 Python for-statements can be treated the same as for-each loops in Java Syntax: for variable in listOrstring: body statements Example) x = "string"
Chapter 3: Formatted Input/Output 1 Chapter 3 Formatted Input/Output.
Quiz 3 Topics Functions – using and writing. Lists: –operators used with lists. –keywords used with lists. –BIF’s used with lists. –list methods. Loops.
String and Lists Dr. José M. Reyes Álamo. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list.
KUKUM-06/07 EKT120: Computer Programming 1 Week 6 Arrays-Part 1.
Introduction to Python Lesson 2a Print and Types.
Data Types and Conversions, Input from the Keyboard
CSC 108H: Introduction to Computer Programming
Arrays We often want to organize objects or primitive data in a way that makes them easy to access and change. An array is simple but powerful way to.
EKT150 : Computer Programming
CISC101 Reminders Assn 3 due tomorrow, 7pm.
String and Lists Dr. José M. Reyes Álamo.
Python Data Structures: Lists
Introduction to Strings
Python Basics with Jupyter Notebook
Python Data Structures: Lists
Arrays Arrays A few types Structures of related data items
Python Data Structures: Lists
COMPUTER PROGRAMMING SKILLS
Data Types Every variable has a given data type. The most common data types are: String - Text made up of numbers, letters and characters. Integer - Whole.
CISC101 Reminders Assignment 3 due today.
Class code for pythonroom.com cchsp2cs
Presentation transcript:

Last Week if statement print statement input builtin function strings and methods for loop

This Week Practice with string methods and for loops Doctests Conversion specifiers New type list –methods –Nested lists –Looping through a list –Looping using range

Doctests Why do we use an example in our docstrings? –To show the user how to call our function –To ensure our function works properly We can test our function by using the doctest module.

Docstrings import doctest def count_spaces(s): ‘’’(str) -> int Return the number of spaces in s as an int. >>>count_spaces(‘’) 0 >>>count_spaces(‘ ‘) 1 >>>count_spaces(‘there are several spaces here.’) 4 ’’’

Doctests def count_spaces(s): count = 0 for char in s: if char == ‘ ‘: count += 1 return count if __name__ == ‘__main__’: doctest.testmod() # or for more details use doctest.testmod(verbose=True) What do these do? Let’s try it!

Visiting the Items in a String S Printing out the characters of the string English: for each char in S print the char Python: for char in S: print(char) Notes: char is a variable name for and in are Python key words

for loops Format: for variable in string: statements Example with strings: name = ”Edward” new = “” for letter in name: new = letter + new print(new)

Strings Using Conversion Specifiers We sometimes would like to insert values of variables into strings: A1 = 60 A2 = 75 A3 = 88 We would like: ‘The average of 60, 75 and 88 is ’ How do we print this with our variables? >>>print(‘The average of’, A1, ‘,’, A2, ‘ and ’, A3, ‘ is ’, (A1+A2+A3)/3) Does this work?

Strings Using Conversion Specifiers We displayed: ‘The average of 60, 75 and 88 is ’ Q. What’s wrong? A. Spacing is wrong around commas and periods. We have many more decimal places than wanted. Q. How can we fix it? A. Use conversion specifiers. >>>print(‘The average of %d, %d and %d is %.2f’ %(A1, A2, A3, (A1+A2+A3)/3.0)) The average of 60, 75 and 88 is

Common Conversion Specifiers %d display the object as a decimal integer %fdisplay the object as a floating point with 6 decimal places %.2fdisplay the object as a floating point with 2 decimal places %sdisplay the object as a string Q. What else do we use % for? A. Modulus. We say that % is overloaded.

Way to store many variables, e.g., students = [“Abby”, “Bob”, “Harry”, “Sara”, “Don”] grades_list = [85, 80, 82, 84, 83] misc = [“Kaya”, 2006, “July”, 20, True] students[0] = ? students[3] = ? grades_list[2] = ? grades_list[5] = ? Lists “Abby” “Sara” 82 error

Lists cont… grades_list = [85, 80, 82, 84, 83] grades_list[2] = 86 grades_list.append(90) grades_list == ?? Functions len(grades_list) outputs… max(grades_list) outputs… min(grades_list) outputs… sum(grades_list) outputs… [85, 80, 86, 84, 83, 90] work for strings too

students = [“Abby”, “Bob”, “Harris”, “Sara”, “Don”] students.sort() [“Abby”, “Bob”, “Don”, “Sara”, “Harris”] students.insert(2, “Charlie”) [“Abby”, “Bob”, “Charlie”, “Don”, “Sara”, “Harris”] students.append(“Kaya”) has the same result as students.insert( ????, “Kaya”) Lists -- Methods student.insert(len(students), “Kaya”)

student_grades = [[‘ ’, 72], [‘ ’, 90], [[‘ ’, 84]] student_grades[0] == student_grades[0][0] == student_grades[1][0] == student_grades[2][1] == Nested Lists -- Lists of Lists list [‘ ’,72] ‘ ’ ‘ ’ 84 ??

Slicing Lists or Strings Idea: Grab part of a list aka a slice of a list. countries = [‘Canada’, ‘France’, ‘China’, ‘Italy’, ‘India’] countries[0:2] == countries[3:] == countries[:4] == countries[s:t] means: start at index s include all list items up to but not including item t. [‘Canada’, ‘France’, ‘China’, ‘Italy’] ?? [‘Italy’, ‘India’]?? [‘Canada’, ‘France’] ??

Visiting the Items in a List L Printing out the list English: for each item in L print the item Python: for item in L: print(item)

For Loops -- Revisited Want to print the numbers from for num in [0, 1, 2, 3, 4, …, 99, 100]: print(num) Is there an easier way to do this? for num in range(0, 101): print(num) range(start, stop[,step]) returns a list of integers beginning with start to the last integer before stop. start can be omitted and defaults to 0 step can be omitted and defaults to 1

For Loops -- Revisited L1 = [1, 2, 3, 4] L2 = [‘A’, ‘B’, ‘C’, ‘D’] Want to print each element from L1 followed by the corresponding element from L2. for num in L1: print(num, ??) # How do we print the item from L2? Loop over indices: for index in range(len(L2)): print(L1[index], L2[index])