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