八 命名、变量、代码、函数
从本节开始 所有注意事项都以注释的形式显示
ex18
# -- coding: utf-8 --
def print_two(*args):#命名函数 括号中*的作用是以*开头,可以传多个参数 但是不能使用重复的参数名
arg1,arg2 = args
print"arg1:%r,arg2:%r"%(arg1,arg2)#这是函数的内容 第一行是给参数解包 要使用缩进
def print_two_again(arg1,arg2):
print"arg1:%r,arg2:%r"%(arg1,arg2)
def print_one(arg1):
print"arg1:%r"%arg1
def print_none():
print"I got nothin',"
#函数命名规则和变量规则一样
print_two("Zed","Shaw")
print_two_again("Zed","Shaw")
print_one("First!")
print_none()
#运行调用使用函数是同一个意思
ex19
# -- coding: utf-8 --
def cheese_and_crackers(cheese_count,boxes_of_crackers):
print"You have %d cheeses!"% cheese_count
print"You have %d boxes of crackers"% boxes_of_crackers
print"Msn than's enough for a party!"
print"Get a blanket.\n"
#函数命名 函数内容
#a = int(raw_input())
#b = int(raw_input())
#cheese_and_crackers(a,b)这是函数变量变为可输入值的尝试 同时 我们可以知道 变量在函数的名字也可以更换
print "we can just give the function numbers directly:"
cheese_and_crackers(20,30)
#赋值
print"OR,we can use variables from our script:"
amount_of_cheese = 10
amount_of_crackers = 50
cheese_and_crackers(amount_of_cheese,amount_of_crackers)
#赋值 函数可以执行已经赋值的变量
print"We can even do math inside,too!"
cheese_and_crackers(10+20,5+6)
#赋值 函数可以执行需要运算的变量
print"And we can combine the two,variables and math:"
cheese_and_crackers(amount_of_cheese + 100,amount_of_crackers + 1000)
#赋值 函数可以执行需要运算并且已经赋值的变量
ex20
# -- coding: utf-8 --
from sys import argv # 依然调用argv
script, file_name = argv # 解包变量argv
def print_all(f): # 定义函数。
print f.read() # 函数功能:打印文本内容。
def rewind(f): # 定义函数。 f为变量
f.seek(0) # 函数功能:回到文本的初始位置
# seek(n)从文件的第n位开始读
def print_a_line(line_count,f): # 定义函数.
print line_count,f.readline()# 打印文本行号,并打印该行的内容 同时继续打印的起点移动到下一行起点 也就是这一行的\n后面
current_file = open(file_name) # 打开 file_name 并赋值给 current_file
print_all(current_file) # 打印文本内容
print"Now let's rewind, kind of like a tape."
rewind(current_file) # 回到文本的初始位置. 这一步很重要 否则文件之后分行打印出来的起点是刚才打印文件内容的终点的后一位
print"Let's print three lines:"
current_line = 1
print_a_line(current_line,current_file) #调用函数 print本身会加一个\n 而readline函数又加了一个 所以变成了隔行打印
current_line +=1#Python里没有C语言那种i++之类的表示方式 最简便的就是这种i+=1 意为i=i+1
print_a_line(current_line,current_file) #调用函数
current_line +=1
print_a_line(current_line, current_file) #调用函数
ex21
# -- coding: utf-8 --
def add(a,b):
print"ADDING %d +%d"%(a,b)
return a + b#返回的值就是函数计算的结果
def substract(a,b):
print"SUBSTRACTING %d -%d"%(a,b)
return a - b
def multiply(a,b):
print"MULTIPLYING %d * %d"%(a,b)
return a * b
def divide(a,b):
print"DEVIDE %d / %d"%(a,b)
return a / b
print"Let's do some math with just functions!"
age = add(30,5)
height = substract(78,4)
weight = multiply(90,2)
iq = divide(100,2)
print"Age:%d,Height:%d,Weight:%d,IQ:%d"% (age,height,weight,iq)
print"Here's a puzzle"
what = add(age,substract(height,multiply(weight,divide(iq,2))))#通过打印顺序看的出来这一步自内而外 逐步执行
print"That becomes:",what,"Can you do it by hand?"
ex24(算是对之前内容的回顾与总结)
# -- coding: utf-8 --
print"Let's practice everything."
print'you\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs.'#\'或者\\都是转义\后面的那个符号 \t是缩进 \n是换行
poem = """
\tThe lovely world
with logic so firmly planted
cannot discern \n the needs of love
nor comprehend passion from intution
and requires an explanation
\n\t\twhere there is none.
"""
#转义字符同上 同时""" """内所有的可直接被打印出来
print"-------------"
print poem
print"-------------"
five = 10 - 2 + 3 - 6
print"This shuold be five:%d" % five#占位符
def secret_formula(started):#定义函数
jelly_beans = started * 50
jars = jelly_beans / 1000
crates = jars / 100#函数内容
return jelly_beans,jars,crates#返回函数运算结果
start_point = 10000#给函数即将操作的参数赋值
beans,jars,crates = secret_formula(start_point)#将这三个新变量依次赋予此前函数返回的值
print"With a starting point of : %d"% start_point
print"We'd have %d beans,%d jars,and %d crates."%(beans,jars,crates)
start_point/=10
print"We can do it this way:"
print"We'd have %d beans,%d jars,and %d crates."%secret_formula(start_point)
#这时该函数return的一组数按顺序依次补进去 但是返回值的个数与占位符必须一一对应
ex25
通过这个练习我们对import的原理有了很好的理解
# -- coding: utf-8 --
def break_words(stuff):
"""This function will break up words for us."""
words = stuff.split(' ')#将字符串切片 形成一个列表
return words
def sort_words(words):
"""Sorts the words."""
return sorted(words)#将列表排序
def print_first_word(words):
"""Prints the first words after popping it off."""
word = words.pop(0)#列表的第一位
#•pop() :list.pop(obj=list[-1]),obj -- 可选参数,要移除列表元素的对象,用于移除列表中的一个元素(默认最后一个元素),并且返回该元素的值,另外,右边为正
print word
def print_last_word(words):
"""Prints the last words after popping it off."""
word = words.pop(-1)#列表的最后一位
print word
def sort_sentence(sentence):
"""Takes in a full sentence and returns the sorted words."""
words = break_words(sentence)
return sort_words(words)
def print_first_and_last(sentence):
"""Print the first and the last words of the sentence"""
words = break_words(sentence)
print_first_word(words)
print_last_word(words)
def print_first_and_last_sorted(sentence):
"""Sorts the words then prints the first and last one"""
words = sort_sentence(sentence)
print_first_word(words)
print_last_word(words)
#接下来的是如何使用ex25.py
#我们会看到不停地ex25.xxx烦得很 可以直接from ex25 import* 没错 我们正在把ex25.py作为一个moudule引用 这样直接调用函数就好
#执行help(ex25)可以打开帮助文档 即为"""内的东西 也可以更具体的打开帮助文档 比如 help(ex25.break_words)
#以下为powershell里运行过程 由于过程繁冗 就不截图演示了 直接附在这代码块的下面
#PS C:\Users\Administrator\desktop\py2> py -2
#Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:53:40) [MSC v.1500 64 bit (AMD64)] on win32
#Type "help", "copyright", "credits" or "license" for more information.
#>>> import ex25
#>>> sentence = "all good things come to those who wait"
#>>> words = ex25.break_words(sentence)
#>>> words
#['all', 'good', 'things', 'come', 'to', 'those', 'who', 'wait']
#>>> sorted_words = ex25.sort_words(words)
#>>> sorted_words
#['all', 'come', 'good', 'things', 'those', 'to', 'wait', 'who']
#>>> ex25.print_first_word(words)
#all
#>>> ex25.print_last_word(words)
#wait
#>>> words
#['good', 'things', 'come', 'to', 'those', 'who']
#>>> ex25.print_first_word(sorted_words)
#all
#>>> ex25.print_last_word(sorted_words)
#who
#>>> sorted_words
#['come', 'good', 'things', 'those', 'to', 'wait']
#>>> sorted_words = ex25.sort_sentence(sentence)
#>>> sorted_words
#['all', 'come', 'good', 'things', 'those', 'to', 'wait', 'who']
#>>> ex25.print_first_and_last(sentence)
#all
#wait
#>>> ex25.print_first_and_sorted(sentence)
#>>> ex25.print_first_and_last_sorted(sentence)
#all
#who
九 循环 列表 和分支
ex29
people = 20
cats = 30
dogs = 15
if people < cats:
print"Too many cats! The world is doomed!"
if people > cats:
print"Not mant cats! The world is saved!"
if people < dogs:
print"The world is drooled on!"
if people > dogs:
print"The world is dry!"
dogs+=5
if people <= dogs:
print"People are greater than or equal to dogs"
if people >= dogs:
print"People are less than or equal to dogs"
if people == dogs:
print"People are dogs."
#实在很简单 只有一个+=注意一下 x+=1等价于x=x+1
ex30
# -- coding: utf-8 --
people = 30
cars = 40
buses = 15
if cars > people:
print"We should take the cars."
elif cars < people:
print"We should not take the cars."
else:
print"We can't decide."
if buses > cars:
print"That's too many buses."
elif buses < cars:
print"Maybe we should take the buses."
else:
print"We still can't decide."
if people > buses:
print"Alright, let's just take the buses."
else:
print"Fine, let's stay at home then."
#若多个elif条件都为真 只处理第一个
ex31
# -- coding: utf-8 --
print"You enter a dark roomm with two doors. Do you go through door #1 or #2 ?"
door = raw_input(">")
if door == "1":
print"There's a giant bear here eating a cheese cake .What do you do?"
print"1.Take the cake."
print"2.Scream at the bear."
bear = raw_input(">")
if bear == "1":
print"The bear eats your face off. Good job!"
elif bear == "2":
print"The bear eats your legs off. Good job!"
else:
print"Well, doing %s is probably better`. Bear runs away." % bear
elif door=="2":
print"You stare into the endless abyss at Cthulhu's retina."
print"1.Blueberries"
print"2.Yellow jacket clorthespins"
print"3.Understanding revolvers yelling melodies"
insanity = raw_input(">")
if insanity == "1" or insanity == "2":
print"Your body survives powered by a mind of jello. Good job!"
else:
print"The insanity rots your eyes into a pool of muck . Good job!"
else:
print"You stumble around and fall on a knife and die. Good job"
ex32
# -- coding: utf-8 --
the_count = [1,2,3,4,5]
fruits = ['apples','oranges','pears','apricots']
change = [1,'pennies',2,'dimes',3,'quarters']
# this first kind of for-loop goes through a list
for number in the_count:#fruit变量在这句被定义 下同
print"This is count %d "% number
# same as above
for fruit in fruits:
print"A fruit of type: %s "% fruit
# also we can go througe list too
# notice we have to use %r since we don't know what's in items
for i in change:
print"I got %r " % i
#s%也可以 但是无法看出这里的数字是整数还是字符串
#we can also build lists,first start with an empty one
elements = []
#then use the range function to do 0 to 5 counts
for i in range(0,6):#range函数(a,b)指的是范围为a到b-1的所有整数(只能是整数)
print"Adding %d to the list" % i
#apprng is a function that lists understand
elements.append(i)#在列表尾部追加元素
#now we can print them out too
for i in elements:
print"Elements was : %d" % i
#二维列表 举个例子 [[1,2,3],[4,5,6]]在Python 列表和数组都被叫做列表
ex33
# -- coding: utf-8 --
i = 0
numbers = []
#用for循环和range函数解决 不用自增
b = int(raw_input(">"))
for a in range (0,b):
numbers.append(a)
print "Numbers now:",numbers
for a in numbers:
print a
#用函数解决
def abc(i):
while i < j:
print"At the top i is %d." % i
numbers.append(i)
i+=1
print"Numbers now:",numbers
print"At the bottom i is %d " % i
j = raw_input(">")#这里必须有int()否则会一直循环 raw_input()默认输入的是str,需要强制转换
#一直循环的原因:
#不同类型的对象(实例),如果其中一个比较对象是数字型(int/float/long/complex等),则数字型的对象<其它非数字型的对象;
#如果两个都是非数字型的对象,则按照类型名的顺序比较,如{} < "abc"(按照"dict" < "str"),而"abc" > [1,2], "abc" < (1,2)。
abc(i)
for num in numbers:
print num
如果没有限制为int类型 会出现如下情况
无限循环下去(真让人头大23333)
ex35
# -- coding: utf-8 --
from sys import exit
def gold_room():
print"This room is full of gold .How much do you take?"
next = raw_input(">")
if "0" in next or "1" in next:
how_much = int(next)
#这里有一个bug 如果你输入的数字里没有1或0那么程序认为你没有输入数字 解决方法如下(都是借鉴别人想法 )
#方法一
# choice = raw_input("> ")
#if int(choice) / int(choice) == 1:
# how_much = int(choice)
# how_much = int(next)
#方法二(针对整形)
#if next.isdigit():
# how_much = int(next)
#str为字符串
#str.isalnum() 所有字符都是数字或者字母
#str.isalpha() 所有字符都是字母
#str.isdigit() 所有字符都是数字 这里用的就是这个
#str.islower() 所有字符都是小写
#str.isupper() 所有字符都是大写
#str.istitle() 所有单词都是首字母大写,像标题
#str.isspace() 所有字符都是空白字符、\t、\n、\r
else:
dead("Man,learn to type a number.")
if how_much < 50:
print"Nice, you're not greedy,you win!"
exit(0)
else:
dead("Your greedy bastard!")
def bear_room():
print"There is a bear here."
print"The bear has a bunch of money."
print"The fat bear is in front of another door."
print"How are you going to move the bear?"
bear_moved = False
while True:#开始无限循环
next = raw_input(">")
if next == "take honey":
dead("The bearlooks at you then salps your face off.")
elif next == "taunt bear" and not bear_moved:#两个条件同时为真
print"The bear has moved from the door. You can go through it now."
bear_moved = True
elif next == "taunt bear" and bear_moved:#若能执行这个条件说明第一个taunt bear一定执行了 则bear_moved 为true 两个条件同时为真
dead("The bear gets pissed off and chews your leg off.")
elif next == "open door" and bear_moved:#此时如果前面taunt bear 的操作执行了 则bear_moved 为true 两个条件仍同时为真
gold_room()
else:
print "I got no idea what that means"
def cthulhu_room():
print"Here you see the great evil Cthulhu."
print"He,it,whatever stares at you and you go insane."
print"Do you flee for your life or eat your head?"
next = raw_input(">")
if "flee" in next:
start()
elif"head" in text:
dead("Well thar tasty!")
else:
cthulhu_room()
def dead(why):
print why,"Good job!"
exit(0)
#exit(0) 表示程序正常退出,exit(1)/exit(-1)表示程序异常退出。
def start():
print"You are in a dark room"
print"There is a door to your right and left."
print"Which one do you take?"
next = raw_input(">")
if next == "left":
bear_room()
elif next == "right":
cthulhu_room()
else:
dead("You stumble around the room until you starve.")
start()
路线图如下
十 列表进阶 字典
# -- coding: utf-8 --
ten_things = "Apples Oranges Crows Telephone Light Sugar"
print"Wait there 's not 10 things in that list,let's fix that."
stuff = ten_things.split(' ')#将元素用''隔开 生成列表
print stuff
more_stuff = ["Day","Night","Song","Frisbee","Corn","Banana","Girl","Boy"]
while len(stuff) != 10:
next_one = more_stuff.pop()#取出列表的最后一个元素并赋值
print"Adding :", next_one
stuff.append(next_one)
print "There 's %d items now." % len (stuff)#获取列表长度
print"There we go:" ,stuff
print"Let's do some things with stuff."
print stuff[0]#列表零号位的元素
print stuff[1]#列表一号位的元素
print stuff[-1]#列表最后一位元素
print stuff[-2]#列表倒数第二位元素
print stuff.pop()#列表最后一位元素
print ' '.join(stuff)#把列表的元素都输出 间隔为''里的内容
print '#'.join(stuff[3:8])#把列表中三号位到七号位(和range函数类似)的元素都输出 间隔为''里的内容
ex39
# -- coding: utf-8 --
#字典注意事项
#1,不允许同一个键出现两次。创建时如果同一个键被赋值两次,后一个值会被记住
#2,键必须不可变,所以可以用数字,字符串或元组充当,而用列表就不行
#create a mapping of state to abbreviation
states = {
'Oredon':'OR',
'Florida':'FL',
'California':'CA',
'New York':'NY',
'Michigan':'MI',
}
# create a basic set of states and some cities in them
cities = {
'CA':'San Francisco',
'MI':'Detroit',
'FL':'Jacksonbille'
}#创建两个字典
#add some more cities
cities['NY'] = 'New York'#字典内添加新的对应关系
cities['OR'] = 'Porland'
#字典内删除对应关系使用 del dict[key]
#print out some cities
print '-' * 10
print "NY State has:",cities['NY']
print "OR State has:",cities['OR']
# print some states
print '-' *10
print"Michigan's abbreviation is: ",states['Michigan']
print"Florida's abbreviation is: ",states['Florida']
# do it by using the states then cities dict
print '-' * 10
print"Michigan has:",cities[states['Michigan']]
print"Florida has:",cities[states['Florida']]
# print every state abberviation
print '-' * 10
for state ,abbrev in states.items():#这个函数的用法为以列表形式返回可遍历的(键, 值) 元组数组 我的理解就是把字典内的对应关系以列表形式返回
print"%s is abbreviated %s " % (state,abbrev)
#print evry city in state
print '-' * 10
for abbrev ,city in cities.items():
print"%s has the city %s" % (abbrev,city)
# now do both at the same time
print '-' * 10
for state,abbrev in states.items():
print"%s state is abbreviated %s and has city %s" % (state,abbrev,cities[abbrev])
print '-' * 10
# safely get a abbreviation by state that might not be here
state = states.get('Texas',None) #此处返回的state值为False
#get函数 dict.get(key, default=None) 返回要查找的指定键(key)的值,如果值不在字典中返回默认值None,当然,后面这个值可以自定义
if not state:
print"Sorry , no Texas."
# get a city with a default values
city = cities.get('TX','Does Not Exit')
print"The city for the state 'TX' is : %s " % city
未完待续…