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

Python3嵌套条件练习求助:代码输出True/False不符合预期

Fixing Your Python pre_word Function Issue

Hey there! Let's break down the problems in your code and get it working as you expect:

What's Going Wrong?

  1. Unwanted True/False Output
    You're wrapping the pre_word() call in a print() statement, but your function already prints "Valid" or "not valid" internally. The True/False you see is the return value of the function being printed by that outer print()—that's extra output you don't want.

  2. Missing Branch for Non-"pre" Words
    If the input doesn't start with "pre", your function doesn't hit any print or return statement. This means it will default to returning None, and your outer print() would output that (which is definitely not what you intended).

Fixed Code Options

This splits the validation logic and the output logic, making your code cleaner and more reusable:

def pre_word(word):
    # Check both conditions at once with logical AND
    return word.startswith("pre") and word.isalpha()

# Get user input and handle output separately
user_word = input("enter a word that starts with \"pre\": ")
if pre_word(user_word):
    print("Valid")
else:
    print("not valid")

Option 2: Keep Logic in the Function

If you prefer to keep the print statements inside the function, just remove the outer print() and cover all possible cases:

def pre_word(word):
    if word.startswith("pre") and word.isalpha():
        print("Valid")
        return True
    else:
        print("not valid")
        return False

# Call the function directly—no need to print its return value
pre_word(input("enter a word that starts with \"pre\": "))

Both options will:

  • Print only "Valid" or "not valid" based on the input
  • Properly handle words that don't start with "pre" (they'll show "not valid")
  • Avoid the unwanted True/False output you were seeing

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:28:53