本文介绍了使用Python实现collat​​z功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前无法在自动化无聊的事情中完成这项挑战:



我的代码是:

  def collat​​z(数字):
全局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:
collat​​z(seqNum)
print(number)

我是得到这个错误:

pre $ Traceback(最近一次调用最后一次):
文件C:/ Users / Administrative / AppData / Local / Programs / Python / Python36-32 / collat​​zSeq.py,第15行,位于< module>
collat​​z(seqNum)
文件C:/ Users / Administrative / AppData / Local /程序/ Python / Python36-32 / collat​​zSeq.py,第3行,在collat​​z中
if(seqNum%2 == 0):
TypeError:不是在字符串格式化期间转换的所有参数

我知道我在写我的代码时做了些错误,但我不明白它到底是什么。任何和所有的帮助,非常感谢!



另外我使用的是python 3. 解决方案 div>


  1. 您正在对字符串进行算术运算,而不是整数。

  2. 没有必要有一个全局变量。将一个参数传递给一个函数,并让它相应地返回一个值。 b




    $ b

      def collat​​z(数字):
    if(数字%2 == 0):
    返回数字// 2

    elif (数字%2 == 1):
    返回3 *数字+ 1

    print('您想使用什么数字?')

    i = int (input())
    while i> 1:
    i = collat​​z(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.

    解决方案
    1. You're doing arithmetic on a string, not an integer.

    2. There's no need to have a global variable. Pass an argument to a function, and have it return a value accordingly.


    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实现collat​​z功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 09:36