You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多
文档控制台
免费开始使用

如何优化get_int()函数以解决字符串与整数比较的TypeError?

Fixing the TypeError in Your CS50-style get_int() Function

Let's break down the problem first: your current get_int() returns a string ("not an integer") when the user enters non-integer input. When get_positive_int() tries to compare this string to the integer 1 with >=, Python throws a TypeError because you can't compare strings and integers directly.

Here are two solid solutions to fix this, aligned with the CS50 style of robust input handling:

Solution 1: Make get_int() Guarantee an Integer Return

This is the closest to how David J. Malan's CS50 get_int() works—it keeps prompting the user until they enter a valid integer, so you never have to worry about non-integer returns.

Updated get_int.py:

def get_int(prompt):
    while True:
        try:
            # Try converting input to int; if successful, return it immediately
            return int(input(prompt))
        except ValueError:
            # If conversion fails, tell the user and loop again
            print("Oops, that's not an integer. Please try again.")

def main():
    num = get_int("Enter an integer: ")
    print(num)

if __name__ == "__main__":
    main()

Updated get_positive_int.py:

Now you can safely compare the returned value to 1, since get_int() will only ever give you an integer:

from get_int import get_int

def main():
    i = get_positive_int("Positive integer please: ")
    print(i)

def get_positive_int(prompt):
    while True:
        n = get_int(prompt)
        if n >= 1:
            break
        print("That's not a positive integer. Please try again.")
    return n

if __name__ == "__main__":
    main()

Solution 2: Return None for Invalid Input (If You Prefer Explicit Checks)

If you don't want get_int() to handle looping internally, you can have it return None to signal invalid input, then add checks in get_positive_int() to handle that case.

Modified get_int.py:

def get_int(prompt):
    user_input = input(prompt)
    try:
        return int(user_input)
    except ValueError:
        # Return None instead of a string to clearly mark invalid input
        return None

def main():
    num = get_int("Enter an integer: ")
    if num is not None:
        print(num)
    else:
        print("Invalid input—please enter an integer.")

if __name__ == "__main__":
    main()

Modified get_positive_int.py:

Add checks for None before attempting the integer comparison:

from get_int import get_int

def main():
    i = get_positive_int("Positive integer please: ")
    print(i)

def get_positive_int(prompt):
    while True:
        n = get_int(prompt)
        if n is None:
            print("That's not an integer. Let's try again.")
        elif n >= 1:
            break
        else:
            print("That number isn't positive. Please enter a number ≥ 1.")
    return n

if __name__ == "__main__":
    main()

Either approach will fix your TypeError—Solution 1 is more aligned with CS50's user-friendly input handling, as it guides the user until they provide valid input without extra checks in the calling function.

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

火山引擎 最新活动