Start New Discussion within our Software Development Community

Here is exercise in error handling, while looping and for looping with itertools.chain.
It is also exercise of functions not letting user to go without giving proper input. I call them to myself 'jail functions'.

Here you could add as an exercise breaking out of loop and continuing until user request to quit.

The code works in both Python2 and Python3 with Python2 input overwritten to be raw_input.

import itertools

""" Change Python2 input to Python3 style """
try:
    input = raw_input
except NameError:
    pass


def get_int(prompt, min=None, max=None):
    """ Do not leave until correct integer is inputted """
    while True:
        try:
            limits = ''
            if min:
                limits = '%s..' % min
                if max:
                    limits += str(max)
            elif max:
                limits = ' < %i' % max
            a = int(input('%s (%s): ' % (prompt, limits)))
            if ((not min or a >= min) and
                (not max or a <= max)):
                return a
            else:
                print('Entered value was not in correct range! Try again!')
        except ValueError:
            print('Need to input integer')

def get_char(prompt, num=None):
    """ Do not leave until correct number of characters is inputted """
    a = ''
    while len(a) != num:
        a = input(prompt + ': ')
        if not num or len(a) == num:
            return a
        print('Give exactly %i character%s' % (num, '' if num == 1 else 's'))


if __name__ == '__main__':
     length = get_int('Give maximum width of the figure', min=2, max=80)
     symbol = get_char('Give symbols to use')
     for line_length in itertools.chain(range(1, length + 1), range(length - 1, 0, -1)):
         print((line_length * symbol)[:line_length])


"""Output example:
Give maximum width of the figure (2..80): 0
Entered value was not in correct range! Try again!
Give maximum width of the figure (2..80): 80.1
Need to input integer
Give maximum width of the figure (2..80): 23
Give symbols to use: DaniWeb tonyjv 
D
Da
Dan
Dani
DaniW
DaniWe
DaniWeb
DaniWeb 
DaniWeb t
DaniWeb to
DaniWeb ton
DaniWeb tony
DaniWeb tonyj
DaniWeb tonyjv
DaniWeb tonyjv 
DaniWeb tonyjv D
DaniWeb tonyjv Da
DaniWeb tonyjv Dan
DaniWeb tonyjv Dani
DaniWeb tonyjv DaniW
DaniWeb tonyjv DaniWe
DaniWeb tonyjv DaniWeb
DaniWeb tonyjv DaniWeb 
DaniWeb tonyjv DaniWeb t
DaniWeb tonyjv DaniWeb
DaniWeb tonyjv DaniWe
DaniWeb tonyjv DaniW
DaniWeb tonyjv Dani
DaniWeb tonyjv Dan
DaniWeb tonyjv Da
DaniWeb tonyjv D
DaniWeb tonyjv 
DaniWeb tonyjv
DaniWeb tonyj
DaniWeb tony
DaniWeb ton
DaniWeb to
DaniWeb t
DaniWeb 
DaniWeb
DaniWe
DaniW
Dani
Dan
Da
D
"""

Specialties:
IT/Science/Contracts/Religious translation/interpreting FIN-ENG-FIN
Python programming

The article starter has earned a lot of community kudos, and such articles offer a bounty for quality replies.