Python3嵌套条件练习求助:代码输出True/False不符合预期
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?
Unwanted
True/FalseOutput
You're wrapping thepre_word()call in aprint()statement, but your function already prints "Valid" or "not valid" internally. TheTrue/Falseyou see is the return value of the function being printed by that outerprint()—that's extra output you don't want.Missing Branch for Non-"pre" Words
If the input doesn't start with "pre", your function doesn't hit anyprintorreturnstatement. This means it will default to returningNone, and your outerprint()would output that (which is definitely not what you intended).
Fixed Code Options
Option 1: Separate Logic (Recommended)
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/Falseoutput you were seeing
内容的提问来源于stack exchange,提问作者issa ahmed

