if city == 'Chennai':
print "this is Chennai city"
elif city == 'Delhi':
print "this is Delhi city"
else:
print "invalid city"
我想在城市无效时提出ValueError。怎么做?
答案 0 :(得分:3)
city = 'some city'
if city == 'Pune':
print "this is pune city"
elif city == 'Delhi':
print "this is Delhi city"
else:
raise ValueError("Invalid City")
Traceback (most recent call last):
File "<pyshell#2>", line 8, in <module>
raise ValueError('Invalid City')
ValueError: Invalid City
答案 1 :(得分:2)
我稍微重构了您的代码,但它显示了如何引发ValueError
:
def validate_city(city):
city = city.title() # Capitalize properly
# use set(["Pune", "Delhi"]) for backwards-compatibility
valid_cities = {"Pune", "Delhi"}
if city in valid_cities:
print "This is %s city" % city
else:
raise ValueError("Invalid city %s" % repr(city))
示例输出:
>>> validate_city("gotham city")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 7, in validate_city
ValueError: Invalid city 'Gotham City'
>>> validate_city("delhi")
This is Delhi city
注意:
title()
方法用于正确地将城市名称大写。在验证用户输入之前规范化用户输入是一种很好的做法。即将“dehli”变成“Dehli”,将“new york”变成“New York”等等。答案 2 :(得分:0)
这取决于您希望如何处理这种情况。但是,您将使用命令
raise ValueError
在您确定这是一个无效城市的时候
validcities = ('Pune', 'Delhi', 'Any other valid city')
try:
if city not in validcities:
raise ValueError
print 'This is', city, 'city'
except ValueError:
print city, ' is an invalid city'
# perform other invalid city here