笨方法学python,Lesson 24, 25

Exercise 24python

代码函数

print "Let's practice everything."
print 'You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs.'

poem = '''
\tThe lovely world
with logic so firmly planted
cannot discern \n the needs of love
nor comprehend passion from intuition
and requires an explanation
\n\t\twhere there is none.
'''

print "--------------"
print poem 
print "--------------"


five = 10 - 2 + 3 - 6
print "This should be five: %s" % five

def secret_formula(started):
    jelly_beans = started * 500
    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 = start_point / 10

print "We can also do that this way:"
print "We'd have %d beans,%d jars,and %d crates." % secret_formula(start_point)

输出ui

Notes:this

对之前内容的汇总、复习google

Exercise 25
code

代码orm

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 word after poping it off.'''
	word = words.pop(0)
	print word
	
def print_last_word(words):
	'''Prints the last word after poping it.'''
	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):
	'''Prints 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 and prints the first and last one.'''
	words = sort_sentence(sentence)
	print_first_word(words)
	print_last_word(words)

输出对象

Notes:排序

①字符串的split()方法以给定的字符对字符串进行分割,并返回分割后的字符串组成的列表,且分割后的字符串能够解包索引

语法:string.split(str,num)

其中,str是分割符,默认是空格,不能为空;num是指将字符串分割成n+1项,省略时默认为最大分割次数。

>>> string = "
>>> string.split()
['
>>> string.split('.')
 ['www', 'google', 'com']
>>> string.split('.',1)
['www', 'google.com']

②内建函数sorted(),对列表、元组和字符串进行排序,但不改变原对象内容。对字符串排序后返回一个列表。

>>> sorted(string)
['.', '.', 'c', 'e', 'g', 'g', 'l', 'm', 'o', 'o', 'o', 'w', 'w', 'w']

③列表的pop()方法删除指定位置的元素并返回该元素。不指定索引值时默认删除最后一个元素

>>> a_list = [1, 2, 3]
>>> a_list.pop(0)
1
>>> a_list.pop()
3
>>> a_list
[2]

④函数体、模块开头三引号标记起来的字符串属于文档字符串,用于提示用户该模块、函数的用途。可用help()命令查看

相关文章
相关标签/搜索