-1

calculation = 0

def collatz(number):
    global calculation
    if number % 2 == 0:
        calculation = number // 2
        print(calculation)
        return calculation
        #odd number
    elif number % 2 == 1:
        calculation = 3 * number + 1
        print(calculation)
        return calculation




try:
    number = collatz(input('Type a number:')))

except:
    while type(number) != int:
        print('Please type a numerical value')
        number = collatz(int(input('Type a number:')))
while calculation  > 1:
    collatz(calculation)

Question: while doing a project from the python book i'm reading i was instructed to create a program that utilizes the collatz conjecrture. I had no problems doing everything up to the point where it wanted me to do exception handling in case the user types a none integer value in. i used the type function to loop through everything in the except statements block of code until the user types an integer value but for some reason it throws an error when it reaches the while loop under the except statement stating that "Name 'number' is not defined' and i'm not sure why its throwing this error

1 Answers1

1

In the except block of your code, where will number have been defined? It could not be in the try block, because if you're executing the except block then by definition the operation of the try block had failed.

As a separate comment, consider what type of data you would get back from input and what can collatz return if neither of the if or else conditions is satisfied?

ely
  • 74,674
  • 34
  • 147
  • 228