如何实现if语句不换行结束且回答错误时终止代码执行?
Got it, let's sort out this code flow issue for you! The problem with your current code is that all the lines after the first if/else block run no matter what the user answers. Even if they type something other than "yes", the program will still ask for their name and check it—because those lines aren't nested inside the first if where they belong.
Here are two straightforward ways to fix this:
Option 1: Indent Your Follow-Up Code (Cleanest Approach)
Just move all the code that should only run when the user says "yes" inside the first if block by indenting it. This is the standard Python way to control flow:
print('Would you like to begin?') answer = input() if answer == 'yes': print('What is your name?') # All this code now only runs if the user said "yes" name = input() if name == 'Test': print('Congratulations! You won!') else: print('Good try. The answer was Test.') else: print('ok') # Program ends here automatically if user didn't say "yes"
How this works:
- If the user types "yes", the code inside the first
ifruns: it asks for their name, checks it, and prints the result. - If they type anything else, the
elseblock runs (prints "ok"), and then the program exits since there's no more code to execute.
Option 2: Explicitly Exit the Program (For More Control)
If you want to make sure the program stops immediately after the else block (useful if you have extra code later that you don't want to run), you can use sys.exit():
import sys print('Would you like to begin?') answer = input() if answer == 'yes': print('What is your name?') name = input() if name == 'Test': print('Congratulations! You won!') else: print('Good try. The answer was Test.') else: print('ok') sys.exit() # This immediately stops the program # Any code below this line will never run if the user didn't say "yes"
Either option will get you the behavior you want—Option 1 is simpler for your current use case, though!
内容的提问来源于stack exchange,提问作者Doctor Pickle

