类中方法内If Else失效:程序无报错但执行异常终止
Fix for Your Car Class Execution Issue
Let's break down what's going wrong with your code and fix it step by step:
Key Problems in the Original Code
- Incorrect
upper()placement: You appliedupper()to the input prompt text instead of the user's input. This means the user's response stays in its original case (like "yes" or "no"), which won't match the uppercase "YES"/"NO" in your conditionals. - Missing instance variable for
name: Thenameparameter from__init__isn't stored as a class instance attribute, so thesorry()method can't access it (this would actually throw aNameError—you might have missed the error message in your runtime output). - Unprinted else branch: The else clause only has a string literal without a
print()call, so even if the code hits this branch, you won't see any feedback.
Corrected Code
class Car(): def __init__ (self, name): self.name = name # Store name as an instance attribute print (f"Hello and welcome {self.name}. You have won a Ferrari. Please enter the details below. \n") phone = input("Your phone number: ") address = input("Your home address: ") def sorry(self): print ("Hey! We are sorry, we do not ship beyond 2000 Miles.") # Apply upper() to the user's input, not the prompt response = input("Do you still want it? Yes or No? : ").upper() if response == "YES": print (f"Cool! {self.name}. Ride to us.") elif response == "NO": print (f"Oops! {self.name}. We are sorry to see you go. :(") else: print("Have a Good day!") # Add print to show feedback Car1 = Car("Jack") Car1.sorry()
What Changed?
- Added
self.name = namein__init__so thenamevalue is accessible across all class methods. - Moved
.upper()to the end of theinput()call, ensuring the user's response is converted to uppercase for reliable condition matching. - Added
print()to the else branch so you get clear feedback when the user enters an invalid option.
Now when you run the code, it will properly handle the user's input, execute the correct conditional block, and show feedback for all cases.
内容的提问来源于stack exchange,提问作者Deepak
相关产品推荐
相关产品推荐

