尝试,除了在python中

时间:2015-10-16 22:09:35

标签: python

我正在尝试编写一个只读取两个符号(=,+)的简单程序。我使用上面的if块进行了检查:

x = raw_input("Please answer + or =")
if x == '+':
   print "plus" 
elif x == '=':
   print "equal"
else:
   print "not valid"

我想删除其他内容并使用try进行检查,除外。 例如,我想要像:

try:
   x = raw_input("Please answer + or =")
   if x == '+':
      print "plus" 
   elif x == '=':
      print "equal"
except ....:
   print "not valid"

有人可以帮助我吗? 谢谢

4 个答案:

答案 0 :(得分:1)

values = {"+": "plus", "=": "equal"}

x = raw_input("Please answer + or =")

try:
    print values[x]
except KeyError:
    print "not valid"

但是,我不确定您是否应该使用try / except,因为if可能更具可读性。

答案 1 :(得分:0)

这只读+或=并将继续重复,直到输入+或=。

while x != "+" and x != "=":
    if x == "+":
       print "plus" 
    elif x == '=':
       print "equal"
    else:
       print ''

答案 2 :(得分:0)

def wordify():
    x = raw_input('Please answer + or =: ')

    if x == '+':
        print 'plus'
    elif x == '=':
        print 'equal'
    else:
        print 'Not valid. Please try again.\n'
        wordify()

现在您只需运行该功能。

In [11]: wordify()
Please answer + or =: 8
Not valid. Please try again.

Please answer + or =: -
Not valid. Please try again.

Please answer + or =: +
plus

In [12]: wordify()
Please answer + or =: *
Not valid. Please try again.

Please answer + or =: =
equal

与其他人建议的情况一样,这不适合使用try / except

答案 3 :(得分:-1)

如果这是一个功能,您总是可以引发错误:

def somefunction(input):
    try:
        if input == '+':
            return 'plus'
        elif input == '=':
            return 'equal'
        raise ValueError
    except ValueError, e:
        return e.message