Вы находитесь на странице: 1из 5

Alexander Magony

CSC108H1F 2014

Week 3
Functions, Variables, and Call Stacks
- Visualizes calling functions in other functions and how multiple stack frames store similar
variable and stuff. Again, its much easier to watch this video.

https://teach.cdf.toronto.edu/StG108/content/challenges/59/1

Type bool
- boolean values: true or false. States whether certain conditions are true. The values True
and False are type bool (as opposed to

- Comparison operators: states true or false if the comparison is true or false.


Less than ( < ): Eg. 3 < 4 returns True
Greater than ( > ): Eg. 3 > 4 returns False
Equal ( == ): Eg. 3 = = 1 * 3 returns True since both sides are equal. 7 == 7.0 is also True.
Greater than or equal to ( >= ): Eg. 3 >= 3 is True since they are equal in this case.
Less than or equal to ( <= ): Eg. 4 <= 3 is False since 4 is greater than 3.
Not equal to ( != ): Eg. 3 != 5 is True since 3 is not equal to 5.
Of course, variables and functions can be used in comparisons as well.
- Logical operators: can be used with Boolean expressions, like the comparison operators.
not: returns True if the expression is NOT true. This can be used multiple times in a row

(eg. not not (3 == 3) which is the same as saying 3 == 3). Eg. not (3 > 4) is True because 3
> 4 on its own is not true.
and: returns True if all expressions are true. Can compare two or more expressions. Eg. (3
> 2) and (2 == 2.0) is True because both expressions are true.
or: returns True if at least one of the expressions are true. Can compare two of more
expressions. Eg. (3 > 2) or (2 < 1) or (2 ** 2 == 1) is True because at least one of the
expressions are true.
Again, variables and function calls can be compared. Eg. class_grade > 50 or class_grade
== mean_grade(70, 80, 90) can be evaluated (the result depends obviously on the variable
and the function).
Operators can be combined. In these cases we have to be careful about the order.
eg. not 80 >= 50 or 90 >= 50 is True as it is equivalent to (not 80 >= 50) or (90 >= 50).
- This is different from not (80 >= 50 or 90 >= 50) which is false.
- As we can see, not is applied first, before or.
- The operator precedence (highest to lowest) is: not, and, or.
- Use parentheses to ensure the order of operations occurs in the order you like or
just for clarity. Eg. ( 4 != 4) or ( 2 > 3) is clearer than 4 != 4 or 2 > 3.

Converting between int, str, and float


- The types we have learned so far are int, str, float, and bool.
We can convert between the first three using built-in functions.

Alexander Magony

CSC108H1F 2014

- str(number) can be used to convert a number to a string.


eg. str(3) returns 3 as in a string, not a number. If multiplied by 2, you would get 33, not
6.

- int(string or number) can be used to convert a string (containing only digits) or a number
into an integer.
eg. int(3 * 5) returns 33333.
eg. int(4.65) returns 4.
- float(string or number) can convert a string (containing only digits) or a number into a float.
eg. float(465) returns 465.0.
eg. float(24) returns 24.0.
- if float or int functions are used to convert a string containing characters other than numeric
digits, a ValueError is returned since Python is unable to do the conversion.

- Using this with inputs:


eg. input(Enter the number of shoes: and the user responds 863, a string (which needs
to be converted to a number, in this case an int, to be compared to other numbers).

If num_shoes_left = 627, we can make num_shoes_wanted = int(input(Enter the number


of shoes: )) and then compare the variables to see if we have enough shoes. In this case,
num_shoes_left >= num_shoes_wanted would return False.

If statements
- We can control when our code runs based on boolean expressions.
- if statements: only execute if the boolean expression is True.
Generally written in this form:
if expression:
statements
- the statements are only executed if the expression is True. If none of the if statements are
fulfilled, nothing is returned. If we print this, it shows that the value None is printed. In most
cases, we want something else to be returned if the if statement is false.

- elif statement: must follow an if statement. If the first if statement is False, then this
expression is evaluated. If THIS statement is True, the expressions underneath are run.
elif expression:
statements
- else statement: if none of the preceding statements are True, run the below expressions.
This covers all of the rest of the options, ensuring that None is never returned.
else expression:
statements

- A few rules: there can be 0 or more elif clauses.

Alexander Magony

CSC108H1F 2014

There can also be 0 or 1 else clauses. It must be the last clause if it exists.
- Here is an example of a function
using if statements.
If the scheduled time is equal
to the estimated time, on time
is returned.
Otherwise/else, if the
scheduled time is later than
the estimated time, early is
returned.
If neither of those expressions
are true, the only remaining
option is that the scheduled
time is earlier than the
estimated time and delayed
is returned.

No if required
- Below are two valid, equivalent functions that return the same results given the same
arguments. Note that the | in the second picture is the cursor, not a character.

- Notice the first function uses an if statement to return boolean results (True or False). While
this works, it is simpler just to return the boolean statement (in this case ==) and True or
False will be returned if it is true or not. It is shorter and cleaner, so it is preferred.

Structuring if statements
- When using an if statement followed by an elif statement, only one of them will execute. If the
first if statement is true, it will execute and then the elif statement will be skipped.
If the if statement is false, it will skip to the elif statement and evaluate that. If that is true,
the elif statement will execute.

Alexander Magony

CSC108H1F 2014

- If you use an if statement following an if statement, they are both able to execute if they are
both true. Even if the first if statement is true, the second if statement is still evaluated. So this
is NOT equivalent to an if and an elif statement.

- Its pretty simple, but if youd like to see the video its the first video on this page: https://
teach.cdf.toronto.edu/StG108/content/challenges/68/1

- Look at this example on the right.


The two bodies of code are
equivalent to each other.

In the first body, both printed


statements only occur if
precipitation is true. The
differentiation is if temperature
is greater than zero or not.
In the second body, this is
represented by first asking if
both precipitation AND
temperature are true first. If
not, it asks if just precipitation is
true. If the code gets this far, it means temperature is not above zero so the winter
statement is printed.
Again, it seems pretty intuitive to me but, if not, check the above link again for the second
video.

More str Operators


- the equality (==) operator can be used to compare strings. It will only be true if the operators
are exactly the same (upper vs lower case matters too).
Of course, the inequality operator (!=) can also be used.

- the less than (<), greater than (>), less than or equal to (<=), or greater than or equal to
(>=) can also be used to compared strings by alphabetical order (later letters are greater than
earlier letters).
eg. abracadabra < ace returns True.
Capital letters are less than lower case letters.
- eg. a > A returns True.
Other characters can be compared too.
- eg. , < 3 returns True.
- Values of different types can be compared for equality but NOT ordering (though ints and
floats can be compared to each other).
eg. s == 3 returns False.
eg. s <= 3 returns a TypeError.

- We can see if one string is IN another statement.


eg. cad in acbracadabra returns True.
4

Alexander Magony

CSC108H1F 2014

eg. in abc returns True.


Again, upper or lower case matters.
- len(string) can be used to find the number of characters of a string.
eg. len() returns 0.
eg. len(354) returns 3.
eg. len(Bwa + ha * 10) returns 23.

str: indexing and slicing


- Given the example of s = Learn to Program the following diagram displays the indices
(plural for index, the position within a string) of the string.
in this example:
- s[0] returns L, the first
letter
- s[2] returns a
Negative indices count back
from the last letter.
- s[-1] returns m, the last
letter.
- s[-3] returns r.
Lengthier sections of the string can be sliced from the string using the below notation.
slice = a substring of a string from a start index up to but not including an end index.
- s[0:5] returns Learn.
- s[9:16] is equivalent to s[9:len(s)] and s[9:], all of which return Program.
- s[:8] is equivalent to s[0:8], both of which return Learn to.
- s[:] includes the entire string, returning Learn to Program.
As we see, using the length of the string as a end index includes everything up to but
not including that end index (so up until the end of the string).
Omitting a start index includes everything from the beginning of the string up to but
not including the end index and omitting an end index includes everything from the
start index to the end of the string.
Negative indices can be mixed with positive indices.
- s[1:8], s[1:-8], and s[-15:-8] all return earn to.
Slicing and indexing does not modify the original string.
- s still returns Learn to Program.
- s[6] = d would create a TypeError since the string cannot be modified.
- However, you can create new variables, or replace the old variable.
s = s[:5] + ed + s[5:] would cause s to refer to and return the new string Learned to
Program. The old string has not been modified, it is no longer referred to by s.

Вам также может понравиться