0

I've made a function that asks 3 questions to the user; taking into account the width, length and cost per tile ... which produces the total cost at the end of the function.

I want the function to go through the series of questions ensuring that the input is equal to an integer. However I do not want it to keep reverting back to the start of the questions.

eg.

If the user types in a string at 'What is the cost: '

I want it to re-ask THAT question and not to revert back to the first question in the series.

As the function is right now - it will keep returning to the first question of 'What is the width: ' if an integer is not entered.

"""
A function based on finding the cost of tiling a certain area; based 
on
width, length and the cost per tile
"""

def tile_cost():
while True:
    try:
        w = float(input('What is the width: '))
        l = float(input('What is the height: '))
        c = float(input('What is the cost: '))
    except ValueError:
        print('This is not an int')
        continue
    else:
        break

print("The cost of tiling the floor will be: £%.2f" % (w * l * c))


tile_cost()

I've tried multiple other ways of doing what i'm trying to achieve, but the codes gets messy and repeats itself and does not actually work for me. Having tried to search this for quite a while I've found it very difficult to find a definitive answer to the problem.

Thanks in advance for anyone's help, it will be massively helpful in understanding python further :)

DeltaCain
  • 1
  • 1
  • @cᴏʟᴅsᴘᴇᴇᴅ not sure about the dupe. The OP apparently knows how to repeatedly ask until the input is valid. He just wants to DRY out doing so repeatedly (repeatedly repeatedly so to speak). – user2390182 Jan 07 '18 at 17:49
  • @schwobaseggl I believe the part in `Encapsulating it All in a Function` is what OP is looking for (take a look). – cs95 Jan 07 '18 at 17:50
  • @cᴏʟᴅsᴘᴇᴇᴅ Agreed, while the question is about a problem this OP has solved, some of the answers there are helpful... – user2390182 Jan 07 '18 at 17:51
  • `Encapsulating it All in a Function` does achieve it, thankyou. I'd read over that question but did not understand that would apply to my situation. scwobseggl, you were correct with the removal of the while loop in tile_cost, thanks to that too. – DeltaCain Jan 07 '18 at 17:58

1 Answers1

0

You can separate number picker:

def pick_num(text):
    while True:
        try:
            a = float(input(text))
            return a
        except ValueError:
            print('This is not a number')



def tile_cost():
    w = pick_num('What is the width: ')
    l = pick_num('What is the height: ')
    c = pick_num('What is the cost: ')
    print("The cost of tiling the floor will be: £%.2f" % (w * l * c))
aiven
  • 3,775
  • 3
  • 27
  • 52