求模 %,与c java 相反
求余 //
round 四舍五入
>>>10 % 3
1
>>>10 % -3
-2
>>>-10 % 3
2
>>>-10 % -3
3
函数
def test():
print(a)
a = 8;
test()
简单函数定义和调用
def describe_pet(animal_type, pet_name):
"""显示宠物的信息"""
print("\nI have a " + animal_type + ".")
print("My " + animal_type + "'s name is " + pet_name.title() + ".")
describe_pet(animal_type='hamster', pet_name='harry')
指定参数名称和值,因此参数顺序不再重要
def describe_pet(pet_name, animal_type='dog'):
"""显示宠物的信息"""
print("\nI have a " + animal_type + ".")
print("My " + animal_type + "'s name is " + pet_name.title() + ".")
describe_pet(pet_name='willie')
参数设置默认值,默认值参数必须放在非默认后面
def describe_pet(pet_name, animal_type='dog'):
"""显示宠物的信息"""
return 34
a = describe_pet(pet_name='willie')
返回值直接写return
def get_formatted_name(first_name, last_name, middle_name=''):
print(first_name + last_name + middle_name)
get_formatted_name('aa', 'bb')
第三个有默认值,可以不传入参数
>>> global b;
>>> b = []
>>> def test(v):
global b
b = a
print(b)
>>> test(a)
[3, 3, 4]
>>> b
[3, 3, 4]
全局变量的使用
function_name(list_name[:])
传递列表复制值,防止参数被修改
>>> def make_pizza(*toppings):
"""打印顾客点的所有配料"""
print(toppings)
>>> make_pizza('mushrooms', 'green peppers', 'extra cheese')
('mushrooms', 'green peppers', 'extra cheese')
>>> make_pizza('mushrooms', 'green peppers', 123)
('mushrooms', 'green peppers', 123)
任意数量、任意类型的参数(*xxx)
def build_profile(first, last, **user_info):
"""创建一个字典,其中包含我们知道的有关用户的一切"""
profile = {}
profile['first_name'] = first
profile['last_name'] = last
for key, value in user_info.items():
profile[key] = value
return profile
形参**user_info 中的两个星号让Python创建一个名为user_info 的空字典
pizza.py:
def make_pizza(size, *toppings):
"""概述要制作的比萨"""
print("\nMaking a " + str(size) +"-inch pizza with the following toppings:")
for topping in toppings:
print("- " + topping)
导入模块:
import pizza
pizza.make_pizza(16, 'pepperoni')
导入特定函数:
from pizza import make_pizza
as指定函数别名:
from pizza import make_pizza as mp
mp(16, 'pepperoni')
as指定模块别名:
import pizza as p
p.make_pizza(16, 'pepperoni')
导入模块全部函数:
from pizza import *
make_pizza(16, 'pepperoni')