Lecture 03 - CS61A fa2022
Side Effect (and Return Values)
- Side effect: The action besides returning value is a side effect of a function.
- Fucntions can deal with the params either way. e.g.
print()will have a side effect of printing things on the monitor and return "nothing", which actually isNone.Noneis a type ofNoneType, which is unsupported for operand. e.g.add(None, None)andNone + 1both returnsTypeErrorNonewill be returned if no value has been explicitly returned.- Is this better?
Revised Version by
ChatgptYour sentence is already clear and grammatically correct. However, you can make it slightly more concise and idiomatic: "None will be returned if no value is explicitly provided." This version conveys the same meaning in a more streamlined manner.
print(None)andprint(print(1), print(2))both returnNone, while the latter one also has side effects to print1and2
More Function Features
- Default value: Operands of Python can have defined default value, just like C++
- Multiple return values: Python supports
return val1, val2, which is not supported in C++ - Doctests: A powerful tools for case test. See more here
Boolean Expression
-
Google Maps uses a boolean to decide whether to avoid highways in driving directions:
avoid_highways = True
Twitter uses a boolean to remember where the user allows personalized ads:
personalized_ads = False- How do they know? Twitter is not be a open source software, is it?
- Stupid Question! Answer: Docs! e.g. Twitter params - dnt
- Comparison, logical and their compound operation.
- Use
==for if_equal!- Why?
- Inspired by CS50P, compiler cannot tell the difference between assign and if_equal.
- Trick:
return grade > 65withoutifandelse
Statement
- Revice that, for structure of a function:
def <name>(<parameters>): # ← Function signature return <return expression> # ← Function body - For compound statements, which is a statement that contains other statements:
<header>: # CLAUSE <statement> # SUITE <statement> # a sequence of statements - Conditional statement:
if,else: no(and).elifsupported.
- Loops:
while, no(and).breakandcontinue- Why
continueis not mentioned in ppt?
- Why
foris somehow complicated:- Syntax:
for <index_val> in <array>:. Beware to append:. - Usage:
for x in ["apple", "banana", "cherry"]:for x in fruits: # fruits=["apple", "banana", "cherry"]for x in range(<from>, <to>, <increasment>):for x in "string" # x will be 's' 't' 'r' 'i' 'n' and 'g'
- Why
foris not mentioned?
- Syntax:
pass: placeholder statement, avoiding errors for somewhere not implemented. Note:;in C is of the same use- idle in OS is somehow similar
;;in SHELL is not related, which is used only after the end of eachcasesuite
Terms
| en | zh_CN | Supplement | Example |
|---|---|---|---|
Vocabs and Phrases
| en | Explanation | Example |
|---|---|---|