01/10/2018, 00:24

Tại sao lại sai hay do python 3 có thay đỗi về pop()?

# -*- coding: utf-8 -*-

def break_words(stuff):
    """This fuction wil break up words"""
    words = stuff.split(' ')
    return words

def sort_word(words):
    """Sort the words."""
    return sorted(words)

def print_first_word(words):
    """Print the first word after poppin it off. """
    word = words.pop(0)
    print (word)

def print_last_word(words):
    """Print the last word after poppin 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)
    print_first_word(words)
    print_last_word(words)
def print_first_and_last(sentence):
    words = break_words(sentence)
    print_first_word(words)
    print_last_word(words)

def print_first_and_last_sorted(sentence):
    """soted words."""
    words = sort_sentence(sentence)
    print_first_word(words)
    print_last_word(words)

Cho mình hỏi tại sao khi chạy theo bài 25 (Learn Python the Hard Way) tới lệnh cuối cùng thì nó lại báo lỗi là:

  File "<stdin>", line 1, in <module>
  File "/root/Desktop/Workstation/ex.py", line 37, in print_first_and_last_sorted
    print_first_word(words)
  File "/root/Desktop/Workstation/ex.py", line 15, in print_first_word
    word = words.pop(0)
AttributeError: 'NoneType' object has no attribute 'pop'

Mình kiểm tra lại toàn bồ code thì thấy nó đúng ? Mong mọi người giúp cám ơn

*grab popcorn* viết 02:31 ngày 01/10/2018

Mình nghĩ do bạn sai đó

words = sort_sentence(sentence)

#sort_sentence ko có trả về. Trong python ko trả về auto trả về NoneType
#-> words là NoneType

def sort_sentence(sentence):
    """Takes in a full sentence and returns the sorted words. """
    words = break_words(sentence)
    print_first_word(words)
    print_last_word(words)

-> NoneType ko có method pop nên nó đã báo lỗi như trên.[quote=“Th3J0k3r, post:1, topic:36663”]
AttributeError: ‘NoneType’ object has no attribute ‘pop’
[/quote]

Tuyết Liên Hoa viết 02:39 ngày 01/10/2018

Mình chạy có sai đâu nhỉ?

Bài liên quan
0