def findNumber(arr, k):
if k in arr:
print( "YES" )
else:
print( "NO" )
if __name__ == '__main__':
arr_count = int(input().strip())
arr = []
for _ in range(arr_count):
arr_item = int(input().strip())
arr.append(arr_item)
k = int(input().strip())
result = findNumber(arr, k)
fptr.write(result + '\n')
fptr.close()
While this runs just fine on Pycharm, on HackerRank i get the error:
Traceback (most recent call last):
File "Solution.py", line 42, in <module>
fptr.write(result + '\n')
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'
Would really appreciate if you could point out what the error might be.
Your function def findNumber(arr, k): does not return anything, so it returns None implicitly.
These lines
result = findNumber(arr, k)
fptr.write(result + '\n')
then try to add None and a string together - which does not work.
Instead of printing inside your function, return "Yes" or "No".
findNumber returns Nothing, so it automatically returns None. You have to replace the "print" in your function with return statements.
Related
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
loop on it to capitalize each word
join them by space
import 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()
I have this error when running the following program and I don't understand why:
Traceback (most recent call last):
line 18
main() line 13, in main
nombre=condition(nombre)
line 3, in condition
if (nombre % 2) == 1:
TypeError: unsupported operand type(s) for %: 'NoneType' and 'int'
Here is my program:
def condition(nombre):
if (nombre % 2) == 1:
nombre=(nombre*3)+1
else:
nombre=(nombre/2)
def main():
nombre=int(input())
print(nombre)
while nombre!=1:
nombre=condition(nombre)
print(nombre)
main()
This error occurring because you doest returning value from condition function and in second iteration of your while != 1 value of nombre was equal to def. try this to fix your code:
def condition(nombre):
if (nombre % 2) == 1:
nombre=(nombre*3)+1
else:
nombre=(nombre/2)
return nombre
if you want that condition return integer value you should use // instead of / :
def condition(nombre):
if (nombre % 2) == 1:
nombre=(nombre*3)+1
else:
nombre=(nombre//2)
return nombre
You are getting NoneType from condition function since it doesn't return anything.
I'm currently working through Automate the Boring Stuff with Python book and run into curious issue on chapter 7.
When trying to execute the following code:
def isPhoneNumber(text):
if len(text) != 12:
return False
for i in range(0, 3):
if not text[i].isdecimal():
return False
if text[3] != "-":
return False
for i in range(4, 7):
if not text(i).isdecimal():
return False
if text[7] != "-":
return False
for i in range(8, 12):
if not text[i].isdecimal():
return False
return True
print("415-555-4242 is a phone number:")
print(isPhoneNumber("415-555-4242"))
print("Moshi moshi is a phone number:")
print(isPhoneNumber("Moshi moshi"))
I get the following error message:
Traceback (most recent call last):
File "automation.py", line 27, in <module>
print(isPhoneNumber("415-555-4242"))
File "automation.py", line 13, in isPhoneNumber
if not text(i).isdecimal():
TypeError: 'str' object is not callable
Switching the str.isdecimal() method for str.isdigit() method allows me to execute the code properly, but I would like to know why the isdecimal() method will not work?
The error has nothing to do with isdecimal(). You have a typo in how you extract the character from text. The
if not text(i).isdecimal():
should read
if not text[i].isdecimal():
(note the square brackets.)
File "automation.py", line 13, in isPhoneNumber
if not text(i).isdecimal():
TypeError: 'str' object is not callable
The typeError is on line 13, where you are calling a string object. Use [] not ()
this is my script, i am new to python but have come to get this, please be forgiving as such in the answers and keep in mind that i am new to this.
import functools
numbers=[]
def means():
end_mean = functools.reduce(lambda x, y: x + y, numbers) / len(numbers)
print(end_mean)
def sum():
end_sum = functools.reduce(lambda x, y: x + y, numbers)
print(end_sum)
def whatDo():
print('Input Extra Numbers '+str(len(numbers)+1)+' (or nothing to close):')
try:
number= int(input())
numbers.append(number)
except:
print('What do you want to do?')
answer = input()
if answer == "mean":
means()
while True:
print('Input Number '+str(len(numbers)+1)+' (or nothing to close):')
try:
number= int(input())
numbers.append(number)
except:
print('What do you want to do?')
answer = input()
if answer == "mean":
means()
print('Do you want anything else?')
reply=input()
if reply=='no':
break
elif reply--'yes':
whatDo()
else:
break
However i get this:
Traceback (most recent call last):
File "E:/Python/calculator.py", line 26, in <module>
number= int(input())
ValueError: invalid literal for int() with base 10: ''
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "E:/Python/calculator.py", line 37, in <module>
elif reply--'yes':
TypeError: bad operand type for unary -: 'str'
after the 'Do you want anything else' and i enter 'yes'.
elif reply--'yes': should be elif reply == 'yes':
You had a typo
elif reply--'yes'
it should be, of course
elif reply=='yes'
How can I return the commented out line below the print statement at the end of this function? Also, when I run the function with the return un-commented, I get one result, but when I run the function with the return commented, I get 7 results and I'm not sure why this is happening.
What I would like to do is call track['name'] after I call the function. When I do, I get this error Traceback (most recent call last):
File "spot.py", line 25, in
track['name']
NameError: name 'track' is not defined
import requests
import json
message = "if i can\'t let it go out of my mind".split()
size = len(message)
def decrementList(words):
for w in [words] + [words[:-x] for x in range(1,len(words))]:
url = 'http://ws.spotify.com/search/1/track.json?q='
request = requests.get(url + "%20".join(w))
json_dict = json.loads(request.content)
track_title = ' '.join(w)
num_words_removed = len(words) - len(w)
new_message_length = size - num_words_removed
new_message = message[new_message_length:size]
for track in json_dict["tracks"]:
if track["name"].lower() == track_title.lower():
print track["name"], " | ", track["href"], " | ", track_title, " | ", num_words_removed
#return track["name"], track["href"], track_title, num_words_removed
decrementList(message)
A return statement causes the function to stop executing and return the value you have specified, whereas with a print statement it just causes something to be output to the terminal, and the function continues to execute.
In order to use the value that is returned from the function, you must do something with it, like assign it to a variable. For example:
track = decrementList(message)
but in that case, you would want to return the track:
for track in json_dict["tracks"]:
if track["name"].lower() == track_title.lower():
return track