Convert any user input to int in Python

后端 未结 3 457
别跟我提以往
别跟我提以往 2021-01-29 06:12

I need to convert user input to int. Below is what I have written so far which is not working out. It only accepts int. the end goal is to

3条回答
  •  無奈伤痛
    2021-01-29 07:07

    int accepts integer string or a float but cannot handle float strings. So convert to float first and then convert to integer. If the input is invalid format, int(i) would raise ValueError exception, so you can use it to handle invalid inputs.

    i = input("Enter any value: ")
    
    try:
      print(float(int(i))
    except ValueError:
      print("Please enter a number")
    

提交回复
热议问题