Python functions not running correctly

I’ve written this code to convert a string to uppercase and lowercase, however when I call my functions, it doesn’t run.

# take the input for the string
string = input("Enter any string: ")

def string_upper(up):
    return up.upper()

    print("Uppercase Output: ", string_upper(string))

def string_lower(low):
    return low.lower()
    print("Lowercase Output: ", string.lower(string))

if __name__ == "__main__":

Any idea on how to fix this?

The error is: NameError: name ‘up’ is not defined

>Solution :

In your code, you are calling string_upper(up) but up is not defined anywhere and that is why you got the error. Same problem is for string_lower().

Another problem is you are returning from string_upper() and string_lower() but not using the return values anywhere. Apart from that you have a print statement in those two functions after the return statement. So, those print statements will never be executed and nothing will be printed in the output.

If you just want the upper case and lower case of input to be printed, you can modify the functions like below –

def string_upper(s):
    print("Uppercase Output: ", s.upper()) # Only printing the values and not returning

def string_lower(s):
    print("Lowercase Output: ", s.lower()) # Same as string_upper

Notice that lower() and upper() doesn’t take any parameters. And to call those functions you should do like this –

if __name__ == "__main__":
    s = input("Enter any string: ")
    string_upper(s) # the functions will print, so no need to capture return values

For simple conversion like to upper or lower case you can skip function altogether and just do –

if __name__ == "__main__":
    s = input("Enter any string: ")
    print("Uppercase Output: ", s.upper())
    print("Lowercase Output: ", s.lower())

Leave a Reply