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 7 years ago.
Improve this question
I am making an algorithm that converts numbers into roman numerals, which involves an array. However, when I run my code, I tell it to check if they array exists, and create it if it doesn't (I use this complex method because the code has to restart itself a lot, you will see).
number = input("What number would you like to convert?")
number = int(number)
def alg(n):
if 'roman' in locals():
print("yes")
if n >= 1000:
roman = roman + ["M"]
n = n - 1000
print(roman)
print(n)
#alg(number)
else:
print("end")
else:
print("no")
roman = [""]
print(len(roman))
print(locals())
alg(number)
alg(number)
I have tried researching it on the Python documentation and on this site, but to no avail.
Every invocation of a function has its own set of local variables. Your check will always return false, because you have just entered the function.
If you want to keep the recursive implementation that you currently have, you should pass the roman variable as a second parameter to the alg function.
Are you sure you want to find it in locals() (which will only look in the scope of your function alg which is just starting, thus cannot containing your roman variable) ?
Maybe you want to look up into globals variables with globals() ?
You check for the word 'roman' in locals; this is not going to happen, as you have yet to define roman. A function's locals do not persist from call to call.
Your decrement
n = n - 1000
doesn't do anything useful (yet). The local copy of n gets changed, but you never use it. The original copy (from the main program) is still intact, as integers are not mutable.
Note that your recursive call passes number -- the main program's original number. You're always converting the original, never working on the smaller quantity.
I'll stop here: without design, structure, or comments, this code is a bit hard to follow.
Related
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 22 days ago.
Improve this question
I am a beginner and need to know what a function for a small tic tac toe project. But all I need to know is this as understood the rest. is and how to use one as well as what can they do
I was just learning from the python docs about a function and could not understand, as I was searching on google still, I could not find anything, if one could help, it would help me loads.
This is the code for my tic tac toe that the YouTuber gave as an example:
def cool(a,b):
return(a+b)
print(cool)
Thanks,
Gops
Welcome to the world of programming.
As a beginner, you should imagine functions as "reusable" part of your code, with the feature of having temporal variable that can change the behavior of the function based on the body of the function.
Calling the functions
To reuse that part of your code that you wrote in your function, you have to call it.
def python_cool():
print("Python is cool")
python_cool()
python_cool()
python_cool()
Technically, this code is the same as:
print("Python is cool")
print("Python is cool")
print("Python is cool")
At this point, if you we are talking about parameters, we have to talk about arguments too.
Parameters
Parameters are the one that you are declaring your function with:
def sample_function( paramter1, parameter2, paramterN ):
Arguments
Arguments on the other hand, are the values when you are calling the function with.
sample_function(argument1, argument2, argumenN)
Example
def print_values( value_1, value_2) :
print("The first value is: ", value_1)
print("The second value is: ", value_2)
print_values(1, 2)
print_value(True, False)
print_values("apple", "peach")
Return values
Another great benefits of functions that they are able to "become" a value that you can store in a variable in the future
For example:
def multiply_by_three( number ) :
return number * 3
This function has a return value of an integer which can be used as:
sample_variable = multiply_by_three(5)
which is technically:
sample_variable = 15
In Python, a function is a block of instructions or code that is used to perform an action. Functions provide an organized way to structure code, making it easier on the human eye. It seems as if you are tired to add a and b, however, a and b are not given values in the return statement.
I self-learned python and would look at the W3Schools stuff which is quite good.
A function is, in effect, a way of running a section of code with a keyword, if you had
def cool(a,b)
print(a+b)
cool(1, 3)
You would have the function running the code you have put inside it and so printing the value of a+b (4) using the values a and b which were passed into the function.
The code you posted would not work because to run the function, a and b need to be passed, which is not done in the question.
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
After receiving an error in the code below i ended up adding
new_list = []
summation = 0
after the second line. But i fail to understand why i had to do that. I thought variables did not have to be declared early on in python
a = int(input())
b = int(input())
while a <= b:
if a % 3 == 0:
new_list.append(a)
a += 1
for number in new_list:
summation += int(number)
print(summation / len(new_list))
In general, Python does not require variables to be declared (except for a couple of cases). In this case, you are not declaring a variable but rather initializing it. Let's imagine that variables are boxes. In python, you don't have to say, please make a box and call it x. The issue is when you come across summation += int(number). This tells python, please take out whatever is in the box called summation, add int(number) to it, and put it back in the box. But you haven't yet put anything in the box. So python says sorry, there's nothing in the box at the moment so I can't take anything out. Same for new_list.append(a), that asks python to please append a to whatever is in the box. So python looks in the box to figure out how to append something to it but it can't find anything so it shows an error.
You may ask, why doesn’t python just put 0 in the box? Well, python doesn't know that what you want in the box is an int. Maybe you wanted a fraction, a complex number, or something you make up yourself that happens to be able to be added to a number. The same goes for the list, python does not know that you wanted a list and not a set, dictionary, tuple, counter, queue, or some other collection. So rather than guess, and possibly get it wrong (which would cause all kinds of weird bugs due to the slight differences in how these work with addition), it just gives you an error.
It depends on what you're doing with the variable. If you're assigning a value to the variable, it will initialize the variable in the loop itself. But if you want to modify a variable like you did with .append(), you have to declare it first as it has to be declared to be modified.
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 3 years ago.
Improve this question
I have a function in Python, and in that same function i have multiple if statements. Lets say i want to return a value from my function. I create a local variable and change it in if statements. Problem is i need it to be defined in function so it works in every if statement, but unlike in C i cant use int a, b, c; but instead i have to give them a value. Problem is that value is going to be recognized if none of the if statements are true.
One clear solution is to take in global values as parameters of the function but i dont want to do that because i dont need their value i only want to change it.
velocity = 5
distance = 6
def calc(distance):
# i would need to say velocity = 5 here
distance + velocity # this does nothing but uses velocity so code cant run
if distance < 7 : # without defining velocity first (in first comment)
velocity = 6
elif distance < 10:
velocity = 7
return velocity
If you really don't want velocity to be a parameter of the function then build an object that has velocity as member variable and calc as method.
When writing Python functions, it is a good idea to strive to follow the following design principles, which come from functional programming.
A function's output should only depend on its inputs. That means that everything that influences the result should be a parameter of the function. This is generally easy to do, and makes the function self-documenting. When you write def foo(x, y, z), it is immediately obvious that the result depends on x, y and z.
A function preferably should only return its output. So it should not use global to modify variables outside of its scope, nor should it modify mutable arguments. (This cannot always be achieved in practice, but it is good to strive for.)
The main advantage is that such functions can be tested and debugged apart from the rest of the application, making those tasks much easier.
In this case,
def calc(distance)
should be:
def calc(distance, velocity)
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 8 years ago.
Improve this question
What happens to variables assigned for the first time (defined) inside if statement or for loop if long time passed from when their code run. Is there some sort of garbage collection that may result in a not defined variable exception. For example:
if True:
a=1
else:
a=3
# long time passed and other codes run
# .
# .
# .
print (a)
I encountered an error in my code that I suspect this to be the reason. Is it documented somewhere in official Python documentation ?
In Python, if you define a variable within an if statement, it will continue to exist after the if statement concludes. Scopes are defined for a class, a def, or the global scope; if you're in a function and you define a variable inside if, for example, that variable will exist until the function is done executing.
Be careful, however, of defining variables in code like this:
if x == True:
a = 1
else:
print "Not true"
If you have code like this, and x ends up being False, then a will not be defined. Later calls to a will throw an exception as a result. So make sure that you get rid of any potential problems of that sort.
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 9 years ago.
Improve this question
Following is my function definition
def func_a():
return 1
def func_b(val1):
return val1*2
And this is one way of calling the function:
count = 0
while count < 10000000:
val2 = func_b(func_a())
count += 1
time taken for above is:
real 0m5.003s
user 0m4.989s
sys 0m0.012s
For the below usage with the same function definition:
count = 0
while count < 10000000:
ret1 = func_a()
val2 = func_b(ret1)
count += 1
the time taken is
real 0m5.502s
user 0m5.414s
sys 0m0.010s
I did about 10 runs each and the real time difference between the two was always ~300-500 ms.
Whereas the sys time was usually only about ~1-2 ms different. (max of about 10 ms).
The application I work with deals with about 60-90k transactions with sub millisecond performance, so this is kind of big for me. Why is there this much difference between the two invocations?
EDIT NOTE: The below answer is not much relevant now after the question revamp, please see the question edit for the original question.
From readability perspective (and code maintenance ?) I guess the
first one is better?
Actually the second one is better, especially if you are not using the return value of function_a anywhere else. Otherwise, the first line will create a name that may cause a namespace clash. Consider this:
foo = 42
# many many lines of code later
foo = function_a()
result = function_b(foo)
print foo # oops!
Is the second one better from memory perspective
The cost is insignificant.
Which of the two is better in terms of
performance?
There is no performance benefit that you can get from one approach or the other that would create any practical impact in your application.
It doesn't matter. There might be an incredibly minor speed advantage due to skipping a few loads and stores without the intermediate variable, and using the variable might extend the lifetime of a temporary a bit, slightly affecting memory usage patterns, but the difference isn't even worth considering. In different situations, one might be more readable than the other. Try to avoid ultra-long lines, and if you're going to pull pieces out of an expression for readability, try to pick meaningful pieces.
The disadvantage of the former approach is that you generate intermediate variables that should never be used again, and you or somebody else might accidentally write one of them (that is, later use "val1" instead of "val2"). Intermediate values are not a serious issue, but they do occasionally cause programming mistakes.
The latter approach may be a little less readable. It looks a lot better in an object oriented context:
val2 = function_a().function_b()