Skip to main content
 首页 » 编程设计

Python 在 if 语句后不返回任何内容

2025年05月04日11开发

我需要一些指导来了解为什么在我运行程序后 shell 中没有打印任何内容。 这是我的代码:

def numbersize1(x): 
    """returns the string 'Negative!' if the number is less than zero, 'Small!' if the number is at least zero but less than 10, 'Medium!' if the number is at least 10 but less than 100, and 'Large!' if the number is greater than or equal to 100. 
 
    Number -> str""" 
    if x<0: 
        return str('Negative!') 
    if x==0 and x<10: 
        return str('Small!') 
    if x==10 and x<100: 
        return str('Medium!') 
    if x==100 and x>100: 
        return str('Large!') 

正如我之前所说,当我运行脚本时,shell 中什么也没有出现。换句话说,如果我输入“1”,字符串“Small!”应该出现,但没有出现。感谢您的帮助。

请您参考如下方法:

如果你这样写:

if x==0 and x<10: 

你是说 x 等于零 并且 它小于 10。如果 x 不等于零,则 if 将不匹配。

你的其他人也一样。看看他们说了什么,想想他们将要做什么。

您不必将字符串转换为字符串,因此您可以将其简化为:

if x<0: 
    return 'Negative!' 
if x<10: 
    return 'Small!' 
if x<100: 
    return 'Medium!' 
return 'Large!'