Lecture 1



CSC 241 NotesYosef MendelsohnWith many thanks to Dr. Amber Settle for the original version of these notes.Prof Settle's notes in turn are based on the Perkovic text.Strings continued:Recall from an earlier discussion that proficiency in working with Strings is vital in many aspects of programming. Python has many built-in functions for manipulating strings. Assume that some variable 's' has been assigned a string value. The following are some useful string functions:s.count(target): Returns the number of occurrences of the substring target in ss.find(target): Returns the index of the first occurrence of the substring target in ss.lower(): Returns a copy of the string s converted to lowercases.upper(): Returns a copy of the string s converted to uppercases.isupper(): Returns True if the string is in upper cases.islower(): Returns True if the string is in lower cases.replace(old, new): Returns a copy of the string s in which every occurrence of substring old is replaced by news.split(sep): Returns a list of substrings of the string s, obtained using the delimiter string sep; the default delimiter is a spaceWe demonstrate a few of these below:>>> s = 'hello world'>>> s.find("world")6>>> s.replace("world", "universe")'hello universe'#Question: What would happen if #instead of the above line, we typed:# s = s.replace("world", "universe") >>> s'hello world'>>> s.split()['hello', 'world']>>> s'hello world'>>> s.upper()'HELLO WORLD'>>> s'hello world'>>> s.count('hell')1>>> s.count("o")2>>> s.count("low")0The method split is particularly useful for parsing a line text into a list of individual words. This kind of thing comes up surprisingly often in the real world. Exercises: Do the following CodeLab exercises in the Week 3 folder:517695177051767517665177151772Practice problem:Assign to a variable 'forecast' the string ‘It will be a sunny day today’ and then write Python statements to do the following:Assign to a variable count the number of occurrences of the string ‘day’ in forecastAssign to a variable weather the index where the substring ‘sunny’ startsAssign to a variable change a copy of forecast in which every occurrence of the substring ‘sunny’ is replaced by ‘cloudy’Solutions are listed in a function called forecast() in this week’s examples file.There are many more string functions available then are described here. See Table 4.1 on page 101 of the textbook for a partial listing. To see them all, remember the handy 'help' function discussed previously:>>> help(str)Help on class str in module builtins:class str(object) | str(string[, encoding[, errors]]) -> str | | Create a new string object from the given encoded string.…Numeric typesWe talked about numeric types (integer, floats, etc.) and some of their properties previously. We need to review some of the concepts we touched on again.Type conversionsIf an expression involves operands of numeric types, Python will convert each operand to the most “complex” type.Some examples are given below:>>> 3 + 0.253.25>>> a = 3>>> b = 0.25>>> c = a+b>>> type(c)<class 'float'>Type conversions can also be done explicitly.Again, consider some examples:>>> int(True)1>>> int(False)0>>> float(3)3.0 Operators and precedence rulesRecall: An expression is a combination of numbers (or other objects) and operators that is evaluated by the Python interpreter to some literal (i.e. a value).As a review, below is a list of common Python operators. All of the operators are shown in order of precedence from highest to lowest. For example, if in an expression you have a '+' and a '&', then the plus operator will be evaluated before the '&' because it has higher precedence. Precedence TableHighest precedence is at the top. OperatorDescription(expressions...), [expressions...], {key:datum...}, `expressions...`Binding or tuple display, list display, dictionary display, string conversionx[index], x[index:index], x(arguments...), x.attributeSubscription, slicing, call, attribute reference**Exponentiation [8]+x, -x, ~xPositive, negative, bitwise NOT*, /, //, %Multiplication, division, remainder+, -Addition and subtraction<<, >>Shifts&Bitwise AND^Bitwise XOR |Bitwise OR in, not in, is, is not, <, <=, >, >=, <>, !=, ==Comparisons, including membership tests and identity tests,not xBoolean NOTandBoolean ANDorBoolean ORlambdaLambda expressionExercise: Explain in what order the operators in the expressions below are evaluated:3+2*4Because the '*' has higher precedence than '+', we will first do the multiplication, followed by the addition.Not surprisingly, the precedence rules for mathematical operations in Python follow the standard precedence rules that you probably learned in high school math. (Parentheses > Exponents > multiplication/division > addition/substraction, etc)2*3**2Exponentiation (32)Multiplication (multiply the 9 from the previous step times 2)2+3 == 4 or a >= 5Addition== comparison>= comparison'or' operationNOTE: Note that >= and == have the same precedence. When this happens, the operator on the left-most side of the expression is evaluated first. Single, double, and triple quotesA string is represented as a sequence of characters that is enclosed within either double or single quotes. To construct a string that contains quotes, we can use the opposite type of quotes, e.g. using single quotes within double quotes or double quotes within single quotes.>>> excuse = 'I am "sick"'>>> excuse'I am "sick"'>>> fact = "I'm sick">>> fact"I'm sick"If text uses both type of quotes, then the escape sequence \’ or \” is used to indicate that a quote is not the string delimiter but is part of the string value.>>> excuse = 'I\'m "sick"'>>> excuse'I\'m "sick"'>>> print(excuse)I'm "sick"If we want to create a string that goes across multiple lines, we can use triple quotes.>>> quote = '''This poem isn't for youbut for meafter all.'''>>> quote"\nThis poem isn't for you\nbut for me\nafter all.\n">>> print (quote)This poem isn't for youbut for meafter all.Formatting String OutputRecall that you can output multiple items in the print function:The default separator between items printed using the print function is a blank space.print('hello', 'goodbye',45)Will output: hello goodbye 45>>> n = 5>>> r = 5/3>>> print(n,r)5 1.66666666667>>> name = 'Ada'>>> print(n, r, name)5 1.66666666667 AdaIf, when using the print function, we wish to use something other than a space, we can use the optional argument sep to indicate what the separator should be.For example, if we wanted to separate the items above with three forward slashes instead of a blank space, we would write:>>> print(n, r, name, sep='///')5///1.66666666667///AdaNormally successive calls to the function 'print' will output on a separate line:>>> for name in ['Marisa', 'Sam', 'Tom', 'Anne']:print(name)MarisaSamTomAnneThe print function also supports the optional argument end .When the argument end = <some string> is added to the arguments to be printed, the string <some string> is printed after each argument.>>> for name in ['Marisa', 'Sam', 'Tom', 'Anne']:print(name, end="! ") #Note the space after the '!' characterMarisa! Sam! Tom! Anne! sep v.s. end ‘sep’ is what you use to separate one item from the next inside the print() functionprint('hello', 'goodbye',45, sep=' ') will separate the 3 items by two spaces: hello Goodbye 45‘end’ will append to the end of each item:print('hello', 'goodbye',45, end='?') will append a question mark after each: hello? Goodbye? 45?Exercise: Use the help() function to see the help notes for the print() function:help(print)In particular, note the following:Some arguments are optional. That is, when you invoke this function, you are not required to provide those arguments unless you want to. Some arguments – typically the optional ones - have a default value. For example, the default value for the ‘end’ argument is a new line. The default value for the ‘sep’ argument is a space.String Formatting Methods There are many useful techniques for formatting output so that it appears in ways that are meaningful. The techniques for doing so take a little getting used to, but it is definitely worth getting to know the basics.We can exert some control over the apperance of output using the format() method.It can be a bit confusing to describe, so we won't spend much time doing so now. Instead, we will demonstrate with a few examples. Your textbook will, of course, give you plenty of detail to explain how it works. Briefly, the format() method is invoked by a string that represents the format of the output. The arguments to the format function are the objects to be printed.Study the examples below: def format_strings_practice(): fn1 = 'Bob' ln1 = 'Smith' fn2 = 'Lisa' ln2 = 'Chen' print( 'Your first name is {0}'.format(fn1) ) print('Your full name is: {1}, {0}.'.format(fn2, ln2))Outputs:Your first name is BobYour full name is: Chen, Lisa.>>> day = 25>>> month = 1>>> year = 2017>>> '{1}/{0}/{2}'.format(day, month, year)'1/25/2017'#Let’s format using the European system:>>> '{0}/{1}/{2}'.format(day, month, year)‘25/1/2017’Start by looking at the arguments to the format() method. In the above examples, there are 3 of them. These arguments can be referred to using {0} for the first argument (day), {1} for the second (month) and {2} for the third (year). Notice that we invoke the format() method using a string. However, inside that string, we can refer to any of the arguments using the braces: { and }. You can also use a call to the format method inside of a call to the print function.>>> weekday = "Wednesday">>> month = "January">>> day = 18>>> year = 2012>>> hour = 1>>> minute = 45>>> second = 33>>> print( '{}, {} {}, {} at {}:{}:{}'.format(weekday, month, day, year, hour, minute, second) )Wednesday, January 18, 2012 at 1:45:33You can line up data in columns. Let’s consider how to line up integers using the field width within the format string. We will discuss lining up non-integer values at a later point.>>> print('{}'.format(45))45>>> print('{:10d}'.format(45)) 45#the ‘d’ is needed...>>> print('{:20d}'.format(45)) 45>>> print('{:3d}'.format(45)) 45Decision structures reviewSometimes we need to perform alternative actions depending on the condition. We have already discussed using 'if'. For example: n = 14 if n < 0: print("n is negative") print('Goodbye')In the above example, if n is negative, we do something. If the condition is false, we simply skip the block. In the above example, the program would simply output 'Goodbye'. Sometimes, however, we may wish to do an action if the condition is false. n = 14 if n < 0: print("n is negative") else: print("n is not negative")More generally, the if-else statement has the following format:if <condition>:<yes body>else:<no body><yes body> is an indented fragment of code that is executed if <condition> evaluates to True.<no body> is an indented fragment of code that is executed if <condition> evaluates to False.To see the full functionality of how the if-else statement works, see the following function:def test2(n): if n < 0: print("n is negative") print("I like negative numbers.") else: print("n is not negative") print("Goodbye")Run the function using negative values (e.g. -4), positive values (e.g. 4). Also be sure to test using 0 – what happens there? Practice problem: Write a function checkHeat that takes one input argument, a temperature, and prints “It is hot!” if the temperature is 86 or more or “It is not hot” if the temperature is less than 86.>>> checkHeat(98)It is hot!>>> checkHeat (78)It is not hotSee the solution in this week's solutions file.Three-way (and more) decisionsThe most general form of an if statement allows for multi-way decisions.For example, consider the following (in the examples file):def test3(n): if n < 0: print("n is negative") elif n > 0: print("n is positive") else: print("n is 0")This code has three alternative executions depending on whether n is positive, negative, or 0, seen below:>>> test3(-4)n is negative>>> test3(0)n is 0>>> test3(4)n is positiveThe general form of an if statement is:if <condition1>:<body1>elif <condition2>:<body2>elif <condition3>:<body3>…else:<last body>Each condition has an associated body that is the block of code to be executed if the condition evaluates to True.Note that conditions do not have to be mutually exclusive, in which case the order in which they appear will make a difference.Consider checkHeat2:def checkHeat2(temp): if temp >= 86: print("It is hot") elif temp > 0: print("It is cool") else: print("It is freezing")The above program is correct because of the order in which conditions are evaluated in Python.Why would the version of the program below be incorrect? What value would produce unexpected results?def checkHeat2(temp): if temp > 0: print("It is cool") elif temp >= 86: print("It is hot") else: print("It is freezing")The 'else' block is optional. Sometimes you need an 'else' block, and sometimes you don't. As an example, suppose you evaluate the number of hours a person practiced their piano in a week. If they practiced more than 20 hours, you say "Wow, hard worker!". If they didn't, you decide not to say something critical, and choose instead not to say anything at all. So in this case, you would not include an 'else' block.hours_practiced = 14if hours_practiced > 20: print("Wow, hard worker!")Review: Branching practice problemWrite a function called checkLogin that asks a user to input a login id, a string, and then checks whether the login id input by the user is in the list [‘emily’, ‘nick’, ‘mark’, ‘julie’]. If so, your function should print “You’re in!”. Otherwise it should print “User unknown”. In both cases, your function should print “Done.” before terminating.>>> checkLogin()Enter login id: julieYou're in!Done.>>> checkLogin()Enter login id: yosefUser unknown.Done. ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download