- Python使用def(define)命令来创建一个函数(不要忘记后面的分号);
- 函数里的变量和脚本里的变量之间是没有联系的。
- 代码展示:
def chess_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 ("Man that's enough for a party!")
print ("Get a blanket.\n")
print ("We can just give the function numbers directly:")
chess_and_crackers(20,30)
print ("Or,we can use variables from our script:")
amount_of_cheese = 10
amount_of_crackers = 50
chess_and_crackers(amount_of_cheese,amount_of_crackers)
print ("We can even do math inside too:")
chess_and_crackers(10+20,5+6)
print ("And we can combine the two,variables and math:")
chess_and_crackers(amount_of_cheese+100,amount_of_crackers+1000)
- seek() 方法用于移动文件读取指针到指定位置。文件名.seek(0)就回到了文件的开始。
- 函数运算实例:
def add(a,b): print ("ADDING %d + %d" % (a,b)) return a + b def sub(a,b): print ("SUBTRACTING %d - %d" %(a,b)) return a - b def mul(a,b): print ("MULTIPLYING %d * %d" % (a,b)) return a * b def div(a,b): print ("DIVIDING %d / %d" % (a,b)) return a / b print ("Let's do some math with just functions!") age = add(30,5) height = sub(78,4) weight = mul (90,2) iq = div(100,2) print ("Age: %d,Height: %d,Weight: %d,IQ: %d" %(age,height,weight,iq)) print ("Here is a puzzle.") what = add(age,sub(height,mul(weight,div(iq,2)))) print ("That becomes:",what,"Can you do it by hand?")
- input输入自定义的值:输入整数时: int(input()) 输入浮点数时可以float(input())
- 代码示练习:
def break_words(stuff):
"""This function will break up words for us."""
words = stuff.split(' ') #split()函数对字符串进行格式的分割
return words
def sort_words(words):
"""Sorted the words."""
return sorted(words) #sorted()函数对字符串进行排序
def print_first_word(words):
"""Prints the first word after popping it off."""
word = words.pop(0) #pop(0) 输出第一个字符串
print word
def print_last_word(words):
"""Print the last word after popping it off."""
word = words.pop(-1) #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):
"""Prints the first and 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)
终端代码:
deng@deng-virtual-machine:~/python$ python
Python 2.7.12 (default, Dec 4 2017, 14:50:18)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import a #注意:import之后不需要加.py
>>> sentence = "All good things come to those who wait."
>>> words = a.break_words(sentence)
>>> words
['All', 'good', 'things', 'come', 'to', 'those', 'who', 'wait.']
>>> sorted_words = ex25.sort_words(words)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'ex25' is not defined
>>> sorted_words = a.sort_words(words) #调用函数
>>> sorted_sords
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'sorted_sords' is not defined
>>> sorted_words
['All', 'come', 'good', 'things', 'those', 'to', 'wait.', 'who']
>>> a.print_first_word(words)
All
>>> a.print_last_word(words)
wait.
>>> words
['good', 'things', 'come', 'to', 'those', 'who']
>>> a.print_first_word(words)
good
>>> a.print_first_word(sorted_words)
All
>>> a.print_last_word(sorted_words)
who
>>> sorted_words
['come', 'good', 'things', 'those', 'to', 'wait.']
>>> sorted_words = a.sort_sentence (sentence)
>>> sorted_words
['All', 'come', 'good', 'things', 'those', 'to', 'wait.', 'who']
>>> a.print_first_and_last(sentence)
All
wait.
>>> a.print_first_and_last_sorted(sentence)
All
Who
- Python规则里,只要一行以冒号(:)结尾,它接下来的内容就应该有缩进。
- Quit()退出python环境
- Python3中range()函数实例(均是左闭右开,即range()函数会从第一个数到最后一个数,但不包含最后一个数):
实例
>>>range(5)
range(0, 5)
>>> for i in range(5):
... print(i)
...
0
1
2
3
4
>>> list(range(5))
[0, 1, 2, 3, 4]
>>> list(range(0)) []
>>>
有两个参数或三个参数的情况(第二种构造方法)::
>>>list(range(0, 30, 5))
[0, 5, 10, 15, 20, 25]
>>> list(range(0, 10, 2))
[0, 2, 4, 6, 8]
>>> list(range(0, -10, -1))
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
>>> list(range(1, 0))
[]
>>>
- Python包含以下函数:
序号 函数
1 len(list)
列表元素个数
2 max(list)
返回列表元素最大值
3 min(list)
返回列表元素最小值
4 list(seq)
将元组转换为列表
Python包含以下方法:
序号 方法
1 list.append(obj)
在列表末尾添加新的对象
2 list.count(obj)
统计某个元素在列表中出现的次数
3 list.extend(seq)
在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)
4 list.index(obj)
从列表中找出某个值第一个匹配项的索引位置
5 list.insert(index, obj)
将对象插入列表
6 list.pop([index=-1]])
移除列表中的一个元素(默认最后一个元素),并且返回该元素的值
7 list.remove(obj)
移除列表中某个值的第一个匹配项
8 list.reverse()
反向列表中元素
9 list.sort(cmp=None, key=None, reverse=False)
对原列表进行排序
10 list.clear()
清空列表
11 list.copy()
复制列表
- 习题35 小游戏:
from sys import exit
def gold_room():
print ("This room is full of gold.How much do you take?")
next=input("> ")
if "0" in next or "1" in next:
how_much = int (next)
else:
dead("Man,learn to type a number.")
if how_much < 50:
print ("Nice,you're not ready,you win.")
exit(0)
else:
dead("You greedy bastared.")
def bear_room():
print ("There is a bear here.")
print ("The bear has a bunch of honey.")
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 = input("> ")
if next == "take honey":
dead("The bear looks at you then slaps 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:
dead("The bear gets pissed off and chews your leg off.")
elif next == "open door" and bear_moved:
gold_room()
else:
print ("I got not 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 = input("> ")
if "flee" in next:
start()
elif "head" in next:
dead("Well that was tasty!")
else:
cthulhu_room()
def dead(why):
print (why,"Good job!")
exit(0)
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 = input("> ")
if next == "left":
bear_room()
elif next == "right":
cthulhu_room()
else:
dead("You stumble around the room until you starve.")
start()