01/10/2018, 15:41
Cần giúp đỡ code Learn Python the hard way - Bài 25
=======================================================================================================
def break_words(stuff):
"""This function will break up words for us."""
words = stuff.split(' ')
return words
def sort_words(words):
"""Sort the words."""
return sorted(words)
def print_first_word(words):
"""Prints he 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 senten."""
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)
================================================================================================================================================================
Mình đang học python bài 25 “Learn python the hard way” của anh Lê trần đạt. mình có nghi vấn ở đoạn c ode cuối chưa hiểu cho lắm.
Đoạn code này :
def print_first_and_last(sentence):
"""Prints the first and last words of the senten."""
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)
================================================================================================================================================================
Vì do mình nhập vào sentence như bài thì anh đạt có nói và cũng như đoạn code là
hàm print_first_word() và print_last_word() sẽ .pop() 1 phần tử của nó
nhưng với 2 hàm cuối
print_first_and_last(sentence) và print_first_and_last_sorted(sentence) thì lại không .pop() phần tử nào cả mà vẫn giữ nguyên cả câu
Bài liên quan
À em hiểu vấn đề rồi. Cám ơn các anh đã chỉnh hộ em title và bài viết. Lần đầu em đăng bài nên còn sai sót :D.
Vì do cái variable hay là “argument thì phải” (sentence) nó chưa được bóc tách từng từ ra thành list() nên python có thể nó sẽ hiểu đây là 1 giá trị. Nếu nó được tách ra thành nhiều từ để tạo lên list() thì nó sẽ thành 1 biến mới có nhiều giá trị bên trong. Do python nó báo lỗi em về list() nên mới để ý