Python:学习笔记(二)


求模  %,与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')

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值