Richard
Richard

Reputation: 29

Evaluating a string input to perform a function

I have made a conversion program where the user enters a number corresponding to the conversion. E.g. if the user enters 1 then the code performs the kilometres to miles conversion.

if choice == 1: km = float(input("Enter the amount of kilometres: ")) print(str(kmtomiles(km))+" miles")

I want to make this so if the user enters 25cm to inches then it will do the correct conversion

Upvotes: 0

Views: 40

Answers (1)

SigmaPiEpsilon
SigmaPiEpsilon

Reputation: 698

Input validation is a tricky thing since there are so many possible ways to break your code with bad input. Good code needs to consider all possible ways things can go wrong. For you specific use case when the desired input is "25cm to inches" or some variations of that you can use python regex module and named groups to extract the relevant fields. An example is given below. You should probably put this in a try except block so that if no match is found then it prompts user again or breaks out of it. This is only a minimal example to build on. The dictionary fields contains the relevant information to use in another converter function.

#input.py
import re

pattern = "(?P<num>[0-9]+)\s*(?P<current_unit>\w+) to (?P<desired_unit>\w+)"

while True:
        try:
            convert_string = input("What to you want to convert? (press(q) to quit): ")
            if convert_string == 'q' or convert_string == 'Q':
                break
            m = re.search(pattern, convert_string)
            fields = m.groupdict()
        except AttributeError:
            print("Sorry, invalid input, please try again(or enter q to quit): ")
            continue
        if convert_string == 'q' or convert_string == 'Q':
            break
        if fields is None:
            continue
        else:
            print("You want %(num)s %(current_unit)s to be converted to %(desired_unit)s" % fields)
            break

$ python3.4 input.py 
What to you want to convert? (press(q) to quit): 25cm to inches
You want 25 cm to be converted to inches
$ python3.4 input.py 
What to you want to convert? (press(q) to quit): 340lb to kgs
You want 340 lb to be converted to kgs
$ python3.4 input.py 
What to you want to convert? (press(q) to quit): lb to kgs
Sorry, invalid input, please try again(or enter q to quit): 
What to you want to convert? (press(q) to quit): q
$ python3.4 input.py 
What to you want to convert? (press(q) to quit): lb to kgs
Sorry, invalid input, please try again(or enter q to quit): 
What to you want to convert? (press(q) to quit): 240 lb to kgs            
You want 240 lb to be converted to kgs

Upvotes: 1

Related Questions