Sunteți pe pagina 1din 5

Alexander Magony

CSC108H1F 2014

Week 2
Type str

- string literal: a sequence of characters. Is the type str and is contained by single or
double quotes.

eg. hello or hello


strings are values and can be stored in variables (eg. sunny_greeting = What a

beautiful day!).
Different symbols can be used in strings (@, *. -. etc). However, Youre so cold will
return a SyntaxError since the internal single quote prematurely ends the string.
This can be fixed by changing the containing quotes to double quotes: Youre so
cold.
- Alternatively an escape character/sequence can be used. You\re so cold. will
return Youre so cold.

- Can add strings together. Cannot add a str to an int or a float (returns TypeError).
Even if the int or float is in quotations (because that makes it a str like 5).

eg. personal + penguin returns personalpenguin. Spaces have to be included in


the quotes (eg. personal + penguin returns personal penguin).

You can also link variables that refer to strings. Example:

name = Alex
phrase = watch out
punctuation = !
name + phrase + punctuation returns Alex watch out!
Strings can be multiplied by ints (floats or strs will return TypeErrors).
eg. ha * 5 returns hahahahaha)
Order of operations still takes precedence.
- Bwa + ha * 5 returns Bwahahahahaha
Dividing strings, raising strings to exponents, and other inappropriate operations will
result in TypeErrors.

Input/Output and str Formatting

- print(argument): prints a sequence of arguments for user to read.


eg. print(hello) returns hello. There are no quotes as quotes only belong to
represent strings within Pythons internal structure, not for the user.

eg. print(3 + 7 - 3) returns 7.


eg. print(hello, there) returns hello there. Notice spaces are included when
printing multiple arguments.

Alexander Magony

CSC108H1F 2014

- Lets create two similar functions where one prints and one returns.

def square_return(num):
return num ** 2
def square_print(num):
print(The square of num is, num ** 2)
Then, if we execute: answer_return = square_return(4) nothing happens. But if we
then enter answer_return, 16 is returned.
If we execute: answer_print = square_print(4) then The square of num is 16 is
returned. If we then execute answer_print, the value None is returned (visually, nothing
returns) since there is no return statement.

NoneType: the type of value that results when no return statement is used in a function
body. The actual value of this type is None which is used to represent nothing being
returned.
- So answer_return represents a numeric value and can be used in calculations (eg.
answer_return * 5 returns 80). However, answer_print * 5 will result in a TypeError since
answer_print refers to NoneType.

- When a return statement executes, it passes a value back to the caller and exits the function.
So if a function contains a print statement after a return statement, the print statement will
never be reached.

- input(prompt): a function that allows Python to get a string from the user. Returns the string
entered by the user (even if a number is typed, it is a string like 2). The prompt is the
argument to input.
eg. input(What is your name? ) returns What is your name? (where a cursor is flashing at
the end, waiting for the user to type something and press enter). If Jen is typed, Jen
returns, the single quotations indicating that it is type str.
The result can be stored. eg. location = input(What is your location? ) returns What is
your location? followed by a blinking cursor waiting for the user. If Toronto is typed in that
same line, Toronto will be the str value that is stored at the memory address contained in
the variable location.
- If name was the variable used to refer to Jen, we could enter print(name, lives in,
location) and print Jen lives in Toronto. Remember that spaces are automatically entered
when print uses several arguments.

- Triple quoted strings are able to span multiple lines. Example: if we enter
>>> print(How
are
you?)
the printed statement is:
How
are
you?
- However, if we enter:

Alexander Magony

CSC108H1F 2014

>>> s = How
are
you?
Entering s will return How\nare\nyou?. Notice that the triple quotes are gone and a \n is
included.
- \n is an escape sequence known as newline. Another escape sequence is \t known as a tab
escape sequence which inserts a tab.
eg. print(3\t4\t5 prints 3 4 5.
- since print(\) will produce a SyntaxError, since Python expects a character following the
escape character, we type print(\\') to print \ on its own.
- Of course, there is still the single quote escape sequence. eg. print(don\t) returns dont. It
also works for double quotes.

Docstrings and Function Help


- when we start typing a build-in function in Python [eg. abs( ], a help box pops up showing the
type of parameters and the return type (in this case abs(number) -> number)

- When you call help(abs), the help box information appears followed by a description of the
function.

- We can add our own help information to our functions by writing documentation in a format
called docstring.

- example: if we write
def area(base, height):
(number, number) -> number
Return the area of a triangle with dimension base and height.

return base * height / 2


then the information contained in the triple quotes will appear if we run help(area). If you
start typing area, the help box will show the first line of the docstring.

Function Design Recipe


- Function design recipe includes:
Header, includes function name and parameters: eg. def area(base, height):
Type contract, includes the type of values needed for the function. Included in triple
quotes since it is not part of the function body: eg. (number, number) -> number

Description, includes an explanation of the functions use. Included in triple quotes since
not part of function body.

Examples, examples of what values can be given to the function to produce what result.
Body, includes the code of the function that helps return the desired value.
3

Alexander Magony

CSC108H1F 2014

- Example:

- Recipe for designing Functions.


1. Type a few examples demonstrating how your function is expected to behave given
certain arguments. Pick a name for the function.
2. Create the type contract, explaining the types of parameters and returned value.
3. Create the header, picking meaningful parameter names.
4. Create a description mentioning every parameter and describing the return value.
Now that youve decided what the function should do and have described the parameters
(all except the header is included in a docstring
5. Create the function body which produces the results that the examples predict. Try
testing the examples to see if the expected values are returned.
You can also try searching your function with help to see if the docstring if formatted
correctly.

Function Reuse
- If you are designing a function that uses code similar to another function, reusing the function
in the new functions code minimizes error.
Eg. Imagine you have designed a perimeter(side1, side2, side3) function that calculates
the perimeter of a triangle. If you are then designing a semiperimeter(side1, side2, side3)
function to calculate half of the perimeter, it is best to include the perimeter function and
divide by half rather than recalculating the perimeter by adding the sides together and
dividing by half. This way, since the perimeter function has already been tested, it is likely
that the semiperimeter function will contain less errors than if you were rewriting the code
from scratch.

- You can also pass function calls of built functions as arguments to other functions.
Eg. if you wanted to find out which triangle had a bigger area, you could use a built area
function as an argument by typing:
- max(area(3.8, 7.0), area(3.5, 6.8)) can be used to compare both triangles. The bigger
area will be returned (in this case 13.2999999). You can then check which triangle
produces this area.

Alexander Magony

CSC108H1F 2014

Visualizing Function Calls


- Important point is that local variables are created in temporary stack frame while functions
are executed.
Stack frame: keeps track of information about a function while being executed.
Local variables: created inside a function body.
The local variables and stack frame disappear when the function exits. The return value
can be stored in a global variable to keep it in computer memory (eg. minutes_2 =
convert_to_minutes(2)).
- Easier to watch the video regarding this topic: https://teach.cdf.toronto.edu/StG108/
content/challenges/52/1

Constants
- Magic numbers: numbers seen many times throughout a bunch of functions (eg. 50 in a
bunch of functions that compare grades to 50 to determine if they pass or fail).
It is better to make these numbers into constants and use these constant variables in the
code. This way, if you need to change the magic number value (eg. the passing grade),
you change it once at the top in the variable rather than in all of the function bodies.
- Example:
On the right, if the
passing grade had to be
changed, we could just
change the
PASS_BOUNDARY variable
rather than changing every
function body to the new
number.

S-ar putea să vă placă și