Python Forum

Full Version: Why doesn't this print function work?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
The problem:
Given a string, return a new string where the first and last chars have been exchanged.


str='abfdas'

def front_back(str):
    if len(str)<=1:
        return(str)
    x=len(str)
    y=str[x-1]+str[1:x-1]+str[0]
    return y
print(front_back(a))
print(y)
Why does print(y) give off the error "name 'y' is not defined?"

Also is line 5 necessary, if so what does it do?
in your example, you never set a value for a, in addition
str is a keyword. Use a different name:
astr='abfdas'

def front_back(val):
    x=len(val)
    if x > 1:
        val = val[x-1]+val[1:x-1]+val[0]
    return(val)


print(front_back(astr))
You should now that slicing allows for negative indexes

def front_back(astr):
    if len(astr) < 2:
        return astr
    else:
        return ''.join((astr[-1], astr[1:-1], astr[0]))
    
    
for astr in ['abcd', 'a', '']:
    print(front_back(astr))
Output:
dbca a
Quote:Why does print(y) give off the error "name 'y' is not defined?"
Because the print() is outside of the function. and "y" is never declared outside of the function.