gpt4 book ai didi

python - try/except python 处理和 int() 函数

转载 作者:行者123 更新时间:2023-12-01 06:45:49 25 4
gpt4 key购买 nike

对于Pythonic Way来说相当新,但是下面的代码没有按预期工作,有人知道为什么吗?如果我输入 143.22,我会得到“不是 int”响应,而不是预期的 collat​​z(143),例如 int(143.22)。顺便说一句,这是《用 Python 自动执行无聊的事情》初学者书籍中的一个基本练习(第 3 章有关使用函数的练习)。谢谢!

def collatz(myint) :
print(myint)
if myint % 2 == 0 :
myint = int(myint / 2)
else:
myint = int(myint *3 +1)
if myint == 1 :
print(myint)
return myint
else:
collatz(myint)

try:
x=input('Input a non-negative integer between 1 and infinity: ')
val = int(x)
if int(x) == abs(int(x)) :
print("Yes input string is an Integer.")
collatz(val)
else:
print('I did say NON negative!')
except ValueError:
print("That's not a positive int!")

最佳答案

您正在尝试运行 int('143.22')

对我来说,这会产生:

Traceback (most recent call last):
File "main.py", line 1, in <module>
int('143.22')
ValueError: invalid literal for int() with base 10: '143.22'

但是,int(143.22) 工作正常。

针对您的用例的快速解决方案可能是将其转换为 float 。

float('143.22')

int(float('143.22'))

关于python - try/except python 处理和 int() 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59230201/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com