第25个python程序

来源:互联网 发布:php api接口开发规范 编辑:程序博客网 时间:2024/05/22 03:17
[root@mysql1 pshell]# cat ex25.py
#!/usr/bin/env Python
#-*-coding:utf-8-*-


def break_words(stuff):
  """this function will break up words for us."""
  words=stuff.split(' ')
  return words


def sort_words(words):
  """sorts the word."""
  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)





[root@mysql1 pshell]# python
Python 2.6.6 (r266:84292, Jan 22 2014, 01:49:05) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import ex25.py
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named py
>>> import ex25
>>> sentence="all good things come to those who wait."
>>> words=ex25.break_words(sentence)
>>> words
['all', 'good', 'things', 'come', 'to', 'those', 'who', 'wait.']
>>> sorted_words=ex25.sort_words(words)
>>> sorted_words
['all', 'come', 'good', 'things', 'those', 'to', 'wait.', 'who']
>>> ex25.print_first_words(words)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'print_first_words'
>>> ex25.print_first_word(words) 
all
>>> ex25.print_last_word(words)
wait.
>>> words
['good', 'things', 'come', 'to', 'those', 'who']
>>> ex25.print_first_word(sorted_words)
all
>>> ex25.print_last_word(sorted_words)
who
>>> sorted_words
['come', 'good', 'things', 'those', 'to', 'wait.']
>>> sorted_words=ex25.sort_sentence(sentence)
>>> sorted_words
['all', 'come', 'good', 'things', 'those', 'to', 'wait.', 'who']
>>> ex25.print_first_and_last(sentence)
all
wait.
>>> ex25.print_first_and_last_sorted(sentence)
all
who
>>> ^D
  File "<stdin>", line 1
    ^D
    ^
SyntaxError: invalid syntax
>>> 
KeyboardInterrupt
>>> quit
Use quit() or Ctrl-D (i.e. EOF) to exit
>>> 
>>> 

0 0
原创粉丝点击