我尝试使用'while true‘来要求用户输入0或一个正整数。我尝试了几种不同的方法,它们似乎都有不同的问题。函数def positive_int拒绝字母和负整数,但不允许阶乘函数工作。阶乘函数独立工作。我得到一个错误代码: TypeError:不支持的操作数类型+:'NoneType‘和'int’,此行的I in range(1,num + 1):。谢谢你的帮助。
def positive_int(prompt=''):
while True:
try:
num = int(input(prompt))
if num < 0:
raise ValueError
break
except ValueError:
print("Please enter a positive integer.")
print('\n')
print("The program will compute and output the factorial number.")
def factorial():
num = positive_int('Please enter the number to factorial: ')
factorial = 1
if num == 0:
print("\nThe factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("\nThe factorial of", num,"is",factorial)
factorial()发布于 2020-04-27 10:11:50
positive_int()函数不返回任何内容,这意味着num = positive_int()将num设置为None。稍后,当代码尝试将此None值添加到一个整数时,它会失败。
您可以通过将break语句替换为return或在中断循环后返回num来解决此问题:
def positive_int(prompt=''):
while True:
try:
num = int(input(prompt))
if num < 0:
raise ValueError
return num # Replacing break with return statement
except ValueError:
print("Please enter a positive integer.") 或
def positive_int(prompt=''):
while True:
try:
num = int(input(prompt))
if num < 0:
raise ValueError
break
except ValueError:
print("Please enter a positive integer.")
return num # Breaking out of the loop takes you here发布于 2020-04-27 10:09:50
您同时将factorial用作函数名和变量名。
发布于 2020-04-27 10:11:31
问题是positive_int没有返回任何内容
尝试:
def positive_int(prompt=''):
while True:
try:
num = int(input(prompt))
if num < 0:
raise ValueError
return num # change to return value rather than break
except ValueError:
print("Please enter a positive integer.")
print('\n')
print("The program will compute and output the factorial number.")
def factorial():
num = positive_int('Please enter the number to factorial: ')
factorial = 1
if num == 0:
print("\nThe factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("\nThe factorial of", num,"is",factorial)
factorial()https://stackoverflow.com/questions/61450612
复制相似问题