Программа, проверяющая заглавные буквы и точку

Я начинающий программист. Я пытаюсь написать программу, которая запросит предложение, а затем проверит 2 вещи. 1) Заглавная буква в начале предложения и 2) точка в конце. Я также хочу, чтобы он распечатал предложение, которое сообщит пользователю, правильно ли его предложение. Например:

Введите предложение: 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.")

Любая помощь будет принята с благодарностью.


person Community    schedule 26.02.2014    source источник
comment
Python is hard.? Ваша фраза неверна... :p   -  person thefourtheye    schedule 26.02.2014


Ответы (3)


Попробуй это:

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.'
person Jayanth Koushik    schedule 26.02.2014
comment
Оператор отрицания в Python — not вместо !. Вы на самом деле получаете синтаксическую ошибку. - person gry; 26.02.2014

Это немного более модульно, потому что вы можете модифицировать его для различных сообщений об ошибках.

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.')
person deufeufeu    schedule 26.02.2014
comment
Поскольку пустой список будет оцениваться как False в логическом контексте, вы можете просто написать if errors: - person gry; 26.02.2014

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.'
person Nishant Nawarkhede    schedule 26.02.2014
comment
Это не желаемый результат. - person Jayanth Koushik; 26.02.2014