Python学习的第二课

  1. 函数
    函数是指可重复使用的程序片段。
    调用(Calling)函数
    1)无参数的函数
def say_hello():
    #该快属于这一个函数
     print(‘hello world’)
#函数结束 

say_hello()  #调用函数
say_hello()  # 再次调用函数

输出结果:

hello world
hello world

2)有参数的函数

def print_max(a,b):
      if a>b:
         print(a,'is maximum')
     elif a==b:
          print(a,'is equal to',b)
     else:
        print(b,'is maximum')


print_max(3,6)

x=4
y=9
print_max(x,y)

输出结果:

6 is maximum
9 is maxmum

3)局部变量与全局变量
局部变量

x=50

def 	func(x):
        print('x is ',x)
         x=2
         print('Changed local  x to' ,x)

func(x)
print('x is still' ,x)

输出结果:

x is 50
Changed local x to 2
x is still 50

全局变量

x=50

def func(x):
     global x
     print('x is ',x)
     x=2
    print('Changed global x to',x)

func(x)
print('Value of x is',x)

输出结果:

x is 50
Changed global x to 2
Value of x is 2

4)默认参数值
对于一些函数来说,你可能为希望是一些参数可选并使用默认的值,以避免用户不想为他们提供值的情况。默认参数可以有效的解决这一情况。
你可以通过在函数定义时附加一个赋值运算符(=),来为参数指定一个默认的参数。

def 	say(message,times=1)
        print(message*times)

say('hello')
say('hello',3)

输出结果:

hello
hellohellohello

5)关键字参数
如果你有一些具有许多参数的函数,而你又希望只对其中的一些进行指定,那你可以通过命名他们,来给他们进行赋值。这就是关键字参数。
我们使用命名(关键字)而非位置(一直以来我们所使用的方式)来指定函数中的参数。
这样做有两大有点:一是,我们不需要考虑参数的顺序,函数的使用将更加的容易。二是我们只对那些我们希望赋予的参数予以赋值,只要其他参数都具有默认参数值。

def func(a,b=5,c=10)
      print('a is',a,'and b is',b,'and c is',c)

func(3,7)
func(25,c=24)
func(c=50,a=100)

输出结果:

a is 3 and b is 7and  c is 10
a is 25 and b is 5 and c is 24
a is 100 and b is 5 and c is 50

6)可变参数
有时你可能想定义的函数里面能够有任意数量的变量,也就是参数的数量是可变的,这可以通过使用 * 星号来是实现。

def total(a=5,*numbers,**phonebook):
      print('a',a)
      #遍历元组中的所以项目
      for single_item in numbers:
            print('single_item',single_item)
      #遍历字典中的所有项目
      for first_part,second_part in phonebook.items():
           print(first_part,second_part)
       
  print(total(10,1,2,3,jack=1123,john=2231,inge=1560))

输出结果:

a 10
single_item 1
single_item 2
single_item 3
inge 1560
john 2231
jack 1123
None

7)Ruturn 语句
ruturn语句用于从函数中返回,也就是中断函数。我们也可以在选择在中断函数时从函数中返回一个值。

def maximum(x,y):
       if x>y:
         return x
        elif x==y:
             returm 'The numbers are equal'
         else:
            return y
            
print(maximum(4,6))

输出结果:

6

注意点:函数定义时,若用return返回某些值时,调用该函数要使用print打印。若函数定义时输出值时使用的是print,则可以直接调用该函数。

8)DocStrings
文档字符串,它能够帮助我们更好的记录程序并让其更加易于理解。
当程序运行时,我们可以通过一个函数来获取文档。

def print_max(x,y):
      '''打印两个数值中的最大值。
      这两个数都应该是整'''
      x=int(x)
      y=int(y)
      if x>y:
         print(x,'is maximum')
     else:
          print(y,'is maximum')

print_max(3,5)
print(print_max.__doc__)

输出结果:
5 is maximum
打印两个数值中的最大数。
这两个数都应该是整数

  1. 模块
    模块的导入使用 import 语句
    将模块某一变量导入程序中,使用:
    from…import 语句
    例:from sys import argv
  2. 数据结构
    1)列表
    列表是一种用于保存一系列有序项目的集合。
# This is my shopping list
shoplist=['apple','mango','carrot','banana']
print('I have', len(shoplist), 'items to purchase.')

print('These items are :',end=' ')
for item in shoplist:
     print(item,end=' ')
print('\nI also have to buy rice.')
shoplist.append('rice')
print('My shopping list is now', shoplist)

print('I will sort my list now')
shoplist.sort()
print('Sorted shopping list is', shoplist)

print('The first item I will buy is', shoplist[0])
olditem = shoplist[0]
del shoplist[0]
print('I bought the', olditem)
print('My shopping list is now', shoplist)

输出结果:

I have 4 items to purchase.
These items are: apple mango carrot banana
I also have to buy rice.
My shopping list is now ['apple', 'mango', 'carrot', 'banana', 'rice']
I will sort my list now
Sorted shopping list is ['apple', 'banana', 'carrot', 'mango', 'rice']
The first item I will buy is apple
I bought the apple
My shopping list is now ['banana', 'carrot', 'mango', 'rice']

2)元组
元组(Tuple)用于将多个对象保存到一起。你可以近似的把它看成一个列表。但是元组不能编辑或更改元组。

#推荐使用圆括号来指明元组的开始与结束,尽管括号是一个可选选项,但是明了胜过晦涩,显式优于隐式。
zoo=('python', 'elephant', 'penguin')
print('Number of animals in the zoo is',len(zoo))

new_zoo='monkey', 'camel',zoo
print('Number of cages in the new zoo is', len(new_zoo))
print('All animals in new zoo are', new_zoo)

print('Animals brought from old zoo are', new_zoo[2])
print('Last animal brought from old zoo is', new_zoo[2][2])
print('Number of animals in the new zoo is',
             len(new_zoo)-1+len(new_zoo[2]))

输出结果:

Number of animals in the zoo is 3
Number of cages in the new zoo is 3

All animals in new zoo are ('monkey', 'camel', ('python', 'elephant', 'penguin'))

Animals brought from old zoo are ('python', 'elephant', 'penguin')
Last animal brought from old zoo is penguin
Number of animals in the new zoo is 5

3)字典
字典的关键:键值:keys
值:Values
注意点:键值是唯一的。

ab = {
         'Swaroop': 'swaroop@swaroopch.com',
          'Larry': 'larry@wall.org',
         'Matsumoto': 'matz@ruby-lang.org',
        'Spammer': 'spammer@hotmail.com'
}
print("Swaroop's address is",ab['Swaroop'])

del ab['Spammer']
print('\nThere are {} contacts in the address-book\n'.format(len(ab)))

for name, address in ab.items():
print('Contact {} at {}'.format(name, address))

# 添加一对键值—值配对
ab['Guido'] = 'guido@python.org'
if 'Guido' in ab:
   print("\nGuido's address is", ab['Guido'])

输出结果:

Swaroop's address is swaroop@swaroopch.com

There are 3 contacts in the address-book

Contact Swaroop at swaroop@swaroopch.com
Contact Matsumoto at matz@ruby-lang.org
Contact Larry at larry@wall.org

Guido's address is guido@python.org

4)序列
列表,元组和字符串都可以看作序列的某种表现形式。
序列的主要功能是资格测试(也就是in 与 not in表达式)和索引操作,他们能够允许我们直接获取序列中的特定项目。

上面提到的序列的三种形态–列表,元组和字符串,同样拥有一种切边运算符。

shoplist = ['apple', 'mango', 'carrot', 'banana']   #列表
name = 'swaroop'  # 字符串

#索引或者下标操作符
print('Item 0 is', shoplist[0])
print('Item 1 is', shoplist[1])
print('Item 2 is', shoplist[2])
print('Item 3 is', shoplist[3])
print('Item -1 is', shoplist[-1])
print('Item -2 is', shoplist[-2])
print('Character 0 is', name[0])

# 列表中切片符的运用
print('Item 1 to 3 is', shoplist[1:3])
print('Item 2 to end is', shoplist[2:])
print('Item 1 to -1 is', shoplist[1:-1])
print('Item start to end is', shoplist[:])

# 字符串中切片运算符的运用
print('characters 1 to 3 is', name[1:3])
print('characters 2 to end is', name[2:])
print('characters 1 to -1 is', name[1:-1])
print('characters start to end is', name[:])

输出结果:

Item 0 is apple
Item 1 is mango
Item 2 is carrot
Item 3 is banana
Item -1 is banana
Item -2 is carrot

Character 0 is s

Item 1 to 3 is ['mango', 'carrot']
Item 2 to end is ['carrot', 'banana']
Item 1 to -1 is ['mango', 'carrot']
Item start to end is ['apple', 'mango', 'carrot', 'banana']

characters 1 to 3 is wa
characters 2 to end is aroop
characters 1 to -1 is waroo
characters start to end is swaroop

5)集合
集合(Set)是简单对象的无序集合,当集合中的项目存在与否比起次序或期出现次数更加重要时,我们就会使用集合。

通过使用集合,你可以测试某些对象的资格或者情况,检查他们是否是其他集合的子集,找到两个集合的交集等等。

>>>bri = set(['brazil', 'russia', 'india'])
>>> 'india' in bri
       	Ture
       	
>>> 'usa' in bri
       False      
        	
 >>> bric = bri.copy()
>>> bric.add('china')
>>> bric.issuperset(bri)
       True
     
>>> bri.remove('russia')
>>> bri & bric # OR bri.intersection(bric)
{'brazil', 'india'}

6)引用

print('Simple Assignment')
shoplist = ['apple', 'mango', 'carrot', 'banana']
# mylist 只是指向同一对象的另一种名称
mylist = shoplist

# 我购买了第一项项目,所以我将其从列表中删除
del shoplist[0]

print('shoplist is', shoplist)
print('mylist is', mylist)
# 注意到 shoplist 和 mylist 二者都
# 打印出了其中都没有 apple 的同样的列表,以此我们确认
# 它们指向的是同一个对象

print('Copy by making a full slice')
# 通过生成一份完整的切片制作一份列表的副本
mylist = shoplist[:]

# 删除第一个项目
del mylist[0]

print('shoplist is', shoplist)
print('mylist is', mylist)
# 注意到现在两份列表已出现不同

输出结果:

Simple Assignment
shoplist is ['mango', 'carrot', 'banana']
mylist is ['mango', 'carrot', 'banana']

Copy by making a full slice

shoplist is ['mango', 'carrot', 'banana']
mylist is ['carrot', 'banana']

7)有关字符串的更多内容

# 这是一个字符串对象
name = 'Swaroop'
if name.startswith('Swa'):
   print('Yes, the string starts with "Swa"')

if 'a' in name:
    print('Yes, it contains the string "a"')

if name.find('war') != -1:
   print('Yes, it contains the string "war"')

delimiter = '_*_'
mylist = ['Brazil', 'Russia', 'India', 'China']
print(delimiter.join(mylist))

输出结果:

Yes, the string starts with "Swa"
Yes, it contains the string "a"
Yes, it contains the string "war"
Brazil_*_Russia_*_India_*_China
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值