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

前端 未结 3 2029
遥遥无期
遥遥无期 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条回答
  •  梦谈多话
    2021-01-22 16:56

    The problem isn't with the conversion to an int. user_num doesn't get a value if an exception is thrown, but it's used later.

    prompt_text = "Enter a number: "
    try:
      user_num = int(input(prompt_text)) # this fails with `asd2`
    except ValueError:
      print("Error") # Prints your error
    
    for i in range(1,10):
      print(i, " times ", user_num, " is ", i*user_num) # user_num wasn't assigned because of the error
    
    even = ((user_num % 2) == 0)
    
    if even:
      print(user_num, " is even")
    else:
      print(user_num, " is odd")
    

    You can fix this by putting the code that uses user_num in the try-block. I'll also add create a function to clean things up.

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

    See the ideone here.

提交回复
热议问题