I'm trying to concatenate a string literal to a string variable and reassign this value to the same variable.
I've tried the +=
operator and something like
string = string + "another string"
but that doesn't work.
Here is my code.
userWord = input("Enter a word: ").upper()
# Prompt the user to enter a word and assign it to the userWord variable
for letter in userWord:
# Loops through userWord and concatenates consonants to wordWithoutVowels and skips vowels
if letter == "A" or letter == "E" or letter == "I" or letter == "O" or letter == "U":
continue
wordWithoutVowels += userWord # NameError: name "wordWithoutVowels" is not defined
print(wordWithoutVowels)
Firstly, I think you intended to do wordWithoutVowels += letter
, not the entire userWord
. Secondly, that expression is the same as wordWithoutVowels = wordWithoutVowels + userWord
, which means that wordWithoutVowels
needs to be defined before it.
Simply add the following before the for
loop
wordWithoutVowels = ''
Edit:
As @DeveshKumarSingh mentioned, you can further improve the loop by using the following if
condition instead of using continue
if letter not in ['A','E','I','O','U']:
wordWithoutVowels += letter