How does I aware from this type of errors in python [closed] - python

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 written a code having an function
Def product(a,b,c)
And declared those values at the end
But when I'm using these variables in program or if and else statements
It is showing an undefined 'a' name error
Please help me it always showing this error how to rectify it.

The Error's on your code were due to:
incorrect indentation
wrong declaration of variable rupees_to_make.
The Logical Errors in your code were:-
Variable five_needed expects a integer as an input, but gets
float on your code because five_needed = rupees_to_make/5 (on
python 3.x) resolves to a floating point number.
The Logical error of the previous line, eventually causes variable one_needed to store a floating value too.
Rectified Code:-
def make_amount(rupees_to_make, no_of_five, no_of_one):
five_needed = rupees_to_make//5
one_needed = rupees_to_make - (5*five_needed)
if rupees_to_make > (5*no_of_five+no_of_one):
print(-1)
elif five_needed < no_of_five and one_needed < no_of_one:
print("No. of Five needed :", five_needed)
print("No. of One needed :", one_needed)
else:
print(-1)
make_amount(28, 8, 5)
OUTPUT:
No. of Five needed : 5
No. of One needed : 3
From Your style of code, I believe that you are new to Python language, and came from a non-weakly typed language background (C, C++, Java etc).(Cause you were using redundant parenthesis after each expression, and initializing a variable with a value before using it which is, uncommon/wasteful in Python as variables are weakly typed in Python). Try avoiding their use, unless necessary from later on.

If you declared those values at the end of your function it's normal that it do not work, you need to declare them at the begining of your function before to use them.

I think the problem you have is the fact that variables in a function are not global (able to be used out of the function) by default.
So if you have something like this:
def product (a,b,c):
#do something
a = "something"
b = "something"
c = "something"
print(a)
You will get NameError: name 'a' is not defined error, since a can't be used out of the function
To get around this, return the values from your function and then print them.
You can't return multiple values individually, but you can add them to a list and then return it.
Eg.
def product (a,b,c):
#do something
a = "something"
b = "something"
c = "something"
return [a,b,c]
p = product (1,2,3)
print(p[0]) #prints a, which is 'something'
print(p[1]) #prints b, which is 'something'
print(p[2]) #prints c, which is 'something'
OR ...
Use the global keyword.
def product (a,b,c):
#do something
global a = "something"
global b = "something"
global c = "something"
print(a)
print(b)
print(c)
>>> something
>>> something
>>> something
Note that this method is dangerous if you have, for instance, a var a defined before the function, since it will be overridden if you define global a in your function.

Related

How to convert string into predefined variable in python [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 2 years ago.
Improve this question
Scenario:
variable2 = "value inside the string"
for i in range(1,5):
x = "variable{0}".format(i)
print(x)
I want the above for loop to print "value inside the string" when i is at 2
Yes, you could do that with globals()/locals() hackery, but I wouldn't recommend it. Instead, use a dictionary:
variables = {
2: "value inside the string",
# ...
}
for i in range(1,5):
x = variables[i] # or variables.get(i, "some default") if values can be missing
print(x)
You can access local variables as a dictionary, and then look them up using a string:
>>> variable2 = "value inside the string"
>>> locals()['variable2']
'value inside the string'
See locals()
I see 2 scenarios here,
you want to print something in a particular case,
for i in range(1,5):
if i == 2:
#do something
print(variable2)
you want multiple variables and print them one after another, in that case using a list would be helpful
variables = ["something1","value inside the string","something2","something3"]
for i in range(1,5):
print(variables[i-1])
I am using eval
variable2 = "value inside the string"
i=2
print(eval("variable{0}".format(i)))
Above print statement will print "value inside the string"

Can i use PRINT function instead of RETURN at the end of every function i create? [duplicate]

This question already has answers here:
What is the purpose of the return statement? How is it different from printing?
(15 answers)
Closed 3 years ago.
i just can not understand the importance of return at the end of functions.with return u have to type print(function()) anyways so why cant we just type print(value) at the and of the function and when we need to use that function just call it like function()?
def example():
value = 5+5
print(value)
example()
print and return are not doing the same thing. The former is displaying information to the user, while the latter is giving a raw value out of a function. Consider the following:
>>> def print_10():
... print(10)
...
>>> def return_10():
... return 10
...
>>> print(return_10() + return_10())
20
>>> print(print_10() + print_10())
Traceback (most recent call last):
...
TypeError: unsupported operand type(s) for +: 'NoneType' and 'NoneType'
return_10 gives back the number 10, while print_10 prints the value 10 to the console and returns None (since you don't specify a return value). Trying to use that value elsewhere is possible (None is a valid result), but it probably doesn't do what you want it to do.
Thinking of this in explicit typing makes this very clear:
def print_10() -> None:
print(10)
def return_10() -> int:
return 10
the print statement only prints what is inside the Parenthesis to the console to be seen and can't be stored in variables or do any operations on it as it is a NoneType
i will show you with an example:
def example():
a = 5
b = 6
print(a + b)
x = example() + 5
print(x)
the above code will return a TypeError.
but if you change it to this:
def example():
a = 5
b = 6
return(a + b)
x = example() + 5
print(x)
you get 16
if you want to display info and not use it again use print else use return
There's a principle called separation of concerns that proposes that each unit of code (function, class, module, etc.) should be responsible for doing just one thing (where the definition of "one thing" is flexible to account for the size of the unit of code being discussed). The benefit is that code that follows this principle is easier to test, debug, combine, and reuse.
If you write a function that prints its result, it is harder to reuse that code in situations where you don't want to print the result, but rather use it in some other way. The function is doing two things: calculating its result, and printing it. If you don't want it to do the second thing, or want it to do the second thing in a slightly different way, you are S.O.L. On the other hand, if the function just calculates its result, doing just one thing, the caller can easily print it if that's what they want.
That said, if you often find yourself printing a result, then it might make sense to provide a second function that calls the first and prints the result, especially if printing it is complicated. But having the first function available is a win for future code reuse.
Some development methodologies advise you to write the simplest thing that works. But I think preserving separation of concerns is an obvious and logical reason to ignore this advice in many cases.

Designing a black box python [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 4 years ago.
Improve this question
I want to have a black box in python where
The input is a list A.
There is a random number C for the black box which is randomly selected the first time the black box is called and stays the same for the next times the black box is called.
Based on list A and number C, the output is a list B.
I was thinking of defining this black box as a function but the issue is that a function cannot keep the selected number C for next calls. Note that the input and output of the black box are as described above and we cannot have C also as output and use it for next calls. Any suggestion?
Make it a Class so C will persist.
class BlackBox():
def __init__(self):
self.C = rand.randint(100)
etc...
As a side note, using some pretty cool Python functionality...
You can make objects of this class callable by implementing __call__() for your new class.
#inside the BlackBox class
def __call__(self, A):
B = []
#do something to B with A and self.C
return B
You can then use this in your main code.
bb = BlackBox()
A = [1, 2, 3]
B = bb(A)
the issue is that a function cannot keep the selected number C for next calls.
This may be true in other languages, but not so in Python. Functions in Python are objects like any other, so you can store things on them. Here's a minimal example of doing so.
import random
def this_function_stores_a_value():
me = this_function_stores_a_value
if 'value' not in me.__dict__:
me.value = random.random()
return me.value
This doesn't directly solve your list problem, but it should point you in the right direction.
Side note: You can also store persistent data in optional arguments, like
def this_function_also_stores_a_value(value = random.random()):
...
I don't, however, recommend this approach because users can tamper with your values by passing an argument explicitly.
There are many ways to store persistent data for a function. They all have their uses, but in general, the ones that come first are useful more often than the ones that come later. (To keep things shorter, I'm solving a slightly simpler problem than the one you asked about, but it should be obvious how to adapt it.)
Instance attribute
class BlackBox:
def __init__(self):
self.C = rand.randint(100)
def check(self, guess):
return (guess - self.C) / abs(guess - self.C)
Now you can create one or more BlackBox() instances, and each one has its own random number.
Closure variable
def blackbox():
C = rand.random()
def check(guess):
return (guess - C) / abs(guess - C)
return check
Now, you can create one or more check functions, and each one has its own random number. (This is dual to the instance variable—that is, it has the same capabilities—but usually one or the other is more readable.)
Global variable
def makeblackbox():
global C
C = random.randint(100)
def check(guess):
return (guess - C) / abs(guess - C)
This way, there's only a single blackbox for the entire program. That's usually not as good a design, which is one of the reasons that "globals are bad". Plus, it's polluting the global namespace with a C variable that means nothing to anyone but the check function, which is another one of the reasons that "globals are bad".
Function attribute
def makeblackbox():
check.C = random.randint(100)
def check():
return (guess - check.C) / abs(guess - check.C)
This is equivalent to a global in that you can only ever have one black box, but at least the variable is hidden away on the check function instead of polluting the global namespace.
Class attribute
class BlackBox:
C = rand.randint(100)
#staticmethod
def check(guess):
return (guess - BlackBox.C) / abs(guess - BlackBox.C)
This is again equivalent to a global variable without polluting the global namespace. But it has a downside over the function attribute—you're creating a class that has no useful instances is often misleading.
Class attribute 2
class BlackBox:
C = rand.randint(100)
#classmethod
def check(cls, guess):
return (guess - cls.C) / abs(guess - cls.C)
This is different from the last three in that you can create new blackboxes by creating subclasses of BlackBox. But this is very rarely what you actually want to do. If you want multiple persistent values, you probably want instances.
Since you are asking in the comments.
This is probably not recommended way but it's easy and works so I'll add it here.
You can use global variable to achieve your goal.
import random
persistant_var = 0
def your_func():
global persistant_var
if persistant_var:
print('variable already set {}'.format(persistant_var))
else:
print('setting variable')
persistant_var = random.randint(1,10)
your_func()
your_func()
Output:
setting variable
variable already set 7
Hope this is clear.

Python: calling def from a different def [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 8 years ago.
Improve this question
I am relatively new to Python and I've been stuck on something that seems very trivial, so hoping someone can help.
What I'm trying to do is call a method inside a method in Python. I want to call this method several times, in various different methods, so I don't want to have to keep on copying and pasting the code if I'm going to be using it ~10 times - just to keep calling that "def".
I have tried things such as:
return anotherMethod()
Any ideas how to do this?!
Thanks!
Edit:
Sorry about the vagueness of the question. I'm trying to get my head around the terminology.
def scaleC():
pianoIcon = Icon("PianoScaleC.png")
d1 = Display("iPiano", pianoIcon.getWidth(), pianoIcon.getHeight())
d1.add(pianoIcon)
return piano()
def scaleCS():
pianoIcon = Icon("PianoScaleCS.png")
d1 = Display("iPiano", pianoIcon.getWidth(), pianoIcon.getHeight())
d1.add(pianoIcon)
return piano()
def piano:
#play the piano keys, etc
So you are doing something like this?:
def my_global_function():
def my_local_function():
print('hello world')
my_local_function()
And then outside of that definition you want to call that function again?
But it has been destroyed because you exited the scope.
You can make it a global then:
my_local_function_global_scope = None
def my_global_function():
def my_local_function():
print('hello world')
# Declare variable space as global and assign to it
global my_local_function_global_scope
my_local_function_global_scope = my_local_function
my_local_function()
my_local_function_global_scope()
SO you want to call the same function/method ten times? Do it in a loop eh?
for i in range(10):
print('Iteration Number %s' % i)
anotherMethod()
if you want to return the results of the function ten times in a list, you can use list comprehension
return [anotherMethod() for _ in range(10)]
Note: the _ variable is a convention used when you are required to have an assignment but you do not want to store that variable, naming it _ will effectively delete it as I understand.
my last idea is that you wan to reference the callable once and call it ten times. You can do that too (And its one of my favorite things about python)
my_method = anotherMethod
my_method()
my_method()
...
my_method()
my_method()
If you are asking on how to define methods in Python that can be called from everywhere you can write the method you want on a library.py file like this:
def fun(a , b):
return a + b
and then call it from another file (ie. program.py) like this:
from library import fun
def main():
# your code
print fun(1, 2)
a = 4
b = 5
c = fun(a, b)
print c
if __name__ == '__main__': main()
this will output:
3
9
hope that helps.
Well it is quite simple. You just literally call that function inside your other function. Here is an example:
def Examples():
print 'Function successfully called!'
def Example()
print 'Calling function...'
Examples() #This will call the function above it
Example()
Your result should be:
Calling function...
Function successfully called!
No errors should pop up and this should work. Just add a variable:
loop = 0
and put the functions in a while loop:
while loop <> 10:
loop += 1
def Examples():
print 'Function successfully called!'
def Example()
print 'Calling function...'
Examples() #This will call the function above it
Example()
This will should solve your problem. I hope this helps you! Your final code with this implied should be:
loops = 0
while loops <> 10:
loops += 1
def scaleC():
pianoIcon = Icon("PianoScaleC.png")
d1 = Display("iPiano", pianoIcon.getWidth(), pianoIcon.getHeight())
d1.add(pianoIcon)
piano()
def scaleCS():
pianoIcon = Icon("PianoScaleCS.png")
d1 = Display("iPiano", pianoIcon.getWidth(), pianoIcon.getHeight())
d1.add(pianoIcon)
piano()
def piano:
#play the piano keys, etc
If I understand your question right, you just need to use it like this.
class YourClass(object):
def method(self):
pass # here goes your method
def method_where_i_want_to_use_other_method(self):
self.method()
#other things you need in this method

Do you change variables AFTER you run a function in python?

So I wrote this function from a book I am reading, and this is how it starts:
def cheese_and_crackers(cheese_count, boxes_of_crackers):
print "You have %d cheeses!" % cheese_count
print "You have %d boxes of crackers!" % boxes_of_crackers
print "Man that's enough for a party!"
print "Get a blanket.\n"
ok, makes sense. and then, this is when this function is run where I got a little confused and wanted to confirm something:
print "OR, we can use variables from our script:"
amount_of_cheese = 10
amount_of_crackers = 50
cheese_and_crackers(amount_of_cheese, amount_of_crackers)
the thing that confused me here is that the amount_of_cheese and amount_of_crackers is changing the variables (verbage? not sure if i am saying the right lingo) from cheese_count and boxes_of_crackers repectively from the first inital variable labels in the function.
so my question is, when you are using a different variable from the one that is used in the initial function you wrote, why would you change the name of the AFTER you wrote out the new variable names? how would the program know what the new variables are if it is shown after it?
i thought python reads programs top to bottom, or does it do it bottom to top?
does that make sense? i'm not sure how to explain it. thank you for any help. :)
(python 2.7)
I think you are just a bit confused on the naming rules for parameter passing.
Consider:
def foo(a, b):
print a
print b
and you can call foo as follows:
x = 1
y = 2
foo(x, y)
and you'll see:
1
2
The variable names of the arguments (a, b) in the function signature (1st line of function definition) do not have to agree with the actual variable names used when you invoke the function.
Think of it as this, when you call:
foo(x, y)
It's saying: "invoke the function foo; pass x in as a, pass y in as b". Furthermore, the arguments here are passed in as copies, so if you were to modify them inside the function, it won't change the values outside of the function, from where it was invoked. Consider the following:
def bar(a, b):
a = a + 1
b = b + 2
print a
x = 0
y = 0
bar(x, y)
print x
print y
and you'll see:
1
2
0
0
The script runs from top to bottom. The function executes when you call it, not when you define it.
I'd suggest trying to understand concepts like variables and function argument passing first.
def change(variable):
print variable
var1 = 1
change(var1)
In the above example, var1 is a variable in the main thread of execution.
When you call a function like change(), the scope changes. Variables you declared outside that function cease to exist so long as you're still in the function's scope. However, if you pass it an argument, such as var1, then you can use that value inside your function, by the name you give it in the function declaration: in this case, variable. But it is entirely separate from var! The value is the same, but it is a different variable!
Your question relates to function parameter transfer.
There are two types of parameter transfer into a function:
By value ------- value changed in function domain but not global domain
By reference ------- value changed in global domain
In python, non-atomic types are transferred by reference; atomic types (like string, integer) is transferred by value.
For example,
Case 1:
x = 20
def foo(x):
x+=10
foo()
print x // 20, rather than 30
Case 2:
d = {}
def foo(x): x['key']=20
foo(d)
print d // {'key': 20}

Categories

Resources