笨方法學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()命令查看

相關文章
相關標籤/搜索