简体   繁体   中英

how to incorporate try and except into a block of code in python

I am working on a collatz sequence code in python. The code should give me a sequence of numbers that end in 1. The code I have here does that when I enter a number.

    try:
    number = int(input('Pick a number'))
except ValueError:
    print('Error! input a number')
def collatz(number):
            if number % 2 == 0:
                x = number // 2
                return x
            else:
                x = 3 * number + 1
                return x

while number != 1:
        number = collatz(number)
        print(number)

However, when I try to invoke the try and except function by entering a letter,I get the desired error message but I also get a NameError.

Traceback (most recent call last):
  File "/home/PycharmProjects/collatz/collatz.py", line 14, in <module>
    while number != 1:
NameError: name 'number' is not defined
Error! input a number *Desired Error Message*

I dont get this error when I remove the try and except function. I have tried defining 'name' as a global variable and also played around with the indentation but nothing seems to work. I would greatly appreciate any kind of help.

I am using python 3.6.

The reason you get the NameError is because number is simply not defined. The call to int fails, thus the assignment to number never happens, you catch and print the error but then just proceed. To force the user to enter a valid number you have to repeat the prompt until the user enters the correct input.

def read_number():
    while True:
        try:
            return int(input('Pick a number'))
        except ValueError:
            print('Error! Input a number')

Then, to read a sequence of numbers you do:

while True:
    number = read_number()
    if number == 1:
        break

If your ValueError get raised, then I think you don't really define number in any other place. That's why your while loop raises a NameError .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM