【发布时间】:2020-09-15 15:16:55
【问题描述】:
我目前正在处理 Automate the Boring Stuff 第 3 章中的 collatz 项目。我有一个完整的整数输入 collatz 函数,但是当我添加 try 时,我一直试图让程序运行,但非整数值的语句除外。
这是我的代码,仅适用于整数输入:
def collatz(number):
if number % 2 == 0:
print(number // 2)
return(number // 2)
else:
print(3 * number + 1)
return(3 * number + 1)
print('Type in a number: ')
colNum = int(input())
while colNum != 1:
colNum = collatz(colNum)
现在,这是我添加 try/except 语句时的代码:
def collatz(number):
if number % 2 == 0:
print(number // 2)
return(number // 2)
else:
print(3 * number + 1)
return(3 * number + 1)
def integercheck(inputVal):
try:
return int(inputVal)
except ValueError:
print('Error: Input needs to be a number.')
print('Type in a number: ')
integercheck(input())
print('Type in a number: ')
colNum = integercheck(input())
while colNum != 1:
colNum = collatz(colNum)
这是我收到的错误代码:
Type in a number:
string
Error: Input needs to be a number.
Type in a number:
string
Error: Input needs to be a number.
Type in a number:
5
Traceback (most recent call last):
File "/Users/Library/Preferences/PyCharmCE2018.2/scratches/scratch_1.py", line 22, in <module>
colNum = collatz(colNum)
File "/Users/Library/Preferences/PyCharmCE2018.2/scratches/scratch_1.py", line 3, in collatz
if number % 2 == 0:
TypeError: unsupported operand type(s) for %: 'NoneType' and 'int'
Process finished with exit code 1
需要明确的是,当我立即输入一个整数时,这个程序可以工作,但是当我在输入一个字符串后输入一个整数时,它就无法工作。如果有人可以提供帮助,我将不胜感激。谢谢!
【问题讨论】:
-
在递归情况下,您隐式返回 None。当您通过任何没有返回语句的代码路径退出 Python 函数时,这就是隐式 return None
标签: python python-3.x