Japeusa
Japeusa

Reputation: 31

Why does this code does not work as function?

I'm new to python and this should be a simple function practice exercise.

I wrote this function that should put in upper case every character of a string in which the index is even, but it didn`t work.

When I wrote a very similar (but not as function), it worked. Why?

Code_1:


h = 'abcdefg'
f = ''

for stuff in h:
    if h.index(stuff) % 2 == 0:
        f = f + stuff.upper()
    else:
        f = f + stuff.lower()
        
print(f)

Output: AbCdEfG

Code_2:


h = 'abcdefg'

def func_test(*a):
    
    f = ''
    
    for stuff in a:
        if a.index(stuff) % 2 == 0:
            f = f + stuff.upper()
        else:
            f = f + stuff.lower()
    return f

func_test(h)

Output: 'ABCDEFG'

Upvotes: 2

Views: 41

Answers (1)

Buddy Bob
Buddy Bob

Reputation: 5889

I think it might be a mistake but, at the moment you are passing in args.

def func(*args)

notice the asterisk before the argument. Doing this in your program will give us

('abcdefg',)

So, take this away and you can easily iterate through the string.

h = 'abcdefg'

def func_test(a):
    f = ''
    
    for stuff in a:
        if a.index(stuff) % 2 == 0:
            f = f + stuff.upper()
        else:
            f = f + stuff.lower()
    return f

print(func_test(h))

tradition create online

x = lambda a: ''.join([let.upper() if count % 2 == 0 else let for count,let in enumerate(a)])
print(x('abcdefg'))

output

AbCdEfG

Upvotes: 5

Related Questions