Problem with swapcaser in python

1

The program should convert a letter into schema A-> a or a-> A and work normally except that at the end of the string a None appears. Anyone know how I can strip it?

def swap_case(s):
for x in s:
    if x.isupper()==True:
        print(x.lower(), end="")
    else:
        print(x.upper(), end="")
s = input('Digite: ')
result = swap_case(s)
print(result)
    
asked by anonymous 29.01.2018 / 12:49

1 answer

5

A None appears because you are not returning anything in your function, you are just printing, change to:

def swap_case(s):
    for x in s:
        if x.isupper()==True:
            return x.lower()
        else:
            return x.upper()
s = input('Digite: ')
result = swap_case(s)
print(result, end="")

Enjoying to improve:

2- (MOST IMPORTANT) The function does not seem to make much sense so (it will return only the first letter changed), because what you should want with " swap_case " is to change all the letters string provided, so it does not make sense, what you should want is:

def swap_case(s):
    text = ''
    for x in s:
        if x.isupper():
            text += x.lower()
        else:
            text += x.upper()
    return text

s = input('Digite: ')
result = swap_case(s)
print(result)
  

Input: nElSoN
  Output: NeLsOn

STATEMENT

Reducing to a line within the function:

def swap_case(s):
    return ''.join(x.lower() if x.isupper() else x.upper() for x in s)

DEMONSTRATION

    
29.01.2018 / 12:51