0.5 * 10 * 5might be the area of a triangle, where the value 10 is the base and 5 is the height. To associate a name with those values, we use variables. The general form of an assignment statement is
variable = expressionAssign the value 10 to a variable named base and the value 5 to a variable height. Now rewrite the expression
0.5 * 10 * 5so that it uses variables base and height. Next, assign the expression to a variable named area. Reassign variables base and height the values 12 and 17, respectively. What is the value of area now? Type area and the return key to see area's value. Verify the current variable values by typing each variable in the shell followed by the return key. Now recalculate the area (using the new values of the variables) and check it's value.
def function_name(parameters): bodyIn the editor section of Wing, define a function calculate_area, parameters: triangle_base and triangle_height (note:any legal variable names would do, but it's best to choose something meaningful).
The function should calculate the triangle's area
(recall area = 0.5*base*height) for the given base
and height, and return the area.
Save the file: File -> Save. A dialog box will appear.
In the text field labelled File name: replace
untitled-1.py
with triangle.py
.
In the Save in: drop down menu, select your own directory:
the line that starts iwth your user id
and continues with 'on CCentre Student Server...'.
Create a new folder called cscb20s.
Open cscb20s, and create a folder LabPractice. Open LabPractice.
Click the Run button. In the shell, call the function as follows:
calculate_area(10, 12) calculate_area(3.4, 5.2) calculate_area(base, height)
math
using
dir
and help
dir(math)
to find out which
functions math contains and use help(math.function)
(where function is replaced by the name of a function from math)
to find out more about a particular function.
To see detailed information about all math
functions, call help(math)
.
In the shell, import math and write code to do the following:
str
str
stands for string.
A string is a sequence of characters. We can iterate over (walk through)
a str in a loop and examine each character.
In the Python shell, do the following:
Assign the string "superconductivity" to a variable s.
(If your fingers are up to it, you may use
the string "supercalifragilisticexpialidocious".)
For the following print statements, recall that "+"
combines strings (concatenates them), and "," can be used
to separate items in a print statement.
>>>
prompt appears.
str
Methods'abc'.upper()
,
a str method, uses the value 'abc' to return its uppercase equivalent,
'ABC'. What methods a value has depends on its type:
'abc' has a method upper() because 'abc' is a str.
Explore the str methods using dir and help,
and use them to complete the tasks below.
Create strings in the Python shell and do the
following:
In most cases, you can't list every possible argument value and outcome. You have to limit your prediction and checking to a relatively small set of values, so that you can do your testing in a reasonable amount of time. The best way to do this is to pick some situations that are representative of others, and also to introduce both "usual" and "unusual" situations. For example, predicting what your function will do with the empty string '' as a parameter, is an unusual test case, since this situation is often unspecified in the function docstring. A representative test case might be the string 'e' (or 'K') standing for all single-character strings.
__builtins__
functions:
longer(str, str)
Given two strings,
return the length of the longer string.
earlier(str, str)
Given two strings made
up of lowercase letters, return the string that
would appear earlier in the dictionary.
count_letter(str, str)
Given a string and a single-character string, count all occurrences
of the second string in the first and return the count.
remove_digits(str)
Return a new string that is the same as the given string, but with digits removed.
repeat_character(str, str)
Given a string and a single-character string, return a string consisting of
the second, single character string repeated as many of times as it appears
in the first string.
where(str, str)
Given a string and a single-character string, return the index of the first occurrence
of the second string in the first. For example, where("abc", "b")
should
return 1. If the second string is not in the first, return -1.
Remember to use the Python functions dir and help to get information about methods.
Do you remember how to slice strings? We can do the same thing with lists. If we have a list
names = ['Bob', 'Ho', 'Zahara', 'Amitabha', 'Dov', 'Maria']then
names[1:4]
returns a new list equal to
['Ho', 'Zahara', 'Amitabha']There are several list methods that you may find helpful:
append, count, extend, index, insert, pop,
remove, reverse, sort
. Use help to learn more about them.
names = ['Bob', 'Ho', 'Zahara', 'Amitabha', 'Dov', 'Maria']For the following steps, use names and slice notation:
while
loopsdisplay_list(list)
display_list_even(list)
display_list_reverse(list)
sum_elements(list)
duplicates(list)
pets = [["Shoji", "cat", 18], ["Hanako", "dog", 15], ["Sir Toby", "cat", 10], ["Sachiko", "cat", 7], ["Sasha", "dog", 3], ["Lopez", "dog", 13]]We can access each element of list pets using its index:
>>> pets[3] ["Sachiko", "cat", 7]We can access each element of list pets using its index: We can also access elements of the inner lists. For example, since pets[3] refers to a list, we can use pets[3] to access the element at position 2:
>>> pets[3][2] 7This is saying that element 2 of element 3 of the list pets (the age of the cat named \Sachiko") is 7.
Write the following loops and functions and call each function to verify your work. You may use for loops.
# Instead of using the terms "url" or "file", we use the more general # term "reader" to indicate an open file or webpage. def display_lines(r): '''Display the lines of the file/webpage (with leading and trailing whitespace removed) from open reader r.''' def display_lines_with_text(r, text): '''Display the lines of the file/webpage (with leading and trailing whitespace removed) from open reader r that contain the str text.''' def copy_file(r): '''Write the lines of open reader r to the file copy.txt.''' if __name__ == '__main__': data_file = open('data.txt') display_lines(data_file) data_file.close() data_file = open('data.txt') display_lines_with_text(data_file, 'ene') data_file.close() data_file = open('data.txt') copy_file(data_file) data_file.close()
May want to expand the file coverage, since that is the most germane for this course.