2

Hello I am stuck on understanding this antivowel code for an exercise in Codecademy

1) # Here is the code 
2) vowels="aeiou" 
3) def anti_vowel(x):
4)     for a in x:     
5)         for j in vowels: 
6)            if a.lower()==j:
7)                x=x.replace(a,"")
8)     return x

why does the .lower function need to be set to x in line 7? When using functions do we always have to set it to a variable if we want to call the function?

also, in line 4 to 5 is this considered as a nested for loop?

P Ramos
  • 31
  • 1
  • 2
  • 5
  • 1
    because `.replace()` RETURNS the modified string. it doesn't update the old string for you. – Marc B Aug 24 '15 at 21:46

2 Answers2

2

.replace(<string>) returns a modified string. Normally, we could set it equal to a new variable. But the programmer chose to overwrite the old variable x with the new modified string. It is similar to saying x = x + 1. You are modifying the old string, but instead of saving it to a new variable, the programmer chose to update the variable. You do not have to always set a variable, but if the function returns a value it is recommended (or append it to a list or something). What is the point of calling a function if you are not going to set the return to something?

You don't have to if you are using it in a conditional. For example (this could be done in a simpler way, but FOR THE PURPOSE OF THE EXAMPLE):

x = raw_input("Please input a number\n")

The number is then stored as x.

If you want to compare the number to another value, you can call the function int() within the conditional instead of setting it as another variable.

if int(x) == 5:
    print 'Yay, you guessed right!'

The alternative:

y = int(x)
if y == 5:
    print 'Yay, you guessed right!'

Hope this helps!

Happy coding, and best of luck!

Joseph Farah
  • 2,463
  • 2
  • 25
  • 36
1

In Python there is an important difference between methods that are in place, meaning they modify the object they are being called upon, and methods that are not in-place and instead return a new object.

So in your example x.replace(a,"") returns a new string. It does not modify the original string x.

rkrzr
  • 1,842
  • 20
  • 31