ValueError:以int为底的无效文字10:''

问题描述:

我是python的新手,这是我工作的第一个项目,它是一个Litecoin - Euro转换程序。我有一个问题,如果我没有将任何东西放到程序的Entry()字段中并提交它,控制台会输出以下错误消息(因为int()和float()不能将空字符串转换为int /浮子):ValueError:以int为底的无效文字10:''

Exception in Tkinter callback 
Traceback (most recent call last): 
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", line 1536, in __call__ 
return self.func(*args) 
File "/Users/Samir/Library/Mobile Documents/com~apple~CloudDocs/Coding/Python/hello_world/exch.py", line 13, in exchange 
choice = int(exc.get()) # choice of EUR to LTC or other way around 
ValueError: invalid literal for int() with base 10: '' 

我在该物质中所使用的整个代码:

from Tkinter import * 
from json import * 
from urllib2 import * 

def exchange(): 
    data = urlopen('https://btc-e.com/api/3/ticker/ltc_eur') # EUR - LTC API 

    j_obj = load(data) #loads json data 
    exch = float(j_obj['ltc_eur']['avg']) # picks exchange rate out of api 

    choice = int(exc.get()) # choice whether EUR to LTC or other way around 
    amount = float (am.get()) # amount of the currency the user wants to convert 

    if choice == 0: 
     print round((1/exch) * amount, 2), "Litecoins" 
    elif choice == 1: 
     print round(exch * amount, 2), "Euro" 
    else: # if something other than 0 or 1 was typed in 
     print "I'm sorry but you have to enter either 0 or 1" 

    am.delete(0, END) 
    exc.delete(0, END) 


master = Tk() # creates new window in var master 
master.wm_title("LTC - EUR converter") # creates title for the window 

Label(master, text = "EUR into LTC (0) or LTC into EUR(1): ").grid(row = 0, sticky = W) # creates choice string in a table (Row 1) 
Label(master, text = "Amount: ").grid(row = 1, sticky = E) # creates text "Amount" in a table (Row 1) 

exc = Entry(master) # picks up Entryvalue 
exc.grid(row = 0, column = 1) 

am = Entry(master) # picks up Entryvalue 
am.grid(row = 1, column = 1) # places it at row 0 colum 1 in the table 

Button(master, text = "Quit", command = master.quit).grid(row = 2, column= 1, sticky = W) # creates a quit button that closes the window 
Button(master, text = "Submit", command = exchange).grid(row = 2, column = 1) # creates a submit button that executes def "exchange" 


mainloop() # starts the program 

我设法解决与改变如果查询以比较输入到串并转换输入(该问题。int和float)后,确认为0或1已经在被键入 的改变的代码:

choice = exc.get() 
amount = am.get() 

if choice == '0': 
    choice = int(choice) 
    amount = float(amount) 

    print round((1/exch) * amount, 2), "Litecoins" 
elif choice == '1': 
    choice = int(choice) 
    amount = float(amount) 

    print round(exch * amount, 2), "Euro" 
else: 
    print "I'm sorry but you have to enter either 0 or 1" 

所以我的问题是,有没有解决方案更有效的问题?因为我认为我的方法有效,但它不是那里最好的选择。

"It is better to ask for forgiveness than permission".

你可以把你的代码在try-except块。

try: 
    choice = int(choice) 
    amount = float(amount) 

except ValueError: 
    print "I'm sorry but you have to enter either 0 or 1" 
    return 

if choice == 1: 
    ... 
else: 
    ... 

这样,您检查choice的值而不是两次。

编辑:如果要谨慎,另备try-except大括号choiceamount。在当前的情况下,输入有效的choice但无效的amount可能会产生误导性的错误消息。

+0

您可能要概括这一点。如果您在选择时输入零或一个数字,但保留空白,您将收到误导性的错误消息。 tkinter验证输入的快速谷歌将向您显示执行此操作的标准方法。 – Mic

+0

@Mic谢谢,添加了一个脚注。 –