How to update a variable inside a function? [closed] - python

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I have a question about two different ways of writing a piece of code. I want to know whether they are both okay or one is better under some conditions? Basically, is it better to give the variable we want to update to the function or not?
def f1(num):
output.append(num)
output = []
f1(2)
print(output)
and
def f1(num, output):
output.append(num)
output = []
f1(2, output)
print(output)

In the first example, your function works for only adding element to globally defined certain array. And it is not good approach, you cannot use it for another array.
Second one has generic approach which is better. But only one small correction; you have an array named output, and you pass it to your function, but you keep its name same in your function. So, for your function, there are two output one global and one local, better use different names in this case:
output = []
def f1(num, arr):
arr.append(num)
f1(2, output)
print(output)
Please see warning PyCharm shows in same naming case:

Consider avoiding to use the first example where possible: global variables can be very difficult to work with, generating problems you never find easily. Instead, use the second piece of code.
You could also write something like the following code:
output = []
def add(num, listName):
listName.append(num)
return listname
for _ in range(5):
output = add(_, output)
print(output)

Related

check unreachable code in most simple way in python [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 12 months ago.
Improve this question
I have a python code with is detect any errors in another python code saved in txt file, i did that i can detect magic numbers and more than 3 parameters in the function, and now i have to check un reachable code, but i don't have an idea how can i do it, i want to detect if there's a code after return in the function, i did several attempts and all of them failed
This main class :
class CodeAnalyzer:
def __init__(self, file):
self.file = file
self.file_string = ""
self.errors = {}
this is a method where it's pass detects function so i can print errors :
def process_file(self):
for i, line in enumerate(self.file):
self.file_string += line
self.check_divide_by_zero(i, line)
self.check_parameters_num(i, line)
and for example this is check parameter function, i need to write similar one but to detect unreachable code :
def check_parameters_num(self, i, line):
count = line.count(",")
if(line.startswith('def') and count+1 >= 3):
self.errors.setdefault(i, []).append(('S007', ''))
Any one can help and have an idea ?
Probably you would have to use the ast module to look at the parse tree.
Look for:
Conditions for if and while statements that are always False. (or always true in case of an else) This would involve "constant propagation", that is realizing that an expression that only depends on constants is itself constant.
Code after a return, without that return being part of an if.
Code at the end of a function that is indented incorrectly an thus in the module context.
Or you could look at how mypy is doing it.

How to pass a 2-dimensional list to a function? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
this is my first post.
The Problem:
I have 2-Dimensional-list which is decleared and filled in a function - looks like this: data = [[1, 2, 3, 4], [10, 20, 30, 40]] - Now I want to pass that list from this function to another to continue working with the list.
I think that you're wanting to do something like this:
def myfunction():
data = [[1,2,3,4],[10,20,30,40]]
return data
def function2(myList):
# do stuff with it here
myList = myfunction()
function2(myList)
But your question is not very clear.
I think it's not an issue with python. Python allows You to pass multidimension lists to functions.
There shouldn't be any issue with this.
just pass like a simple variable.
I think I know your problem, it is the same process to pass a multidimensional array to a function as any other variable, the problem is other code, python is really annoying with tabs and spaces and it can cause confusing errors aside from the usual inconsistent use of tabs and spaces error. Just try deleting the function that's not working and rewrite it and you'll probably fix your error

Not Match Between Argument Passed and List Available [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
The community is reviewing whether to reopen this question as of 2 years ago.
Improve this question
I was working with Python3, and trying some sorts of code. And then i came to try some function features, here is my code
def print_list_members(some_list):
for i in first_list:
print(i)
that's all my function definition. and then i add for example new to the code
first_list = ["Alfried", "Michael", "John"]
second_list = ["Joseph", "Tim", "Delta"]
then i try to produce traceback by passing different argument with the function code
print_list_members(second_list)
but, no traceback raised, except something make me a bit confused, the output is
Alfried
Michael
John
the question is, how it be possible? or is it an error from python itself?
Change your code here
def print_list_members(some_list):
for i in some_list:
print(i)
You iterate over the global first_list inside the body of the function, so you print first_list. Whatever you pass as an argument is ignored. Perhaps you wanted iterate over some_list?

Output of a function used as an input for another [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
Last question about this topic.
I didn't add the output as its not the issue rather then passing of the output. Basically the final output of each function is a list. I am running into a problem. So this is the code I have
def mean(studentp_file):
li = []
for line in studentp_file:
nameless = line[1:14]
for l in range(len(nameless)):
answer = sum(nameless)/len(nameless)
li.append(answer)
li.insert(0,"Needie Seagoon")
li.insert(2,"Eccles")
li.insert(4,"Bluebottle")
li.insert(6,"Henry Crun")
li.insert(8,"Minnie Bannister")
li.insert(10,"Hercules Grytpype-Thynne")
li.insert(12,"Count Jim Moriarty")
li.insert(14, "Major Dennis Bloodnok")
mean_li = li
return mean_li
passing_file = normalise("DB.csv.", "units.csv")
mean(passing_file)
"""
This function will print out the final mean average percentile for each student over
their computer science degree.
"""
def final(mean_li):
~ wanted to see if the code worked.~
print(mean_li)
mean_list = mean(studentp_file)
final(mean_list)
The problem I am having is passing the variable mean_li into the new function final(). I get the error mean_list = mean(student_file) is not defined? I was able to pass output of another function into the previous function but for some reason I can't do it here.
Any help would be great.
I guess the error is studentp_file is not defined. The variable studentp_file is only valid inside the definition of function mean. Outside of that function, you are using passing_file variable. This should work
mean_list = mean(passing_file)

According to style is it right to put a funcion like parameter when ending an aplication with sys.exit() in python? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have seen a code written like this:
if __name__ == "__main__":
#...
result = someFunction(someParameter)
sys.exit(result)
and even like this, where you write the call of the function in the sys.exit() function:
if __name__ == "__main__":
#...
sys.exit(someFunction(someParameter))
Which is the most correct option according to style?
Both are equivalent, but I think you know this. If you are asking from a style perspective, I'd say you should always favour the option that is more readable. In this case, I think the first one is more readable.
Python uses snake_case by convention so you might consider also using that to define your variables and functions.
You might also want to change the name of the result variable to be more descriptive.
exit_status = some_function(some_parameter)
sys.exit(exit_status)
Hopefully, this was what you were after.
Edit: #AnttiHaapala made a good point that succeeded isn't the best variable name either as 0 is Falsy in Python but considered a pass as an exit code. I've renamed it to exit_status.

Categories