Python Forum
Why doesn't this print function work?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Why doesn't this print function work?
#1
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?
Reply
#2
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))
Reply
#3
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
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#4
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Why does this function print empty list? hhydration 1 1,529 Oct-28-2020, 02:03 AM
Last Post: deanhystad
  Question on "define function"; difference between return and print extricate 10 4,719 Jun-09-2020, 08:56 PM
Last Post: jefsummers
  How to print the docstring(documentation string) of the input function ? Kishore_Bill 1 3,543 Feb-27-2020, 09:22 AM
Last Post: buran
  Hi, my loop yes/no part doesn't work and I really need help fordxman5 2 2,602 Feb-14-2018, 11:38 PM
Last Post: Larz60+
  I Can't Get This Sorting Function In This LinkedList Code To Work JayJayOi 10 7,918 Jan-11-2018, 01:14 AM
Last Post: JayJayOi

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020