Python, unable to convert input() to int()

前端 未结 3 1983
遥遥无期
遥遥无期 2021-01-22 16:12

I am trying to convert input() data to int() with the following code:

prompt_text = \"Enter a number: \"
try:
  user_num = int(input(prompt_text))
except ValueEr         


        
3条回答
  •  旧时难觅i
    2021-01-22 16:57

    The problem that you are facing is that the interpreter raises the error in the try and executes the except block. After that it will start to execute everyline. This will throw the NameError

    You can overcome that by putting the rest of the program into the else block.

    prompt_text = "Enter a number: "
    
    try:
        user_num = int(input(prompt_text))  
    
    except ValueError:
        print("Error")
    
    else:
        for i in range(1,10):
          print(i, " times ", user_num, " is ", i*user_num)
    
        even = ((user_num % 2) == 0)
    
        if even:
          print(user_num, " is even")
        else:
          print(user_num, " is odd")
    

    Quoting from the Python tutorial

    The try ... except statement has an optional else clause, which, when present, must follow all except clauses. It is useful for code that must be executed if the try clause does not raise an exception.

    Another way is to use a sentinel value

    prompt_text = "Enter a number: "
    user_num = 0 # default value
    try:
        user_num = int(input(prompt_text))
    except ValueError:
        print("Error")
    

    This will also work. However the results may not be as expected.


    Protip - Use 4 spaces to indent

提交回复
热议问题