1

我是初学者程序员。我正在尝试编写一个程序来询问一个句子,然后检查两件事。1) 句首的大写字母和 2) 句尾的句号。我还希望它打印出一个句子,告诉用户他们的句子是否正确。例如:

输入一句话: python很难。

你的句子不是以大写字母开头。

输入一句话: Python很难

你的句子结尾没有句号。

输入一句话: python很难

你的句子不是以大写字母开头,结尾也没有句号。

最后;

输入一句话: Python很难。

你的句子很完美。

但是,我被困住了,我所拥有的只是这个烂摊子:

sentence = input("Sentence: ")
if sentence[0].isupper():
  print("")
if (sentence[0].isupper()) != sentence:
  print("Your sentence does not start with a capital letter.")
elif "." not in sentence:
  print("Your sentence does not end with a full stop.")
else:
  print("Your sentence is correctly formatted.")

任何帮助将不胜感激。

4

3 回答 3

2

尝试这个:

sentence = input('Sentence: ') # You should use raw_input if it is python 2.7
if not sentence[0].isupper() and sentence[-1] != '.': # You can check the last character using sentence[-1]
    # both the conditions are not satisfied
    print 'Your sentence does not start with a capital letter and has no full stop at the end.'
elif not sentence[0].isupper():
    # sentence does not start with a capital letter
    print 'Your sentence does not start with a capital letter.'
elif sentence[-1] != '.':
    # sentence does not end with a full stop
    print 'Your sentence does not end with a full stop.'
else:
    # sentence is perfect
    print 'Your sentence is perfect.'
于 2014-02-26T09:57:23.003 回答
1

这有点模块化,因为您可以针对各种错误消息对其进行修改。

se = "Python is easy"
errors = []
if not se[0].isupper(): errors.append('does not start with a capital letter')
if se[-1] != '.': errors.append('does not end with a full stop')
if errors != []:
   print('Your sentence ' + ' and '.join(errors) + '.')
else:
   print('Your sentence is perfect.')
于 2014-02-26T10:05:59.183 回答
0
se="Python is easy"
if se[0].isupper() and se[-1]=='.':
   print 'ok'
else:
   print 'Not ok'

更新 :

您可以使用strip函数在字符串的开头和结尾删除不必要的空格。

se="Python is hard."
se=se.strip()
if se[0].isupper():
    if se[-1]=='.':
        print 'Your sentence is correctly formatted.'
    else:
        print 'Your sentence has no full stop at the end.'
elif se[0].islower() and se[-1]!='.':
    print 'Your sentence doesnt start with a capital letter and has no full stop at the end.'
else:
    print 'Your sentence does not start with a capital letter.'
于 2014-02-26T09:56:33.047 回答