0

I am trying to create a simple program to apply the statement of the Collatz Conjecture to an integer that the user can enter, I have:

def collatz(n):
    print n,
    if n % 2 ==0:
        n = n / 2
    elif n == 0:
        Print "Collatz Conjecture true for" , 'n'
    else:
        n = n *3 + 1

input("\n\nInsert a positive integer:")
def collatz(n)

However it is saying there is a syntax error in the line:

Print "Collatz Conjecture true for" , 'n'

I can't see what mistake ther is in this line.

Also as I haven't been able to test it yet, does this look as though it will work ok?

4

4 回答 4

3

Python is case sensitive. Use "print" not "Print".

于 2011-10-30T20:34:54.353 回答
3

好吧,你的语法错误是 python 区分大小写,所以你需要print而不是Print.

但是你有更多的问题:

  • 'n'打印字符串n。我认为您想要的是n打印变量的值(或者如果没有,那么您可以只创建一个字符串“... true for n”)。

  • 最后(我认为),为了运行函数collatz,你不需要def; 这只是为了定义。

于 2011-10-30T20:39:28.813 回答
2

更多问题:

  1. 停止条件应该是n == 1,不是n == 0
  2. 您必须重复或迭代,因为您只是迈出了一步。
  3. 检查输入,确保它确实是一个正数。
于 2011-10-30T20:46:06.280 回答
0
 def collatz_steps(n):
    steps=0
    if n==1:
        return 0 
    else:
        while n!=1:
            if n%2==0:
                n=n/2
                steps+=1
            else:
                n = 3*n+1
                steps+=1
        return steps
于 2012-04-04T02:46:34.810 回答