2017.8.31 Codecademy

練習1

  1. def a function called cube that takes an argument called number.
  2. make that function return the cube of that number (i.e. that number multiplied by itself and multiplied by itself once again).
  3. def a second function called by_three that takes an argument called number.
  4. if that number is divisible by 3, by_three should call cube(number) and return its result.
  5. otherwise, by_three should return False.
def cube(number):
   return number * number * number

def by_three(number):
   if number % 3 == 0:
     return cube(number)
 else:
     return False

print(cube(2))
print(by_three(3))
print(by_three(4))

8
27
False


練習2:

  1. def a function called distance_from_zero, with one argument (choose any argument name you like).
  2. if the type of the argument is either int or float, the function should return the absolute value of the function input.
  3. otherwise, the function should return “Nope"

def distance_from_zero(x):
  if type(x)==int or type(x)==float:
    return abs(x)
  else:
    return 'Nope'

print(distance_from_zero(5))
print(distance_from_zero(-5))
print(distance_from_zero(-5.5))

5
5
5.5


max(): 最大值

maximum = max(1,2,3)
print(maximum)

3


min(): 最小值

minimum = min(1,2,3)
print(minimum)

1


abs(): 絕對值

absolute = abs(-42)
print(absolute)

42


type(): 類型

print(type(42))
print(type(4.2))
print(type('hello'))

<class ‘int’>
<class ‘float’>
<class ‘str’>


發表留言