如何解决如何修复 Python Turtle textinput() 中的 int() 错误
当我运行此代码时,当在 invalid literal
中输入一个字母时,我收到一个 textinput()
错误,因为它仅用于注册 int
值而不是 str
值。
我尝试了一些不同的东西,但似乎都不起作用。
import turtle
eg = 100
def betcurrency():
bettedc = turtle.textinput('Bet money.',f'You have {eg}')
if int(bettedc) <= eg:
print(f'User betted {bettedc}$')
elif int(bettedc) >= eg:
betcurrency()
print("Users can't bet what they don't have!")
elif int(bettedc) <= 0:
betcurrency()
print('User tried to bet a negative amount.')
else:
betcurrency()
print('User betted invalid money.')
这是我得到的错误;
Traceback (most recent call last):
File "e:\Visual Studio Code\Python\Finished\Turtle Race\main.py",line 145,in <module>
setup()
File "e:\Visual Studio Code\Python\Finished\Turtle Race\main.py",line 112,in setup
betcurrency()
File "e:\Visual Studio Code\Python\Finished\Turtle Race\main.py",line 41,in betcurrency
if int(bettedc) <= eg:
ValueError: invalid literal for int() with base 10: 'TEXT' #This is the text I put in.
解决方法
['c','b','a']
,
您的错误是由于 int()
无法从用户输入中提取 int 时未能捕获引发的错误。
如果您正在与用户输入进行交互并且需要某种验证,我通常建议将该逻辑移出到函数中。您可以将 collect_int
从 here 修改为使用您正在使用的海龟提示。
import turtle
def collect_int(
heading,message,err_msg="Invalid number entered. Please try again."
):
while True:
try:
return int(turtle.textinput(heading,message))
except ValueError:
message = err_msg
def bet_currency(user_currency):
while True:
bet = collect_int('Bet money.',f'You have {user_currency}')
if bet <= 0:
print('User tried to bet a negative amount.')
elif bet <= user_currency:
print(f'User betted {bet}$')
break
else:
print("Users can't bet what they don't have!")
user_currency = 100
bet_currency(user_currency)
如果您试图通过海龟 GUI 与用户交互,那么使用 print
有点奇怪。用户可能不会想到在控制台中查看。也许这些是您正在处理的正在进行的程序中的非用户可见日志,但似乎值得一提。
请注意,我还将 eg
(为清楚起见重命名为 user_currency
)传递给 bet_currency
函数。函数从自身外部获取数据并不是一个好主意——函数访问的所有变量都应该进入参数。如果参数过多或函数改变了对象的属性,请使用类将多个相关数据分组在一个狭窄的范围内。从长远来看,这可以避免错误并使程序更易于编写。
我还删除了递归:如果提示失败的时间足够长(约 1000 次),程序就会崩溃。这对您的程序来说不太可能重要,安全性和可靠性现在可能不是您的首要任务,但使用 while True:
循环并从一开始就正确执行它同样容易。
elif bet <= 0:
和 else
永远不会发生,因为前两个分支涵盖了所有可能的情况。
这个条件似乎不正确:
bet >= user_currency:
print("Users can't bet what they don't have!")
我希望你可以用所有的钱下注,所以我会赢 bet > user_currency
。这可能只是 else
,因为第一个分支涵盖了另一种可能的情况 <=
。
elif bet <= 0:
永远不会发生,除非 eg
可以为负数。我只是将它作为第一个选项,或者查看 this answer,它提供了更通用的提示,让您可以传入一个验证函数,该函数可以阻止负数并更优雅地处理这些不同的场景。
如果您的 Python 海龟库有 textinput()
,它可能还有它的伴侣 numinput()
,它可能会解决您的问题:
import turtle
stack = 100
def betcurrency():
bet = turtle.numinput("Bet money.",f"You have {stack}",minval=1,maxval=stack)
if bet:
print(f"User bet ${bet:.2f}")
else:
print("User cancelled bet.")
这可能比尝试自己处理潜在错误更简单。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。