That's correct behaviour. remove removes that element and doesn't return a value (i.e. returns None). You can use pop if you wish to access the removed element.
I'm trying to write all the multiples of 7 from 0 to 100 (0 also being a multiple of 7), using a function called "multiple", but I get "None" at the end of the output.
How can I fix my code so that the "None" disappears?
my code:
def multiple(start, end):
for number in range(start,end):
if number % 7 == 0:
print(number, end=" ")
number += 1
print(multiple(0,100))output:
0 7 14 21 28 35 42 49 56 63 70 77 84 91 98 None
Videos
That's correct behaviour. remove removes that element and doesn't return a value (i.e. returns None). You can use pop if you wish to access the removed element.
somelist.remove(x) removes the first element it finds that equals x from somelist. It doesn't return the modified list. To print the modified list, simply print the list.
print(Question_tk_l)
If you want to turn it into a nice string, you should join it with space.
print(' '.join(Question_tk_l))
Python will always return None, if no return is specified at the point of exiting the function call. Your options are:
- return something else if the condition is not met.
- ignore the function if it returns
None
option 1 (return something else when the condition isn't met):
def html_check(td, text):
if td.text == text:
value = td.find_next('td').text
return value
return "no value found"
option 2 (ignores the function if None is returned):
if html_check(td, 'section'):
# do things
You can specify a default value, to return, in case no element matches. Something like:
def html_check(td, text):
if td.text == text:
value = td.find_next('td').text
return value
return "Default Value"
Also, you can spcify the default value via argument, which would somewhat look like :
def html_check(td, text, default_value):
if td.text == text:
value = td.find_next('td').text
return value
return default_value
And, then use it like:
for tr in table_body.find_all('tr'):
for td in tr:
description= html_check(td, 'Description', 'Default Description')
category = html_check(td, 'Category','Default Category')
department = html_check(td, 'Department', 'Default Department')
justification = html_check(td, 'Justification', 'Default Justification')
print(description, category, department, justification)
You are printing the return value of your function, and printing inside the function. Remove the print statement you are using to print the return value of the call.
Where you do:
print weather_Connection(interval, api_key)
remove the print:
weather_Connection(interval, api_key)
A function in Python always has a return value, even if you do not use a return statement, defaulting to None:
>>> def foo(): pass # noop function
...
>>> print foo()
None
The alternative is to not use print in your function, but return a string instead:
def weather_Connection(interval,apikey):
result = [
print_forecast('Choa Chu Kang',get_response('/forecast/apikey/1.394557,103.746396')),
print_forecast('Yishun',get_response('/forecast/apikey/1.429463,103.84022')),
print_forecast('Redhill',get_response('/forecast/apikey/1.289732,103.81675')),
print_forecast('Jalan Besar',get_response('/forecast/apikey/1.312426,103.854317')),
print_forecast('Jurong West',get_response('/forecast/apikey/1.352008,103.698599')),
print_forecast('Tampines',get_response('/forecast/apikey/1.353092,103.945229')),
]
return '\n'.join(result)
Remove the print() call, the function is returning None.
The default return value of a function is None in python. If you're printing inside a function and not returning anything from it then there's no need of print() when calling the function.
Demo:
>>> def func():
... print ("foo")
...
>>> print(func())
foo
None
>>> func() #works fine without `print()`
foo
There is nothing wrong with returning None.
In most cases, you don't need to explicitly return None. Python will do it for you. This is an altered version of your foobar which behaves identically without explicitly returning None:
def foobar(arg):
if check:
return result
# If not check, then None will be returned
Still, even if Python implicitly returns None, there is a value in being explicit; Your code becomes easier to read and understand. This is a constant trade-off for which there is no general answer.
I think returning None is a "no go" from a usability standpoint rather than style. As briefly mentioned in this answer, consider raising an exception instead. For example:
def foobar(arg):
# connect to page by httplib
# check for arg in a certain pattern by lxml
if not check:
raise ValueError("arg did not match pattern in lxml")
return result
try:
result = foobar(arg)
except ValueError:
result = None
if result is not None:
# do stuff
else:
# do other stuff
The advantage of this approach is that it makes it explicit when there is not a match. Other people using your function won't need to know that None is the return value they should expect when there isn't a match and they can handle the exception as they see fit.
You can use a generator expression with in str.join to remove all uppercase letters, which are enumerated in string.ascii_uppercase
from string import ascii_uppercase
def remove_capitals(a_string):
return ''.join(i for i in a_string if i not in ascii_uppercase)
>>> print(remove_capitals("A1B2C3D"))
123
>>> print(remove_capitals("Georgia Institute of Technology"))
eorgia nstitute of echnology
Use isupper,
def remove_upper_case(x):
return ''.join(i for i in x if not i.isupper())
Execution:
In [281]: remove_upper_case("Georgia Institute of Technology")
Out[281]: 'eorgia nstitute of echnology'
In [282]: remove_upper_case("A1B2C3D")
Out[282]: '123'
https://youtu.be/EY-oLHxpKrI
Several weeks ago a was pursuing some of the posts here on python and stumbled on an article about bad programming habits. I cant find the article again for reference but right at the top was a heady warning to avoid returning a meaningful None. AT the time I thought, 'well thats just droll and I never do that anyway', but as it turns out I do it all the time. If the function finds the correct thing then return the correct thing otherwise just end the function and python will return None for you.
So do you guys do the same thing? Whats wrong with returning None in the first place? What strategies do you use to avoid returning None?
Might not be exactly on topic but I wish more people would code their functions to NOT return None and instead return expected type.
BeautifulSoup is the biggest perpetrator of this. Whenever you parse the tree/soup you'll either get a list of results or a single result, now if no results are found instead of getting an empty list you get None returned, which in turn requires you to make checks on every single lookup which really messes up your code up and makes everything look ridiculous.
switched to lxml/xpath and never looked back.
Per PEP-20, explicit is better than implicit, so when I'm writing code where None is a valid answer, I explicitly return a None. If it's an error to get to the end, raise an error.
If it's a hack/preliminary code, I don't care. For production level code, I have one return and it's the last line of the function/method. For a short function, I don't really care, but definitely for a long function.
remove doesn't return anything. It modifies the existing list in-place. No assignment needed.
Replace
var = ['p', 's', 'c', 'x', 'd'].remove('d')
with
var = ['p', 's', 'c', 'x', 'd']
var.remove('d')
Now var will have a value of ['p', 's', 'c', 'x'].
remove mutates the list in-place, and returns None. You have to put it in a variable, and then change that:
>>> var = ['p', 's', 'c', 'x', 'd']
>>> var.remove('d') # Notice how it doesn't return anything.
>>> var
['p', 's', 'c', 'x']
Like you said, return None is (almost) never needed.
But you should consider that the intention of your code is much clearer with an explicit return None. Remember: a piece of code also needs to be readable by human-beings, and being explicit usually helps.
To expound on what others have said, I use a return None if the function is supposed to return a value. In Python, all functions return a value, but often we write functions that only ever return None, because their return value is ignored. In some languages, these would be called procedures.
So if a function is supposed to return a value, then I make sure all code paths have a return, and that the return has a value, even if it is None.
If a function "doesn't" return a value, that is, if it is never called by someone using its return value, then it's ok to end without a return, and if I need to return early, I use the bare form, return.