Here is my code in Python for returning a string in capitalized:
import math
import os
import random
import re
import sys
def solve(s):
name = list(s.split())
for i in range(len(name)):
nparts = name[i].capitalize()
return print (nparts, end = " ")
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
s = input()
result = solve(s)
fptr.write(result + '\n')
fptr.close()
When I run only the function then the result is ok, but when I try to write the result in a file then I get the error below:
fptr.write(result + '\n')
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'
By manually checking I found that when I am storing the result into the result variable it also gets an extra value "None". I have no idea why this is going on. Please help.
Your def solve(s):
function doesn't return anything so by default it returns None
Fix it to:
def solve(s):
name = list(s.split())
return name
To capitalize each word a sentence:
split
it capitalize
each wordjoin
them by spaceimport os
def solve(sentence):
return " ".join(word.capitalize() for word in sentence.split())
if __name__ == '__main__':
s = input("Give a sentence: ")
result = solve(s)
with open(os.environ['OUTPUT_PATH'], 'w') as fptr:
fptr.write(result + '\n')
When the programmer does not define functions to return anything, Python function by default return None
. This is the thing that is happening in your program.
The function solve
does not return anything and so returns None which gets stored in the variable result
when the function is called
A change that you can make in your program is to return the name.
def solve(s):
name = list(s.split())
return name
Also, in your program, a return
statement cannot be used within a for
block. Moreover, name
is not defined in your main
program. A tip to fix it would be to change the variable name from name
to result
in your for loop and place the for block after calling the function:
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
s = input()
name = solve(s)
for i in range(len(name)):
nparts = name[i].capitalize()
print (nparts, end = " ")
fptr.write(name[0] + '\n')
fptr.close()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.