Home > database >  Python functions not running correctly
Python functions not running correctly

Time:05-26

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__":
    string_upper(up)
    string_lower(low)

Any idea on how to fix this?

The error is: NameError: name 'up' is not defined

CodePudding user response:

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
    string_lower(s)

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())

CodePudding user response:

One of the problems you are having is that you are returning a value before printing the output, try printing the value first, and then returning a value.

The return will prevent the rest of the code in the function from running...

CodePudding user response:

When you return inside the function it mean function had ended. So to print result you can print value returned in main

string = input("Enter any string: ")

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

def string_lower(low):
    return low.lower()

if __name__ == "__main__":
    print("Uppercase Output: ",string_upper(up))
    print("Lowercase Output: ",string_lower(low))
  • Related