25

Click here to load reader

Lecture 1 - condor.depaul.educondor.depaul.edu/ymendels/401/l3.docx  · Web viewFollowing the def command is the . ... Programs typically consist of a sequence of statements that

  • Upload
    dokhanh

  • View
    215

  • Download
    2

Embed Size (px)

Citation preview

Page 1: Lecture 1 - condor.depaul.educondor.depaul.edu/ymendels/401/l3.docx  · Web viewFollowing the def command is the . ... Programs typically consist of a sequence of statements that

CSC 401 NOTESLECTURE #3

Yosef Mendelsohn

NOTE: Many of the examples shown in this lecture can be found in the PY file that has the week indicated in the filename. This file can be found on the class web page. For example, to find code examples and exercises from week 3, look for a file named something like: examples_week3.py

FunctionsA mathematical function takes an input (say x) and produces some output (say x+1):

f(x) = x+5

To compute the value of the function for input 3, we write f(3) to obtain 8.

Functions in Python are similar.

We have already seen several functions in action such as len(), print(), append(), etc. We say that these functions are “built-in” or "predefined".

For example, the function len() takes a string or list as input and returns the length of the string or list.

The function print() takes a string prints it to the screen.

The function some_list.append() takes an argument and appends that value to the list 'some_list'.

Another built-in function is min() . This function that takes multiple inputs and returns the smallest.

See the example below:

>>> min(2,5)2

>>> min(2, -4, 5)-4

As mentioned, the above functions are “built-in” to Python. We sometimes call these “predefined” functions.

Based on notes by Ljubomir Perković Page 1

Page 2: Lecture 1 - condor.depaul.educondor.depaul.edu/ymendels/401/l3.docx  · Web viewFollowing the def command is the . ... Programs typically consist of a sequence of statements that

But what if we want to create our own functions?

Let’s take the example above that adds 5 to a number shown earlier:f(x) = x+5

and create a function in Python that will do the same thing. Here is the code to do so:

def add5(x):return x+5

In general, a function that we define in Python begins with the keyword ‘def’.

A Python ‘def’ statement has the following format:

def <function name> (<0 or more parameters>):<iterated statements># one or more Python statements,# all statements have a tab in front of them

All functions that we create will adhere to the following pattern: The def keyword is used to define a function. Following the def command is the identifier of the function. (In

the case above the name of the function is ‘add5’). Following the identifier is a set of parentheses containing 0, 1, or

more input arguments. (In the case above we have one argument, 'x').

A colon is placed at the end of the first line. We sometimes call this line the function "header" or “signature”.

Below the def statement and indented with a tab is the “implementation” of the function, i.e. the Python code that does the work.

This indentation is absolutely required. Python notes the beginning and end of the function by looking at this indentation.

As we will see, Python uses indentation in many, many situations in order to determine the beginning and end of a section.

The return statement is optional. Some functions will need a return statement. Other functions will not. It depends on what the function is supposed to do. If you want the function to return a piece of information, then you will need a return statement. In the example above, we wish the function to return the value of x with 5 added on. Therefore, we will need to include a return statement.

Examples:

2

Page 3: Lecture 1 - condor.depaul.educondor.depaul.edu/ymendels/401/l3.docx  · Web viewFollowing the def command is the . ... Programs typically consist of a sequence of statements that

Write a function that takes 3 numbers as a parameter and returns the sum of those numbers:

def addThreeNumbers(n1, n2, n3):sum = n1+n2+n3return sum

Exercise:Write a function that takes 3 numbers and returns (not outputs) the average of those numbers. Call the function average_3_nums.

Exercise:Write a function that takes a list of numbers as a parameter and returns the average of the numbers in the list. Call it average_of_list.

Hints: If you have a list called 'my_list', then you can get the sum of the list

using Python's built-in function 'sum()' e.g. sum(my_list) Recall that you can obtain the length of a list using the built-in

function 'len()' e.g. len(my_list)

Thought Question:What would happen if the list was empty?How do we fix this?

A common mistake when writing functionsA common mistake for beginners writing functions is to use print instead of return

For example, if we define the function f above as:

def add5(x):print(x+5)

then the function ‘add5’ will print x+5 on input x, but when used in an expression, it will not evaluate to it.

See the sample runs below to see what is meant by this:

>>> def add5(x):print(x+1)

>>> add5(3)4

3

Page 4: Lecture 1 - condor.depaul.educondor.depaul.edu/ymendels/401/l3.docx  · Web viewFollowing the def command is the . ... Programs typically consist of a sequence of statements that

>>> 3* add5(2)+13Traceback (most recent call last): File "<pyshell#49>", line 1, in <module> 3* add5(2)+1TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'

When evaluating add5(3), the Python interpreter evaluates add5(3) which will print 4 but does not evaluate to anything.

The second example makes this clear. The Python interpreter will print 3 when evaluating add5(2), but add5(2) does not evaluate to anything and so cannot be used in an expression.

Exercise: Does the print() function return anything?

Answer: The best way to check is to use an assignment statement so that the value returned by print gets a name:

>>> x = print("Hello!")Hello!

>>> x>>>

We can see above that x does not have a value, meaning that the print() function does not return anything.

Another important reason for avoiding the use of print() functions is that they are often not needed – or even desired! Recall that the print() function simply outputs textual information to the standard output device (usually a computer monitor). However, in most “real world” programming, our functions may do all kinds of things that in no way require textual information to be displayed.

As programmers we will indeed use print() a lot. However, this is really just to test our code and confirm that things are working as we are proceeding with our work. But the “published product” should have few (and often NO) print() functions present!

Decision structuresPrograms typically consist of a sequence of statements that the Python interpreter executes in order.

4

Page 5: Lecture 1 - condor.depaul.educondor.depaul.edu/ymendels/401/l3.docx  · Web viewFollowing the def command is the . ... Programs typically consist of a sequence of statements that

However, some alternative actions may need to be done based on some test. That is, we may have chunks of code that should be executed in certain situations, but should be skipped in other situations.

One-way decisionsThe ‘if’ statement is perhaps the most fundamental way that the Python interpreter can select which action to perform. The if statement is always based on a test. This test is a question that evaluates to a boolean result. If the result is 'True', the interpreter evaluates the block immediately following the 'if' statement. If the result evaluates to 'False', the interpreter does not evaluate the block.

Example: The following tests whether the input argument is less than 0. If it is, it prints a message that the argument is negative. Otherwise, nothing happens.

if n < 0:print(‘n is negative’)print('This means it is less than 0')

#Note that we are no longer indented#This means we are no longer inside the 'if' block

print('goodbye') #gets executed regardless of the if #block is T or F

The if statement in its simplest form, has the following structure:

if <condition>:<body>

<condition> is a Boolean expression, i.e. an expression that evaluates to True or False.

Some examples of such conditions include: if n < 0: if age >= 86: if name == 'Smith': if 34 in some_list:

<body> consists of one or more statements that are executed if the condition evaluates to True . If the condition evaluates to False, then <body> will be skipped.

Important: As with functions, note how the statements inside the ‘if’ block must be indented.

5

Page 6: Lecture 1 - condor.depaul.educondor.depaul.edu/ymendels/401/l3.docx  · Web viewFollowing the def command is the . ... Programs typically consist of a sequence of statements that

if <condition>:body statement 1body statement 2…last body statement

rest of the program continues ...

Draw a flow chart for the if statement.

Consider the following example program:

n=42

if n < 0: print("n is negative") print("These indented statements are part") print("of the if statement body") print("Still in the body...")

print("In the body no more")print("I am executed whether or not the condition")print("evaluates to True.")

Try sample runs on: Positive values (e.g. 4) Negative values (e.g. -4) n=0

The following is another example:

secret="Djengo"

guess = input("Enter the secret word: ") if guess==secret: print("You got it!!") print("Goodbye...")

Exercise: Modify this code to become a function that takes 0 parameters. Call it guess_secret_word()

Exercise: Modify the list function from our earlier exercise to check for an empty list and return 0.0 if the list is empty. Call this function average_of_list_v2.

Iteration structuresSometimes a program needs to repeat a block of code multiple times.

6

Page 7: Lecture 1 - condor.depaul.educondor.depaul.edu/ymendels/401/l3.docx  · Web viewFollowing the def command is the . ... Programs typically consist of a sequence of statements that

For example, the program may need to iterate through a list or some other collection of objects and run a block of code on the objects in the list.

A block code that repeats a number of times is typically called a loop.

As an example, consider the following:

lst_animals = ['cat', 'dog', 'chicken']for i in lst_animals:

print (animal)

OUTPUT: catdogchicken

Consider another example (for.py):

some_list = [67, 34, 98, 63, 23]

for i in some_list: print(i)

This code produces this output when run:>>> 6734986323

An aside:You might note that the in the examples above, the identifier ‘i' is not very clear.

And… you’d be 100% correct. However, when iterating through a loop, programmers frequently use a simple identifier such as ‘i' or 'j' or 'x'. Sometimes it is fine to do this.

But in some cases, your code can be much more clear (and remember, we really like clear!) by using an identifier that reflects each item in the iteration. For example:

>>> lst_animals = ['cat', 'dog', 'chicken']

>>> for item in lst_animals:

7

Page 8: Lecture 1 - condor.depaul.educondor.depaul.edu/ymendels/401/l3.docx  · Web viewFollowing the def command is the . ... Programs typically consist of a sequence of statements that

print (item)

I think the following is even better:

>>> lst_animals = ['cat', 'dog', 'chicken']

>>> for animal in lst_animals:print (animal)

Similarly, for our list of numbers, we might do something like:

some_list = [67, 34, 98, 63, 23]

for num in some_list: print(num)

It all depends on context – and very often, simple identifiers such as 'i' is just fine. But in general, having clear identifiers is quite nice.

If we’re iterating through say, a list of something where the values are not obvious (e.g. a list of meaningless numbers), then an identifier such as ‘i' is fine.

Exercise: Write a function called count_characters that accepts a list of strings. The function will count all of the characters in every string in the list, and will return that value. For example:

list_of_strings = ["hello","how are you?", "all is good, thank you very much"]

print( count_characters(list_of_strings) )# will output 49

As always, the solution can be found in this week's solutions file.

Note on the ‘in’ operator: Recall that the + operator can do two different operations based on context (add v.s. concatenation). Similarly, the ‘in’ operator can do different things as well. This ‘in’ operator can either be used to iterate through a list (e.g. if inside a ‘for’ loop), or it can be used as a boolean operator (e.g. when used inside a conditional to evaluate if an item is present in a list).

The range functionSometimes we want to iterate over a sequence of numbers in a certain range, rather than an explicit list.

For example, suppose we wanted to print all values between 0 and 9:

8

Page 9: Lecture 1 - condor.depaul.educondor.depaul.edu/ymendels/401/l3.docx  · Web viewFollowing the def command is the . ... Programs typically consist of a sequence of statements that

for i in range(10):print(i, end=" ")

OUTPUTS: 0 1 2 3 4 5 6 7 8 9

Here is how the range() function works:1. If it is passed only 1 argument, it returns all values from 0 to the

argument. Note that it is non-inclusive of the second argument. Eg: range(3) returns 0, 1, 2.

2. It it is passed 2 arguments, it returns all values from the first argument to the second argument (again, non-inclusive of the second argument). For example: range(1,5) returns 1,2,3,4.

3. It is is passed a 3rd argument, it returns from the first argument to the second argument (non-inclusive) jumping in increments of the 3rd argument. For example: range(5, 15, 3) returns 5, 8, 11, 14

Try the following using a for loop as demonstrated above:a. From 0 to 1, i.e. 0, 1b. From 3 to 12, i.e. 3, 4, 5, 6, 7, 8, 9, 10, 11, 12c. From 0 to 8, but with a step of 2, i.e. 0, 2, 4, 6, 8d. From 0 to 24 with a step of 3, i.e. 0, 3, 6, 9, 12, 15, 18, 21, 24e. From 3 to 12 with a step of 5, i.e. 3, 8

The answers are posted in this week's solutions under the function range_practice().

The new line after every print() commandAs you will have noticed, the print() function prints a new line every time it executes. That is, it prints its argument(s), and then tacks on a "return" afterwards.

A very convenient parameter to the print() function is end. In fact, this 'end' parameter is always there. We haven't used it because it has a default value of '\n' which means "add a new line". In other words, when you invoke, say,

print('hi')

You are actually invoking:print('hi', end='\n')

This 'end' parameter is always there. However it has a derfault value of '\n '. So unless you explicitly include the end parameter and give it a different value, it will always add a '\n ' at the end of every print() command.

9

Page 10: Lecture 1 - condor.depaul.educondor.depaul.edu/ymendels/401/l3.docx  · Web viewFollowing the def command is the . ... Programs typically consist of a sequence of statements that

You could do something weird such as: for i in range(3):

print(i, end="---")

This would output:0---1---2---

Getting / Creating Documentation for functionsNearly all of Python's built-in functions have documentation that can be viewed with the help() function.

For example, suppose you wanted documentation on how to use the len() function:

>>> help(len)Help on built-in function len in module builtins:

len(...) len(object) -> integer Return the number of items of a sequence or mapping.

>>> help(min)Help on built-in function min in module builtins:

min(...) min(iterable[, key=func]) -> value min(a, b, c, ...[, key=func]) -> value With a single iterable argument, return its smallest item. With two or more arguments, return the smallest argument.

Unfortunately, the help function does not provide useful information about programmer-defined functions (i.e. the functions created by programmers that are not built-in to Python). However, we as programmers can – and should – include information about our functions that will be available with the help() function.

For example, we can see what it displays when we ask about a function add5 we defined in the previous section:

>>> help(add5)Help on function add5 in module __main__:

add5(x)

As you can see, we really don't get any useful information here. However, when defining (i.e. creating) a function, a good programmer will always provide at least some kind of documentation for that function. If this is done in a particular way which we will learn

10

Page 11: Lecture 1 - condor.depaul.educondor.depaul.edu/ymendels/401/l3.docx  · Web viewFollowing the def command is the . ... Programs typically consist of a sequence of statements that

about, this information will be available to anybody who uses your function by simply typing the help() command.

The simplest way is as follows: Simply add a string below the def statement:

def add5(x):'prints the value of x+5'print(x+1)

Then when we call the help function on the method, we will get the string we have added:

>>> help(add5)Help on function f in module __main__:

add5(x) prints the value of x+5

Exercises: In addition to the required code, be sure to also write a brief (single line) help statement for each. See the solutions in this week's solutions file.

a. Write a personalized hello function called greetUser() that takes as a parameter a name represented as a string and prints “Hello <name>” on the screen.

b. Write a function called printParity() that takes as a parameter a list of numbers and prints, onto the screen and one per line, the values in the list. The odd values should have a label “odd” in front of them, and the even values should have a label “even” in front of them.

c. Write a function called printFour() that takes a list of strings as a parameter and prints all of the strings of length four to the screen, one per line.

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 s s.find(target): Returns the index of the first occurrence of the

substring target in s s.lower(): Returns a copy of the string s converted to lowercase s.upper(): Returns a copy of the string s converted to uppercase s.isupper(): Returns True if the string is in upper case s.islower(): Returns True if the string is in lower case

11

Page 12: Lecture 1 - condor.depaul.educondor.depaul.edu/ymendels/401/l3.docx  · Web viewFollowing the def command is the . ... Programs typically consist of a sequence of statements that

s.replace(old, new): Returns a copy of the string s in which every occurrence of substring old is replaced by new

s.split(sep): Returns a list of substrings of the string s, obtained using the delimiter string sep; the default delimiter is a space

We 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")0

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

Practice problem: Assign to a variable 'forecast' the string ‘It will be a sunny day

today’ and then write Python statements to do the following:

12

Page 13: Lecture 1 - condor.depaul.educondor.depaul.edu/ymendels/401/l3.docx  · Web viewFollowing the def command is the . ... Programs typically consist of a sequence of statements that

o Assign to a variable count the number of occurrences of the string ‘day’ in forecast

o Assign to a variable weather the index where the substring ‘sunny’ starts

o Assign to a variable change a copy of forecast in which every occurrence of the substring ‘sunny’ is replaced by ‘cloudy’

13

Page 14: Lecture 1 - condor.depaul.educondor.depaul.edu/ymendels/401/l3.docx  · Web viewFollowing the def command is the . ... Programs typically consist of a sequence of statements that

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

14

Page 15: Lecture 1 - condor.depaul.educondor.depaul.edu/ymendels/401/l3.docx  · Web viewFollowing the def command is the . ... Programs typically consist of a sequence of statements that

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.

Operator Description(expressions...), [expressions...], {key:datum...}, `expressions...`

Binding or tuple display, list display, dictionary display, string conversion

x[index], x[index:index], x(arguments...), x.attribute Subscription, slicing, call, attribute reference

** Exponentiation [8]+x, -x, ~x Positive, 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 x Boolean NOTand Boolean ANDor Boolean ORlambda Lambda expression

Exercise: Explain in what order the operators in the expressions below are evaluated: 3+2*4

o Because the '*' has higher precedence than '+', we will first do the multiplication, followed by the addition.

o 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**21. Exponentiation (32)

15

Page 16: Lecture 1 - condor.depaul.educondor.depaul.edu/ymendels/401/l3.docx  · Web viewFollowing the def command is the . ... Programs typically consist of a sequence of statements that

2. Multiplication (multiply the 9 from the previous step times 2)

2+3 == 4 or a >= 51. Addition2. == comparison3. >= comparison4. 'or' operation

NOTE: 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 you

16

Page 17: Lecture 1 - condor.depaul.educondor.depaul.edu/ymendels/401/l3.docx  · Web viewFollowing the def command is the . ... Programs typically consist of a sequence of statements that

but 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 Ada

If, 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///Ada

Normally successive calls to the function 'print' will output on a separate line:

>>> for name in ['Marisa', 'Sam', 'Tom', 'Anne']:print(name)

MarisaSamTomAnne

The print function also supports the optional argument end .

When the argument

17

Page 18: Lecture 1 - condor.depaul.educondor.depaul.edu/ymendels/401/l3.docx  · Web viewFollowing the def command is the . ... Programs typically consist of a sequence of statements that

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 '!' character

Marisa! Sam! Tom! Anne!

sep v.s. end ‘sep’ is what you use to separate one item from the next inside the print()

functiono print('hello', 'goodbye',45, sep=' ') will

separate the 3 items by two spaces: hello Goodbye 45 ‘end’ will append to the end of each item:

o 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:1. Some arguments are optional. That is, when you invoke this function, you are

not required to provide those arguments unless you want to. 2. 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.

18