1. Write a program that displays the length of the string entered by the user, as well as the first, fifth, and last characters.

    a = input(str()) # НапримСр слово Javascript print(len(a), '=ΠžΠ±Ρ‰Π΅Π΅ количСство символов') print(a[0], '=ΠΏΠ΅Ρ€Π²Ρ‹ΠΉ', a[4], '=пятый', a[-1], '=послСдний') 

    It's all clear.

  2. Remember to consider the case when the length of the string is less than five characters.

     a = input(str()) # НапримСр слово Java print(len(a), '=ΠžΠ±Ρ‰Π΅Π΅ количСство символов') print(a[0], '=ΠΏΠ΅Ρ€Π²Ρ‹ΠΉ', a[4], '=пятый', a[-1], '=послСдний') 

    IndexError: string index out of range

Solution option design:

 a = input(str()) # НапримСр слово Java strlen = len(a) print(strlen, '=ΠžΠ±Ρ‰Π΅Π΅ количСство символов') if strlen > 5: five_element = a[4] else: five_element = 'Π‘Ρ‚Ρ€ΠΎΠΊΠ° ΠΊΠΎΡ€ΠΎΡ‡Π΅ 5 символов' print(a[0], '=ΠΏΠ΅Ρ€Π²Ρ‹ΠΉ', five_element, '=пятый', a[-1], '=послСдний') 

Options? cycle? and you can do without if?

  • Corrected, yes it is a design. - Dnpy

1 answer 1

You do not have a cycle, if is not a cycle. You have easier, but you can:

 try print(a[0], a[-1], a[4]) except IndexError: print("Π‘Ρ‚Ρ€ΠΎΠΊΠ° ΠΊΠΎΡ€ΠΎΡ‡Π΅ пяти символов") 
  • Your example will not display the first and last characters if the length is less than 5 characters. Your example also suggested that it would be nice to handle the case if the string is empty. - Jenyay
  • @Jenyay is just an alternative to if. You can handle all cases like this. - andy.37