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

类中方法内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 applied upper() 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: The name parameter from __init__ isn't stored as a class instance attribute, so the sorry() method can't access it (this would actually throw a NameError—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?

  1. Added self.name = name in __init__ so the name value is accessible across all class methods.
  2. Moved .upper() to the end of the input() call, ensuring the user's response is converted to uppercase for reliable condition matching.
  3. 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:15:18