簡體   English   中英

為多個if-else提高ValueError

[英]Raise ValueError for multiple if-else

if city == 'Chennai':
   print "this is Chennai city"
elif city == 'Delhi':
   print "this is Delhi city"
else:
   print "invalid city"

每當城市無效時,我想引發ValueError。 怎么做 ?

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

我對您的代碼進行了一些重構,但是它顯示了如何引發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

筆記:

  • 一組用於查找有效城市,這比許多if語句行更易於維護。
  • 查找集比列表要快
  • title()方法用於將城市名稱正確地大寫。 最好在驗證用戶輸入之前對其進行標准化。 即,將“ dehli”變成“ Dehli”,將“紐約”變成“ New York”,依此類推。

這取決於您要如何處理這種情況。 但是,您將使用命令

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM