You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中isinstance判断整数输入返回False及分支执行异常求助

Fixing Your Python Integer & Square Root Issues

Hey there! Let's work through your two problems step by step—they're common pitfalls for new Python devs, so you're not alone here.

Problem 1: isinstance returns False for integer inputs

The root issue here is how Python's input() function works: it always returns a string, no matter what you type. Even if you enter 64, the variable number1 holds the string value "64", not an integer. That's why isinstance(number1, int) will always return False—you're checking if a string is an integer, which it never is.

Problem 2: else branch runs for non-integer inputs

Your condition if(result == "False") is comparing a boolean value (False) to a string ("False"). These two are not equal, so the condition never triggers, and the code always jumps to the else block. When you pass a string like "Sun" to SQUARE_ROOT, the line int(number2) tries to convert that string to an integer, which fails and throws the ValueError you're seeing.

The Fix: Use try-except for safe type conversion

The most reliable way to handle this is to attempt converting the input to an integer, and catch the error if it fails. Here's a revised version of your code that works as expected:

def calculate_square_root(number):
    # We're passing an integer here, no need to convert again
    sq_root = number ** 0.5
    print(f"The square root is: {sq_root}")

user_input = input("Please enter an integer: ")

try:
    # Try to convert the input string to an integer
    integer_value = int(user_input)
    print("You have correctly entered an integer.")
    calculate_square_root(integer_value)
except ValueError:
    # This runs if the conversion fails (e.g., input is "Sun")
    print("You have not entered an integer. The program will quit.")

Key improvements:

  • try-except block: This safely handles type conversion errors without crashing the program. If converting the input to an integer fails, it triggers the except branch instead of throwing an unhandled error.
  • Avoid redundant conversions: We convert the input to an integer once before calling the function, so the function can work directly with the integer value.
  • PEP8-compliant naming: Changed SQUARE_ROOT to calculate_square_root—lowercase with underscores is the standard for Python function names.

Bonus note: What about isdigit()?

You might think of using user_input.isdigit() to check if the input is an integer, but this won't work for negative numbers (e.g., "-64" returns False). The try-except approach handles all valid integer cases (positive, negative, zero) seamlessly.

内容的提问来源于stack exchange,提问作者Tamal Bose

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 07:58:29