Reputation: 119
I am using python3. I am trying to write to write a program that in case an input string is even returns the two middle characters and in case it is odd it returns the middle character. I believe the task to be simple but my code returns and unwanted None
in the output.
def get_middle(s):
if len(s)%2==0:
#recall that division of two integers outputs a float so I gotta integer it back
print(s[int(len(s)/2)-1]+s[int(len(s)/2)])
else:
print(s[int(len(s)/2)])
print(get_middle("house"))
print(get_middle("houses"))
The output for the code below is
u
None
us
None
I just don't see where the None is slipping into my code. Any ideas?
Upvotes: 1
Views: 135
Reputation: 1723
So basically when you say print(get_middle(s))
, python prints what the function returns, which in your case is None
since there is no return
statement.
You can do 2 things here: 1. Return the required value from the function and let the code calling the function print it.
def get_middle(s):
if len(s)%2==0:
#recall that division of two integers outputs a float so I gotta integer it back
return s[int(len(s)/2)-1]+s[int(len(s)/2)]
else:
return s[int(len(s)/2)]
print(get_middle("house"))
print(get_middle("houses"))
I would personally prefer 1 since function is named ger_middle
, so it should just get you the middle. Doing whatever you want with the middle should be the job of the code that calls it.
Upvotes: 2
Reputation: 1735
I think what you mean to do is return
the values you calculate inside get_middle
rather than print
them. i.e.:
def get_middle(s):
if len(s)%2==0:
#recall that division of two integers outputs a float so I gotta integer it back
return (s[int(len(s)/2)-1]+s[int(len(s)/2)])
else:
return (s[int(len(s)/2)])
print(get_middle("house"))
print(get_middle("houses"))
Upvotes: 1
Reputation: 4553
get_middle
doesn't return anything, so when you print its return value, it prints 'None'.
Upvotes: 1