Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
The Collatz Sequence
#4
Hello,

the main problem is that your function doesn't return any value, like mlieqo says. Also you have two points more to revise:

1- input function returns a 'char'. Then you are comparing in your loop in its first iteration a char with a int. '1' is not the same that 1. You solve it to cast the input.

2- You are not controlling negative values. Then, a -1, -5, -100... values are allowed (maybe "while n>1")

Maybe anything like this:
def collatz(number):
    if number % 2 == 0:
    	result = number//2
    	return result
    else:    
        result = 3*number + 1
        return result
try:
    n = int(input("Give me a number: "))
    while n != 1:
    	print(n)
    	n = collatz(n)
except ValueError:
    print('Type a number please!')
... Sorry for my low English level...
Reply


Messages In This Thread
The Collatz Sequence - by Truman - Apr-17-2018, 10:54 PM
RE: The Collatz Sequence - by micseydel - Apr-17-2018, 11:10 PM
RE: The Collatz Sequence - by Truman - Apr-18-2018, 10:11 PM
RE: The Collatz Sequence - by mlieqo - Apr-18-2018, 09:29 AM
RE: The Collatz Sequence - by vaison - Apr-18-2018, 01:41 PM
RE: The Collatz Sequence - by vaison - Apr-19-2018, 11:03 AM
RE: The Collatz Sequence - by Truman - Apr-19-2018, 09:38 PM
RE: The Collatz Sequence - by vaison - Apr-19-2018, 10:23 PM
RE: The Collatz Sequence - by Truman - Apr-19-2018, 10:48 PM
RE: The Collatz Sequence - by mlieqo - Apr-20-2018, 08:08 AM
RE: The Collatz Sequence - by s_sahil - Dec-27-2018, 07:19 AM
RE: The Collatz Sequence - by Truman - Dec-27-2018, 11:28 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Collatz-problem CaptainNeemo 2 2,320 Dec-07-2020, 04:09 PM
Last Post: deanhystad
  How can I found how many numbers are there in a Collatz Sequence that I found? cananb 5 3,948 Nov-23-2020, 05:15 PM
Last Post: cananb
  [split] The Collatz Sequence valencia 4 3,821 Jan-06-2019, 08:10 PM
Last Post: valencia

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020