评估字符串输入以执行功能

时间:2017-12-17 16:47:21

标签: python-3.x

我制作了转换程序,用户输入与转换相对应的数字。例如。如果用户输入1,则代码执行千米到英里的转换。

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

我想这样做,如果用户输入25cm to inches,那么它将进行正确的转换

1 个答案:

答案 0 :(得分:1)

输入验证是一件棘手的事情,因为有很多可能的方法来破坏输入错误的代码。好的代码需要考虑所有可能出错的方法。对于特定用例,当所需输入为" 25cm到英寸"或者您可以使用python regex模块和命名组来提取相关字段。下面给出一个例子。你应该把它放在try除了块之外,这样如果没有找到匹配,那么它会再次提示用户或突破它。这只是一个很小的例子。字典fields包含在另一个转换器函数中使用的相关信息。

#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