[A byte of Python] 学习笔记一

目录

控制流

if语句

while语句

for循环

break语句

continue语句

函数

关键字参数

可变参数

模块

数据结构

列表 List

元组 Tuple

字典 Dictionary

序列 Sequence

集合 Set

引用

字符串


控制流

if语句

if 条件一:
    执行一
elif 条件二:
    执行二
else:
    执行三

while语句

while 条件:

else:

for循环

for i in range(1,5):
    
else:
    

break语句

中止循环用,任何相应循环内中的else块都不会再执行。

continue语句

跳过本次循环剩下语句,继续下一次循环。

函数

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

关键字参数

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 7 and 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

可变参数

定义的函数内的参数数量是可变的,可通过星号实现。

*param :从此处开始直到结束的所有位置参数( Positional Arguments) 都将被收集并汇集成一个称为“param”的元组( Tuple) 。
 **param : 从此处开始直至结束的所有关键字参数都将被收集并汇集成一个名为 param 的字典( Dictionary) 。

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
Jack 1123
John 2231
Inge 1560

模块

import sys
from math import sqrt
print("Square root of 16 is", sqrt(16))

数据结构

列表 List

方括号括起,逗号分隔,可变。

# Define my shopping list

shopping_list = ['apple', 'orange', 'banana', 'watermelon']
print('I need to buy these things:', end=' ')

for item in shopping_list:

    print(item, end=' ')

shopping_list.append('pear')
print('\n', shopping_list)

shopping_list.sort()
print('\n', shopping_list)

I need to buy these things: apple orange banana watermelon 
 ['apple', 'orange', 'banana', 'watermelon', 'pear']

 ['apple', 'banana', 'orange', 'pear', 'watermelon']

元组 Tuple

括号括起,逗号隔开,不可变。

old_zoo = ('tiger', 'lion', 'kangaroo')
print(old_zoo, len(old_zoo))

new_zoo = 'camel', 'monkey', old_zoo
print(new_zoo, len(new_zoo))

print(new_zoo[2])
print(new_zoo[2][0])
('tiger', 'lion', 'kangaroo') 3
('camel', 'monkey', ('tiger', 'lion', 'kangaroo')) 3
('tiger', 'lion', 'kangaroo')
tiger

字典 Dictionary

链接键值(Keys)和值(Values),只能使用不可变的对象( 如字符串) 作为字典的键值, 但可以使用可变或不可变的对象作为字典中的值。

格式:

d = {key : value1 , key2 : value2}
ads = {'Violaine': 'vio@outlook.com', 'Guillaume': 'gui@gmail.com'}

print('The address of Guillaume is:', ads['Guillaume'])

del(ads['Violaine'])
print(len(ads))

ads['Violaine'] = 'vio@outlook.com'

for name, address in ads.items():
    print('The address of {} is: {}:'.format(name, address))
The address of Guillaume is: gui@gmail.com
1
The address of Guillaume is: gui@gmail.com:
The address of Violaine is: vio@outlook.com:

序列 Sequence

列表、 元组和字符串可以看作序列( Sequence) 的某种表现形式。

序列的主要功能是资格测试( Membership Test) ( 也就是 in 与 not in 表达式) 和索引操作( Indexing Operations)
 

切片( Slicing) 运算:(适用于列表、元组、字符串)

shoplist = ['apple', 'mango', 'carrot', 'banana']

# Indexing or 'Subscription' operation #
# 索引或“下标( Subscription) ”操作符 #
print('Item 0 is', shoplist[0])
print('Item 1 is', shoplist[1])
print('Item -1 is', shoplist[-1])
print('Item -2 is', shoplist[-2])

# Slicing on a list #
print('Item 1 to 3 is', shoplist[1:3])
print('Item 1 to end is', shoplist[1:])
print('Item 1 to -1 is', shoplist[1:-1])
print('Item start to end is', shoplist[:])
Item 0 is apple
Item 1 is mango
Item -1 is banana
Item -2 is carrot
Item 1 to 3 is ['mango', 'carrot']
Item 1 to end is ['mango', 'carrot', 'banana']
Item 1 to -1 is ['mango', 'carrot']
Item start to end is ['apple', 'mango', 'carrot', 'banana']

name = 'swaroop'
print('Character 0 is', name[0])
# 从某一字符串中切片 #
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[:])
Character 0 is s
characters 1 to 3 is wa
characters 2 to end is aroop
characters 1 to -1 is waroo
characters start to end is swaroop

shoplist = ['apple', 'mango', 'carrot', 'banana']
print(shoplist[::1])
print(shoplist[::2])
['apple', 'mango', 'carrot', 'banana']
['apple', 'carrot']

集合 Set

集合是简单对象的无序collection,只关心集合中的项目存在与否。

country = set(['China', 'France', 'US'])
print('China' in country)
print('Germany' in country)
True
False

引用

如果仅仅是将一个变量名赋予给另一个名称, 那么它们都将“查阅”同一个对象。

希望创建一份诸如序列等复杂对象的副本( 而非整数这种简单的对象( Object) ) , 必须使用切片操作来制作副本。

country = ['China', 'France', 'US']

# pays 只是指向同一对象的另一种名称
pays = country
del country[0]
print(country, pays)

# 通过生成一份完整的切片制作一份列表的副本
pays = country[:]
del pays[0]
print(country, pays)
['France', 'US'] ['France', 'US']
['France', 'US'] ['US']

字符串

name = 'Violaine'

if name.startswith('Vio'):
    print('Yes, it starts with "Vio".')
if 'laine' in name:
    print('Yes, it contains "laine".')
if name.find('io') != -1:
    print('Yes, it contains "io".')

delimiter = '***'
namelist = ['Violaine', 'Guillaume']
print(delimiter.join(namelist))
Yes, it starts with "Vio".
Yes, it contains "laine".
Yes, it contains "io".
Violaine***Guillaume
this is a book about python. it was written by Swaroop C H.its name is "a byte of python". Table of Contents Preface Who This Book Is For History Lesson Status of the book Official Website License Terms Using the interpreter prompt Choosing an Editor Using a Source File Output How It Works Executable Python programs Getting Help Summary 4. The Basics Literal Constants Numbers Strings Variables Identifier Naming Data Types Objects Output How It Works Logical and Physical Lines Indentation Summary 5. Operators and Expressions Introduction Operators Operator Precedence Order of Evaluation Associativity Expressions Using Expressions Summary 6. Control Flow Introduction The if statement ivUsing the if statement How It Works The while statement Using the while statement The for loop Using the for statement Using the break statement The continue statement Using the continue statement Summary 7. Functions Introduction Defining a Function Function Parameters Using Function Parameters Local Variables Using Local Variables Using the global statement Default Argument Values Using Default Argument Values Keyword Arguments Using Keyword Arguments The return statement Using the literal statement DocStrings Using DocStrings Summary 8. Modules Introduction Using the sys module Byte-compiled .pyc files The from..import statement A module's __name__ Using a module's __name__ Making your own Modules Creating your own Modules from..import The dir() function Using the dir function Summary 9. Data Structures Introduction List Quick introduction to Objects and Classes Using Lists Tuple Using Tuples Tuples and the print statement Dictionary Using Dictionaries Sequences Using Sequences References Objects and References More about Strings String Methods Summary 10. Problem Solving - Writing a Python Script The Problem The Solution First Version Second Version Third Version Fourth Version More Refinements The Software Development Process Summary 11. Object-Oriented Programming Introduction The self Classes Creating a Class object Methods Using Object Methds The __init__ method Using the __init__ method Class and Object Variables Using Class and Object Variables Inheritance Using Inheritance Summary 12. Input/Output Files Using file Pickle Pickling and Unpickling Summary 13. Exceptions Errors Try..Except Handling Exceptions Raising Exceptions How To Raise Exceptions Try..Finally Using Finally Summary 14. The Python Standard Library Introduction The sys module Command Line Arguments More sys The os module Summary 15. More Python Special Methods Single Statement Blocks List Comprehension Using List Comprehensions Receiving Tuples and Lists in Functions Lambda Forms Using Lambda Forms The exec and eval statements The assert statement The repr function Summary 16. What Next? Graphical Software Summary of GUI Tools Explore More Summary A. Free/Libré and Open Source Software (FLOSS) B. About Colophon About the Author C. Revision History Timestamp
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值