0

collatz sequence it says error in line 2 i.e try:

help to complete the collatz sequence def Collatz(number): try: if number%2==0: print(number//2) return(number//2) elif number%2==1: print(3*number+1) return(3*number+1) except valueError: print('number entered is invalid') number=int(input('enter any number')) while number >1: print(collatz(number))

30th Oct 2016, 12:43 PM
harjeevan singh
harjeevan singh - avatar
7 Réponses
+ 4
There is just 2 minor error in your code.... first blocks are properly indent and second name of the function at function call. check this out def Collatz(number): try: if number%2==0: print(number//2) return(number//2) elif number%2==1: print(3*number+1) return(3*number+1) except valueError: print('number entered is invalid') number=int(input('enter any number')) while number >1: print(Collatz(number))
30th Oct 2016, 11:12 PM
Waqas Asghar Bhalli
Waqas Asghar Bhalli - avatar
+ 3
Everything is fine just minor change in the condition of While loop. Just copy below code and run it you will get your desired sequence def Collatz(number): try: if number%2==0: print(number//2) return(number//2) elif number%2==1: print(3*number+1) return(3*number+1) except valueError: print('number entered is invalid') number=int(input('enter any number')) while number != 1: number = Collatz(number)
2nd Nov 2016, 12:35 PM
Waqas Asghar Bhalli
Waqas Asghar Bhalli - avatar
+ 2
You should indent the try and except blocks. Also standard indentation is 4 spaces/tab.
30th Oct 2016, 1:37 PM
Laurentiu Footalau
Laurentiu Footalau - avatar
+ 1
Yh, you should indent after function definition
30th Oct 2016, 4:35 PM
Joshua Christian
Joshua Christian - avatar
+ 1
You should indent the try and except blocks after function definition.
31st Oct 2016, 9:02 AM
Djaber Meghar
Djaber Meghar - avatar
0
guys it still does not work properly......it goes in to infinite loop
2nd Nov 2016, 12:12 PM
harjeevan singh
harjeevan singh - avatar
0
thanks Waqas and all guys...basically the problem was in last line
2nd Nov 2016, 3:16 PM
harjeevan singh
harjeevan singh - avatar