python基本语法

Syntax

swap two variables in one line:

a, b = b, a

We'll demystify this bit of Python magic later when we talk about tuples.

Function

Functions that don’t return

return None

Without a return statement, least_difference is completely pointless, but a function with side effects may do something useful without returning anything.

Like print()

Default arguments

defgreet(who="Colin"):
print("Hello,",who)

Higher-order functions

defmult_by_five(x):
    return 5 *xdefcall(fn,arg):
"""Call fn on arg"""returnfn(arg)

defsquared_call(fn,arg):
"""Call fn on the result of calling fn on arg"""returnfn(fn(arg))

print(
call(mult_by_five, 1),
squared_call(mult_by_five, 1),
    sep='\n',# '\n' is the newline character - it starts a new line)

Round

round(number, ndigits=None)
    Round a number to a given precision in decimal digits.

    The return value is an integer if ndigits is omitted or None.  Otherwise
    the return value has the same type as the number.  ndigits may be negative.

Booleans and Conditionals

'3' == 3 # False

Combining boolean values

and
or # and is evaluated before or
not 

conditionals

def inspect(x):
    if x == 0:
        print(x, "is zero")
    elif x > 0:
        print(x, "is positive")
    elif x < 0:
        print(x, "is negative")
    else:
        print(x, "is unlike anything I've ever seen...")
print("Splitting", total_candies, "candy" if total_candies == 1 else "candies")

Boolean convertion

print(bool(1)) # all numbers are treated as true, except 0
print(bool(0))
print(bool("asf")) # all strings are treated as true, except the empty string ""
print(bool(""))

exercise

We’ve seen that calling bool() on an integer returns False if it’s equal to 0 and True otherwise. What happens if we call int() on a bool? Try it out in the notebook cell below.

Can you take advantage of this to write a succinct function that corresponds to the English sentence "does the customer want exactly one topping?"?

add Codeadd Markdown
 
def exactly_one_topping(ketchup, mustard, onion):
    """Return whether the customer wants exactly one of the three available toppings
    on their hot dog.
    """
    return (ketchup and not mustard and not onion) or (mustard and not ketchup and not onion) or (onion and not ketchup and not mustard)
# Check your answer
q6.check()
Correct:

This condition would be pretty complicated to express using just and, or and not, but using boolean-to-integer conversion gives us this short solution:

return (int(ketchup) + int(mustard) + int(onion)) == 1
Fun fact: we don't technically need to call int on the arguments. Just by doing addition with booleans, Python implicitly does the integer conversion. So we could also write...

return (ketchup + mustard + onion) == 1
posted @ 2022-03-14 15:34  yuxuan2125  阅读(34)  评论(0)    收藏  举报