01/10/2018, 10:20
Hàm trong python
mình đang học cuốn “Learn Python The Hard Ways” cho mình hỏi đoạn code nay o Exercise 25:
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 popping it off."""
word = words.pop(0)
print word
def print_last_word(words):
"""Prints the last word 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):
"""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)
Minh run theo huong dan cua anh Dat va sach:
$ python
Python 2.7.1 (r271:86832, Jun 16 2011, 16:59:05)
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
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)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'break_word'
Ma no cu loi hoai ai cho minh y kien khac phuc loi voi! Cam on!
Bài liên quan
break_word
khác so vớibreak_words
Cho mình hỏi xíu vẫn cái ở trên sao khi:
$ python
Python 2.7.1 (r271:86832, Jun 16 2011, 16:59:05)
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
Type “help”, “copyright”, “credits” or “license” for more information.
Bạn cho mình xem lỗi được không?
loi hoi nay minh sua duoc roi cam mon, ban cho minh hoi:
Để mình nói về việc
import
này trong Python một cách đơn giản nhấtVí dụ bạn có một
file a.py
split
là một phương thức giúp bạn tách các phần tử ra bằng các chuỗi Ví dụThế nên trong ví dụ của bạn hàm
break_words
là tách chữ nó sẽSau đó
return
về thìwords = ex25.break_words(sentence)
tương đương vớiwords = ['All', 'good', 'things', 'come', 'to', 'those', 'who', 'wait']
Về
sorted
thì nó sẽ sắp xếp các chữ cái theo thứ tự ‘abc’return
về thìsorted_words = ex25.sort_words(words)
thìsorted_words
sẽ nhận được một dãy sắp xếp như bạn tháayprint_first_word
là in chữ đầu tiên mà chữ đầu tiên là phần tử đầu tiên trong mảng. Phần tử đầu tiên trong mảng là[0]
. Let’s take a look at functionprint_first_word
Giải thích về
pop
.Thế nên
word = words.pop(0)
thìword
sẽ nhận cái chữ đượcpop
ra ở vị trí0
.print_last_word
hoạt động tương tự chỉ khác vị trí là-1
là vị trí cuối cùng để nói sơ qua về vị trímong là bạn hiểu