本节将介绍如何自定义函数、调用函数、使用函数库中的函数
a、格式:def + 函数名(参数):
def hello_world(word):
注意,有colon冒号:
b、可选的函数注释"""Prints 'Hello World!' to the console."""
c、函数体
word = "Hello World!"
print(word)
整理上述代码如下:
def hello_world(word):
"""Prints 'Hello World!' to the console."""
word = "Hello World!"
print(word)
helloworld("I love Python!")
def cube(number):
return number*number*number
def by_three(number):
if (number % 3) == 0:
return cube(number)
else:
return False
import math
print math.sqrt(25)
#输入结果为5
from math import sqrt
print sqrt(25)
from math import *
def biggest_number(*args):
print max(args)
return max(args)
def smallest_number(*args):
print min(args)
return min(args)
def distance_from_zero(arg):
print abs(arg)
return abs(arg)
biggest_number(-10, -5, 5, 10)
smallest_number(-10, -5, 5, 10)
distance_from_zero(-10)
maximum = max(1,2,3,8.8,9.9,4,7,6,9)
print maximum
min()——返回整型或浮点型数值集合中的最小值
minimum = min(1,2,3,0.5)
print minimum
abs()——返回输入数值的绝对值
absolute = abs(-99)
print absolute
type()——返回数据的类型
print type(99) #int
print type(99.9) #float
print type('Python') #str
def shut_down(s):
if s == "yes":
return "Shutting down"
elif s == "no":
return "Shutdown aborted"
else:
return "Sorry"
import math
print math.sqrt(13689) #结果是117.0
def distance_from_zero(number):
if type(number) == int or type(number) == float:
return abs(number)
else:
return "Nope"
def hotel_cost(nights):
return 140*nights
def plane_ride_cost(city):
if city == "Charlotte":
return 183
elif city == "Tampa":
return 220
elif city == "Pittsburgh":
return 222
elif city == "Los Angeles":
return 475
def rental_car_cost(days):
if days >= 7:
return days*40 - 50
elif days >= 3:
return days*40 - 20
return days*40
def hotel_cost(nights):
return 140*nights
def plane_ride_cost(city):
if city == "Charlotte":
return 183
elif city == "Tampa":
return 220
elif city == "Pittsburgh":
return 222
elif city == "Los Angeles":
return 475
def rental_car_cost(days):
if days >= 7:
return days*40 - 50
elif days >= 3:
return days*40 - 20
return days*40
def trip_cost(city,days):
return hotel_cost(days) + plane_ride_cost(city) + rental_car_cost(days)
def hotel_cost(nights):
return 140*nights
def plane_ride_cost(city):
if city == "Charlotte":
return 183
elif city == "Tampa":
return 220
elif city == "Pittsburgh":
return 222
elif city == "Los Angeles":
return 475
def rental_car_cost(days):
if days >= 7:
return days*40 - 50
elif days >= 3:
return days*40 - 20
return days*40
def trip_cost(city,days,spending_money):
return hotel_cost(days) + plane_ride_cost(city) + rental_car_cost(days) + spending_money
print("Above costs %d dollars!" % trip_cost("Los Angeles", 5, 600))