问题描述
我目前无法在自动化无聊的事情中完成这项挑战:
我的代码是:
def collatz(数字):
全局seqNum
如果(seqNum%2 == 0):
返回seqNum // 2
elif(seqNum% 2 == 1):
return 3 * seqNum + 1
print('你想用什么数字?')
seqNum = input()
number = int(seqNum)
i = number
while i> 1:
collatz(seqNum)
print(number)
我是得到这个错误:
pre $ Traceback(最近一次调用最后一次):
文件C:/ Users / Administrative / AppData / Local / Programs / Python / Python36-32 / collatzSeq.py,第15行,位于< module>
collatz(seqNum)
文件C:/ Users / Administrative / AppData / Local /程序/ Python / Python36-32 / collatzSeq.py,第3行,在collatz中
if(seqNum%2 == 0):
TypeError:不是在字符串格式化期间转换的所有参数
我知道我在写我的代码时做了些错误,但我不明白它到底是什么。任何和所有的帮助,非常感谢!
另外我使用的是python 3. 解决方案 div>
-
您正在对字符串进行算术运算,而不是整数。
没有必要有一个 You're doing arithmetic on a string, not an integer.
There's no need to have a
global
variable. Pass an argument to a function, and have it return a value accordingly.
全局
变量。将一个参数传递给一个函数,并让它相应地返回一个值。 b $ b
def collatz(数字):
if(数字%2 == 0):
返回数字// 2
elif (数字%2 == 1):
返回3 *数字+ 1
print('您想使用什么数字?')
i = int (input())
while i> 1:
i = collatz(i)
print(i)
I am currently having trouble completing this challenge in "Automate the boring stuff":
My code is:
def collatz(number):
global seqNum
if (seqNum % 2 == 0):
return seqNum // 2
elif (seqNum % 2 == 1):
return 3 * seqNum + 1
print('What number would you like to use?')
seqNum = input()
number = int(seqNum)
i = number
while i > 1:
collatz(seqNum)
print(number)
And I am getting this error:
"Traceback (most recent call last):
File "C:/Users/Administrative/AppData/Local/Programs/Python/Python36-32/collatzSeq.py", line 15, in <module>
collatz(seqNum)
File "C:/Users/Administrative/AppData/Local/Programs/Python/Python36-32/collatzSeq.py", line 3, in collatz
if (seqNum % 2 == 0):
TypeError: not all arguments converted during string formatting"
I know I am doing SOMETHING wrong with how I wrote my code but I don't understand what it is exactly. Any and all help is greatly appreciated!
Also I am using python 3.
def collatz(number):
if (number % 2 == 0):
return number // 2
elif (number % 2 == 1):
return 3 * number + 1
print('What number would you like to use?')
i = int(input())
while i > 1:
i = collatz(i)
print(i)
这篇关于使用Python实现collatz功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!