【问题标题】:ValueError: invalid literal for int() with base 10: ' 'ValueError: int() 以 10 为基数的无效文字:''
【发布时间】:2017-12-06 12:51:08
【问题描述】:

我是 python 新手,这是我从事的第一个项目,它是一个莱特币 - 欧元转换程序。我有一个问题,如果我没有在程序的 Entry() 字段中输入任何内容并提交它,控制台将输出以下错误消息(因为 int() 和 float() 无法将空字符串转换为 int/一个浮点数):

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

我设法通过将 if 查询更改为将输入与字符串进行比较并在确认已输入 0 或 1 后将输入转换(为 int 和 float)来解决问题。 修改后的代码:

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"

所以我的问题是,对于这个问题有没有更有效的解决方案?因为我认为我的方法可行,但它不是最好的选择。

【问题讨论】:

    标签: python python-2.7 performance tkinter valueerror


    【解决方案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 的值一次而不是两次。

    编辑:如果为choiceamount 保留单独的try-except 大括号是明智的。在当前情况下,输入有效的choice 但无效的amount 可能会产生误导性错误消息。

    【讨论】:

    • 你可能想概括一下。如果您在选择中输入零或一但将金额留空,您将收到误导性错误消息。 tkinter 验证输入的快速 google 将向您展示执行此操作的标准方法。
    • @Mic 谢谢,添加脚注。
    猜你喜欢
    • 2013-08-04
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多