Strings and Testing string methods, formatting testing approaches CS GMU

Similar documents
Getting Started Values, Expressions, and Statements CS GMU

CS 115 Lecture 4. More Python; testing software. Neil Moore

Python for Non-programmers

CS 115 Data Types and Arithmetic; Testing. Taken from notes by Dr. Neil Moore

Introduction to: Computers & Programming: Review prior to 1 st Midterm

age = 23 age = age + 1 data types Integers Floating-point numbers Strings Booleans loosely typed age = In my 20s

Overview of List Syntax

Basic Concepts. Computer Science. Programming history Algorithms Pseudo code. Computer - Science Andrew Case 2

Intro. Scheme Basics. scm> 5 5. scm>

CSCA20 Worksheet Strings

Lecture 9: July 14, How to Think About Debugging

Student Number: Instructor: Brian Harrington

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

Python Intro GIS Week 1. Jake K. Carr

Lecture 3. Input, Output and Data Types

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

Selection statements. CSE 1310 Introduction to Computers and Programming Alexandra Stefan University of Texas at Arlington

DEBUGGING TIPS. 1 Introduction COMPUTER SCIENCE 61A

CMSC 201 Fall 2016 Lab 09 Advanced Debugging

ECE 364 Software Engineering Tools Lab. Lecture 3 Python: Introduction

CS1114 Spring 2015 Test ONE ANSWER KEY. page 1 of 8 pages (counting the cover sheet)

Syntax and Variables

Python allows variables to hold string values, just like any other type (Boolean, int, float). So, the following assignment statements are valid:

MITOCW watch?v=rvrkt-jxvko

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

A First Look at ML. Chapter Five Modern Programming Languages, 2nd ed. 1

CS 106 Introduction to Computer Science I

Working with Strings. Husni. "The Practice of Computing Using Python", Punch & Enbody, Copyright 2013 Pearson Education, Inc.

06/11/2014. Subjects. CS Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / ) Beginning with Python

THE AUSTRALIAN NATIONAL UNIVERSITY Mid Semester Examination September COMP1730 / COMP6730 Programming for Scientists

Strings are actually 'objects' Strings

Sequence of Characters. Non-printing Characters. And Then There Is """ """ Subset of UTF-8. String Representation 6/5/2018.

Python Day 3 11/28/16

1. What is the minimum number of bits needed to store a single piece of data representing: a. An integer between 0 and 100?

Comp Exam 1 Overview.

CS 1301 Exam 1 Fall 2010

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

CS 115 Lecture 8. Selection: the if statement. Neil Moore

Text Input and Conditionals

CSC148 Fall 2017 Ramp Up Session Reference

Professor: Sana Odeh Lecture 3 Python 3.1 Variables, Primitive Data Types & arithmetic operators

Python Review IPRE

Python Working with files. May 4, 2017

Chapter 2 Working with Data Types and Operators

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

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

Introduction to Python Programming

Lists How lists are like strings

Python The way of a program. Srinidhi H Asst Professor Dept of CSE, MSRIT

COMP1730/COMP6730 Programming for Scientists. Data: Values, types and expressions.

printf( Please enter another number: ); scanf( %d, &num2);

Python Programming: Lecture 2 Data Types

Programming in Python 3

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

URLs and web servers. Server side basics. URLs and web servers (cont.) URLs and web servers (cont.) Usually when you type a URL in your browser:

SSEA Computer Science: Track A. Dr. Cynthia Lee Lecturer in Computer Science Stanford

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 3: SEP. 13TH INSTRUCTOR: JIAYIN WANG

TESTING, DEBUGGING, EXCEPTIONS, ASSERTIONS

Full file at

Getting started with Java

UNIVERSITY OF TORONTO SCARBOROUGH. Wnter 2016 EXAMINATIONS. CSC A20H Duration 2 hours 45 mins. No Aids Allowed

CS1 Lecture 3 Jan. 18, 2019

CS 1301 Exam 1 Answers Fall 2009

6.096 Introduction to C++

Babu Madhav Institute of Information Technology, UTU 2015

Have examined process Creating program Have developed program Written in C Source code

COMP1730/COMP6730 Programming for Scientists. Testing and Debugging.

Algorithms and Programming I. Lecture#12 Spring 2015

Chapter Two PROGRAMMING WITH NUMBERS AND STRINGS

Excel 2010 Functions. 4/18/2011 Archdiocese of Chicago Mike Riley

2. You are required to enter a password of up to 100 characters. The characters must be lower ASCII, printing characters.

There are two ways to use the python interpreter: interactive mode and script mode. (a) open a terminal shell (terminal emulator in Applications Menu)

CS1 Lecture 3 Jan. 22, 2018

Variables, expressions and statements

Topic 6: A Quick Intro To C

Python Review IPRE

7. (2 pts) str( str( b ) ) str '4' will not compile (single, double, or triple quotes

UTORid: Lecture Section: (circle one): L0101 (MWF10) L0201 (MWF11) Instructor: Jacqueline Smith Jen Campbell

Lecture 1. Types, Expressions, & Variables

The Practice of Computing Using PYTHON. Chapter 4. Working with Strings. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Python Unit

VARIABLES. Aim Understanding how computer programs store values, and how they are accessed and used in computer programs.

DaMPL. Language Reference Manual. Henrique Grando

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG

Python: common syntax

Pointers (continued), arrays and strings

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes

CS16 Exam #1 7/17/ Minutes 100 Points total

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

Basic Scripting, Syntax, and Data Types in Python. Mteor 227 Fall 2017

Beyond Blocks: Python Session #1

Introduction to computers and Python. Matthieu Choplin

Iteration. # a and b are now equal # a and b are no longer equal Multiple assignment

Worksheet 6: Basic Methods Methods The Format Method Formatting Floats Formatting Different Types Formatting Keywords

CS 2316 Exam 1 Spring 2014

CS 1110, LAB 3: MODULES AND TESTING First Name: Last Name: NetID:

Expressions, Statements, Variables, Assignments, Types

Scripting Languages. Python basics

Server side basics CS380

C++ Basics. Lecture 2 COP 3014 Spring January 8, 2018

Transcription:

Strings and Testing string methods, formatting testing approaches CS 112 @ GMU

Topics string methods string formatting testing, unit testing 2

Some String Methods (See LIB 4.7.1) usage: stringexpr. methodname ( args ) method purpose returned value s.upper() s.lower() s.startswith(svar[,start[,stop]]) s.endswith(svar[,start[,stop]]) s.join(iterable) s.split(sep) s.replace(old, new[,count]) converts letters to upper or lower case is svar a prefix/suffix of s? concatenates items from iterable, with copies of string s inbetween them. get list of strings obtained by splitting s into parts at each occurrence of sep. replace all (or count) occurrences of old str with new str. modified copy of s bool string result of all those joined things list of strings from between occurrences of sep string with replacements performed 3

Useful Tip: printing without a newline print() specializations end= : choose what print() adds at the end; default: "\n" sep= " choose what's printed between arguments; default: " " you have a lot of control over printing! print("a",end='') print('b c', end='') print("d") ab cd 1.2.3!4-->5-->6 print(1,2,3,sep='.', end='!') print(4,5,6,sep='-->')

Formatting Strings Brief introductions here, but also read the documentation. Three approaches: percent operator, % LIB 4.7.2 ZY 3.7 format method LIB 6.1.3 ZY 7.5 f-strings new as of Python 3.6

String Formatting: % operator describe pattern of string with placeholders, then supply all substitutions at once. Syntax: pattern_string % tuple Semantics: simplify lefthand string to value left to right, match placeholders in string with values from tuple substitutions obey special formatting directives 6

String Formatting: % operator placeholder style of output accepted input %d integer integers, floats %f float integers, floats %g float (scientific notation) %s string anything (calls str() ) integers, floats but it prefers scientific notation representation %% the '%' character none just represents the % symbol <more> don't memorize these: %i, %o, %u, %x, %X, %e, %E, %c, %r "there are %d days until %s." % (75, "holiday") "%s ran %f miles today" % ("Zeke", 3.5) "change is %d dollars and %d cents." % (4,39) "you got %f%% of them, %s." % (0.95*100, "George") "%s's number is %g/mol." % ("Avogadro",6.02214e23) 7

More Options purpose examples results state exact # columns after decimal point (%f) state min. # columns for entire thing "%.2f" % (2/3) "%.0f" % 15.5 "%4d" % 30 "%3d" % 1234 "%5f" % 2.5 '0.67' '16' ' 30' '1234' ' 2.5' use leading sign (+/-) "%+f" % 5 '+5.000000'

POLL 5A String formatting

The format( ) method A powerful option to craft a string is the format method. use { }'s as placeholders, put style rules inside examples: "{}" "{:4.2f}" "{:^5}" provide substitutions as arguments to.format() method See more examples: LIB 6.1.3.2

More options Again, indicate min # cols and exact # cols after the decimal. "{:10.2}".format(0.123) ' 0.12' Show as percent: "{:%}".format(0.12) Align left/center/right: "{:>6}".format("hi") "{:<6}".format("hi") "{:^6}".format("hi") "{:.^6}".format("hi") "{:o^6}".format("hi") '12.000000%' ' hi' 'hi ' ' hi ' '..hi..' 'oohioo'

New! f-strings special version of string literals with embedded expressions indicated with leading f in front of open-quote. name = "George" age = 67 print( f"happy {age}th birthday, {name}!")

Some corner cases of f-strings you can call functions and methods: f"{len(name)} letters long" f"{name.upper()}!" watch out for clashing quote styles! (can't \escape them inside the {}'s) f"{1+3} years" f"{int('1')+3} years" f"{int(\"1\")+3} years" FORBIDDEN

Testing Code

Notes on Debugging and Testing We basically never write 100% correct code on our first try How can we debug our code? (identify the problem) how can we thoroughly test it? (check for correct behavior) Debugging code is essentially a careful analysis of all the assumptions about our code, to find the assumption that is false. Examples: I assume I used correct syntax. I assume I modified the correct variable. I assume the list (or some index) exists before I use it I assume this print statement happens each iteration I assume I'm editing the same file I'm running!

Locating the Syntax Error line # 1 print("hello!") code 2 n = int(input("please enter a number: ") 3 if n>0: 4 print("number is "+str(n)) 5 else: 6 print("number was negative.") demo$ python3 syntax_error.py File "syntax_error.py", line 3 if n>0: ^ SyntaxError: invalid syntax Getting a syntax error on a "perfect" line of code? Look up to the previous line(s). You're likely missing a parenthesis, colon, or something else. the indicated location is merely where Python got when it realized something was wrong.

print-style debugging runtime error: some value/variable can't be used that way. Did we build it wrong, or use it wrong? print out relevant variables/expressions just before the offending operation occurs. Pros: access variables at the confusing portion of the code. Flexible, easy to include. Cons: need to be removed before code is ready to publish. Can introduce their own errors! When overused, hard to tell what program is doing versus what debugging print statements are doing.

Drawing Out Memory Run the code by hand or by using the visualizer. preserve and identify aliases check with id() calls updates vs. re-assignments make sure you perform the actions that are indicated, not just what you think should happen! seek where your expectations and actual performance diverge. Did we forget to handle this situation, or are we handling it incorrectly?

Testing Approaches Unit Testing for the smallest parts of code you can manage, write tests that test this piece of code. programmers often create large batches of unit tests that can be rerun as desired this is called "regression testing". all our testing files do this! J standardized ways of creating these exist but tend to use classes and objects topics we haven't learned yet.

Two Testing Styles Black box testing "outsider's expectations". given a piece of code, think about what it is supposed to do, and create test cases that give specific inputs and look for the expected outputs/behavior (including tests that you expect to fail!) White box testing "code coverage." Looking at the actual structure of your code, think of test cases that should use/'touch' each part of the code, to make sure each part of the code works when used.

Practice Problem This code is riddled with various kinds of errors! copy it from: http://cs.gmu.edu/~marks/112/examples/buggy.py debug the code until it gets correct values. choose blackbox test cases. choose white box test cases. def prime(n): is_prime = True for d in range(2,sqrt(n)) if d%n==0: is_prime = False else: is_prime = True return is_prime