Python if function returns nothing

How do you check if your function returns nothing?

Let’s write a program that asks for a list of numbers and describes the interesting ones using the personality traits below, while counting up all the dull ones without traits. Question: Some numbers have personality, while other numbers are just dull.

How do you check if your function returns nothing?

I’m trying to answer a question from a challenge.

Question: Some numbers have personality, while other numbers are just dull. Let’s write a program that asks for a list of numbers and describes the interesting ones using the personality traits below, while counting up all the dull ones without traits.

Your program should ask for a list of space-separated numbers. For any number with at least one trait, it should print a full description of its personality. Then it should print how many dull numbers were counted.

arrogant_numbers = [3, 6, 7, 23, 25, 35, 39, 66, 68, 112, 119, 254, 259, 732, 737, 4565, 4663, 13330, 13730, 29880, 29998, 79670, 80015, 230054, 239068, 1534301, 1607352, 2060587, 21700891, 99167753, 99873125] def find_personality(number): traits = '' # Find the traits of the number if number % 2 != 0: traits = traits + 'odd ' # Check for other traits after this if number >10000: traits = traits + 'excessive ' if '3' in str(number): traits = traits + 'irksome ' if number in arrogant_numbers: traits = traits + 'arrogant ' return traits # Write the rest of your program after this dullcounter = 0 numbers = input('Enter numbers: ') number_list = numbers.split() for word in number_list: trts = find_personality(int(word)) print(f" is an number.") if '' in trts: dullcounter = dullcounter + 1 print(f'Dull numbers: ') 

I’m having problems with counting the dull numbers (the ones that have no traits) it counts all the numbers given instead of the ones that have no traits.

desired output

Here’s how the final solution should look like:

my output

Here’s how my output looks like:

Your output string trts will always contain » .
Instead of this you should validate if trts is an empty string.
So, instead of

if '' in trts: dullcounter = dullcounter + 1 

you should use this or similar:

if not trts: dullcounter = dullcounter + 1 

The problem is that your function always returns a string, albeit an emtpy string if the number is dull. Try introducing logic that breaks out of the function if a number is dull (instead of returning an empty string).

Your if condition is always True. Use an alternative condition like this

if ****(trts) > 0: dullcounter = dullcounter + 1 

Recursive function returning none in Python, You need to return the recursive result: else: return get_path (directory [filename], rqfile, path) otherwise the function simply ends after executing that statement, resulting in None being returned. You probably want to drop the else: and always return at the end: for filename in dictionary.keys (): path = …

Читайте также:  Бесконечный цикл python tkinter

Why return nothing in class method?

I’ve recently started working at a company doing work in Python, and in their code they have a class which defines a handful of functions that do nothing, and return nothing. Code that is pretty much exactly

I’m really confused as to why anyone would do that, and my manager is not around for me to ask. Would one do this for the sake of abstraction for child classes? A signal that the function will be overridden in the future? The class I’m looking at in particular inherits from a base class that does not contain any of the functions that are returning nothing, so I know that at least this class isn’t doing some kind of weird function overriding.

Sometimes, if a class is meant to be used interchangeably with another class in the API, it can make sense to provide functions that don’t do much (or anything). Depending on the API though, I would typically expect these functions to return something like NotImplemented .

Or, maybe somebody didn’t get enough sleep the night before and forgot what they were typing . or got called away to a meeting without finishing what they were working on .

Ultimately, nobody can know the actual reason without having a good knowledge of the code you’re working with. Basically — I’d wait for your boss or a co-worker to come around and ask.

If the functions have meaningful names, then it could be a skeleton for future intended functionality.

Why is Tkinter Entry’s get function returning nothing?, A simple example without classes: from tkinter import * master = Tk () # Create this method before you create the entry def return_entry (en): «»»Gets and prints the content of the entry»»» content = entry.get () print (content) Label (master, text=»Input: «).grid (row=0, sticky=W) entry = Entry (master) entry.grid …

Python for loop within function not returning values

I wrote this fairly simple Python function but for some reason after the for loop ends, nothing returns or is able to be printed out within the function. I can call the function just fine and I called prints within the for loop to ensure the values were correct and they were. Am I missing anything obvious here? The print statement at the bottom prints nothing.

def evaluate_arima_model(X, arima_order, s_arima_order): scores = [] train_steps = [36, 48, 60, 72, 84] for i in train_steps: Train = X[0:i] Test = X[i:i + 12] model = SARIMAX(Train, order=arima_order, seasonal_order=s_arima_order) model_fit = model.fit(trend='nc', disp=0) yhat = model_fit.forecast(12) rmse = sqrt(mean_squared_error(numpy.exp(Test), numpy.exp(yhat))) scores.append(rmse) print(scores) return scores 

This is how the function is called (by another function with nested loops

def evaluate_models(dataset, p_values, d_values, q_values, sp_values, sd_values, sq_values, s_values): dataset = dataset.astype('float32') best_score, best_cfg, best_cfg2 = float("inf"), None, None for p in p_values: for d in d_values: for q in q_values: order = (p,d,q) for sp in sp_values: for sd in sd_values: for sq in sq_values: for s in s_values: sorder = (sp,sd,sq,s) try: rmse = evaluate_arima_model(dataset, order, sorder) if rmse < best_score: best_score, best_cfg, best_cfg2 = rmse, order, sorder print('ARIMA%s SARIMA%s RMSE=%.3f' % (order,sorder,rmse)) except: continue print('\n','Best ARIMA%s SARIMA%s RMSE=%.3f' % (best_cfg, best_cfg2, best_score)) series = read_csv('dataset.csv', header=None, index_col=0, parse_dates=True, squeeze=True) series = numpy.log(series) # Evaluate parameters p_values = range(0, 2) d_values = range(0, 2) q_values = range(0, 2) # Evaluate seasonal parameters sp_values = range(0, 2) sd_values = range(0, 2) sq_values = range(0, 2) #Set seasonality s_values = [12] #Call grid loop evaluate_models(series, p_values, d_values, q_values, sp_values, sd_values, sq_values, s_values) 

Output: Best ARIMANone SARIMANone RMSE=inf

Читайте также:  Java naming conventions class

New version still not working:

def evaluate_arima_model(X, arima_order, s_arima_order): scores = [] train_steps = [36, 48, 60, 72, 84] for i in train_steps: Train = X[0:i] Test = X[i:i + 12] model = SARIMAX(Train, order=arima_order, seasonal_order=s_arima_order) model_fit = model.fit(trend='nc', disp=0) yhat = model_fit.forecast(12) rmse = None rmse = sqrt(mean_squared_error(numpy.exp(Test), numpy.exp(yhat))) scores.append(rmse) print(scores) print(scores) return scores 

Your print() statement must print something. However, because you do not have a return statement, your function does not return anything (well, it returns None ). If you want your function to return something, add one last line:

DEBUG ATTEMPT:
In [1]: def evaluate_arima_model(X, arima_order, s_arima_order): . scores = [] . train_steps = [36, 48, 60, 72, 84] . for i in train_steps: . rmse = None . scores.append(rmse) . print(scores) . return scores . . In [2]: evaluate_arima_model(1,1,1) [None, None, None, None, None] Out[2]: [None, None, None, None, None] 

I do not see a reason for this to not work.

You need to write the return statement instead of print.

def evaluate_arima_model(X, arima_order, s_arima_order): scores = [] train_steps = [36, 48, 60, 72, 84] for i in train_steps: Train = X[0:i] Test = X[i:i + 12] model = SARIMAX(Train, order=arima_order, seasonal_order=s_arima_order) model_fit = model.fit(trend='nc', disp=0) yhat = model_fit.forecast(12) rmse = sqrt(mean_squared_error(numpy.exp(Test), numpy.exp(yhat))) scores.append(rmse) return(scores) 

Finally sorted this out, the issue was returning a list vs a scalar, which is what I needed. So "return scores[0]" fixed it.

def evaluate_arima_model(X, arima_order, s_arima_order): scores = [] train_steps = [36] for i in train_steps: Train = X[0:i] Test = X[i:i + 12] model = SARIMAX(Train, order=arima_order, seasonal_order=s_arima_order) model_fit = model.fit(trend='nc', disp=0) yhat = model_fit.forecast(12) rmse = sqrt(mean_squared_error(numpy.exp(Test), numpy.exp(yhat))) scores.append(rmse) return scores[0] 

Python - How to unit test a function that does not return, The function is used to compute the values of the variables that are passed to another function. The computation of the arguments is what I want to test and it is preferable if I can test it without moving it out to a new function. –

Источник

Python Function Return NoneType

Notesformsc

In the previous articles, you have seen various types of functions. Function either return a value or nothing. In this article, you will learn about functions that return a None. The None is the only value that belong to None Type.

When Python Functions Return None

There are a number of situations when a python function returns a None value. We have listed them here.

  • Functions purposely returns a None.
  • Functions that does not return anything and assigned to a variable.
  • Function that returns another function
Читайте также:  Html text overflowing div

Now, we will see an example of each of these cases.

Function That Returns a None

A function is created and does some calculation and returns None . Consider the following example to understand this.

def expression_1(num): if num > 100: return num + 100 else: return None result = expression_1(90) print(result)

In the example above example, if the number is less than 100 , the result will get a value of None . The output of the program is given below.

== RESTART:C:/PythonExercises/function_return_none.py == None >>> 

Function Returns Nothing

There are functions that does not return anything and in such case, the function automatically returns a None . The following example multiply two numbers but does nothing more than that. When the function is printed as output, the value of the output is None .

def multiply(n1, n2): result = n1 * n2 print(multiply(4, 7))

The output of the function is None . See below.

== RESTART: C:/PythonExercises/function_no_return.py === None >>> 

Function That Return Another Function

In this case, the function returns another function. The program cannot print another function, therefore, it is equal to None .

def printChar(): return print("D") result = printChar() print(result)

The output of the program is given below.

= RESTART: C:/PythonExercises/Func_Ret_OtherFunc.py = D None >>> 

The output above is interesting because it shows how the values are printed sequentially. First, the print("D") is executed and "D" is printed.The second print statement is executed after the function terminates. Therefore, the final output is None .

In the next article, we will discuss about advanced python functions.

Источник

Return nothing Python | Example code

There is no such term as “returning nothing” in Python. Every function returns some value. If no explicit return statement is used, Python treats it as returning None.

Return nothing python examples

To literally return ‘nothing’ use the pass keyword, it returns the value None if added in a function(Functions must return a value, so why not ‘nothing’). You can do this explicitly and return None yourself though.

def cal(x): if x > 1: return x else: pass print(cal(1)) 
def cal(x): if x > 1: return x else: return None print(cal(1)) 

Return nothing Python

Answer: There is nothing wrong with returning None. In most cases, you don’t need to explicitly return None. Python will do it for you.

def foobar(check): if check: return "Hello" print(foobar(False)) 

Output: None

Do comment if you have any doubts and suggestions on this Python basic tutorial.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Источник

Оцените статью