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

运行Python代码遇NameError求助:变量未定义及函数报错

Let's break down what's going wrong here and fix it step by step!

1. The Immediate NameError Trigger

The first problem is straightforward: when you call disemvowel(word) at the end, you haven’t actually defined a variable named word anywhere. Python has no idea what you’re referring to, hence the NameError. You need to create a string variable first before passing it to the function.

2. Sneaky Typo

In your loop, you wrote word.remove(vowle) — that’s a typo! It should be vowel, not vowle. Even if you fixed the first error, this would throw another NameError once Python tries to look up the non-existent vowle variable.

3. Strings Can’t Be Modified Directly

Python strings are immutable, meaning you can’t change their characters in-place with methods like .remove(). Trying to do this would throw an AttributeError once you fix the first two issues. Instead, we need to create a new string without the vowels.

Fixed Full Code

Here’s a corrected version of your code, with explanations:

def disemvowel(word):
    # Include both lowercase and uppercase vowels to catch all cases
    vowels = {"a", "e", "i", "o", "u", "A", "E", "I", "O", "U"}
    # Use a list comprehension to filter out vowels, then join back to a string
    no_vowels = ''.join([char for char in word if char not in vowels])
    print(no_vowels)
    return no_vowels  # Return the result so you can reuse it later

# Define your input string first!
my_input_word = "Hello, let's fix this NameError!"
# Call the function with the defined variable
disemvowel(my_input_word)

If you prefer a loop-based approach using string replacement (which is simpler for this case), here’s another option:

def disemvowel(word):
    vowels = "aeiouAEIOU"
    for vowel in vowels:
        # Replace all instances of the vowel with an empty string
        word = word.replace(vowel, '')
    print(word)
    return word

my_input_word = "Testing this alternative method!"
disemvowel(my_input_word)

Both versions will correctly remove vowels and eliminate the NameError by ensuring we pass a properly defined variable to the function.

内容的提问来源于stack exchange,提问作者Salah Eddin Berriani

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:01:29