0

I have been trying to complete a task from automate the boring stuff. This is the task."Write a function named collatz() that has one parameter named number. If number is even, then collatz() should print number // 2 and return this value. If number is odd, then collatz() should print and return 3 * number + 1.

Then write a program that lets the user type in an integer and that keeps calling collatz() on that number until the function returns the value 1.Add try and except statements to the previous project to detect whether the user types in a noninteger string."

def collatz(num):
    ev_odd = num % 2  #detecs whether number is odd or even
    if ev_odd == 1:
        num = num * 3 + 1    
    else:
        num = num//2
    print(num)
    global number
    number = num

#the program
print('enter an integer')
number = int(input())
collatz(number)
while number != 1:
    collatz(number)

i made this code it is working fine.But I am unable to use try and except statement to this..Help me out. Other recommendation to improve this code are requested. Regards

Unknown
  • 1
  • 2
  • Why do you need to use try except? What's the problem you're trying to solve? – jonrsharpe May 06 '19 at 19:11
  • @jonrsharpe i want to to use try and except to ensure that user enters an integer in the input so that if he enters a string the program should not crash due to error and continue working in a proper way – Unknown May 07 '19 at 11:55
  • Then see e.g. https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response, that's only tangentially related to the code you've posted. – jonrsharpe May 07 '19 at 11:57

0 Answers0