How to get return output from another script? - python

How can i get the output from another script?
My first script to run:
from test2 import *
class Test():
def todo (self):
mult()
addx()
if __name__ == '__main__':
Test().todo()
My second script named (test2.py):
def mult():
x= 2 * 4
print(x)
return x
def addx():
sum = x + 2
print("sum",sum)
Error:
NameError: name 'x' is not defined

In the function addx() you haven't declared x. I believe you want x from mult. So you can do something like this
def addx():
x = mult()
sum = x + 2
print("sum",sum)

You should use the return value of mult, to pass it to your second function addx as a parameter.
def todo (self):
x = mult()
addx(x)
I advise you to read the Python doc section about function : https://docs.python.org/fr/3/tutorial/controlflow.html#defining-functions

In test2.py, you have not defined x
def addx():
sum = x + 2
print("sum",sum)
The problem above is that the computer doesn't know what x is. You could pass it as a parameter:
def addx(x):
sum = x + 2
print("sum", sum)
and change your code to:
from test2 import *
class Test():
def todo(self):
addx(x=mult()) # whatever number you want
if __name__ == '__main__':
Test().todo()

Related

Python: Unable to return gift with nested function

def hypo(a,b):
def square(x): return x*x;
return math.sqrt(square(a) + square(b));
def secondfunction():
result = hypo(1,2);
print(result);
I am trying to learn Python myself but unable to understand what is wrong?
Expected Result something like this 2.23606797749979
I got it working using a lambda:
import math
def hypo(a,b):
square = lambda x: x * x
return math.sqrt(square(a) + square(b))
def secondfunction():
result = hypo(1, 2)
print(result)
secondfunction()
Output:
2.23606797749979
Also, you don't need semicolons in Python, unless you want to make a winky-face ;)
You need to call the function secondfunction() to get the result
def hypo(a,b):
return (a ** 2 + b ** 2) ** 0.5
def secondfunction():
print(hypo(1,2))
secondfunction()
Output:
2.23606797749979
You can try
def hypo(a,b):
def square(x):
return x*x
return math.sqrt(square(a) + square(b))
def secondfunction():
result = hypo(1,2)
print(result)
secondfunction()
or if you execute it from a script you can add at the end
if __name__ == '__main__':
secondfunction()
Output
2.23606797749979

import an argument from a function as a variable to another function

Is there any way to import an argument from a function as a variable to another function?
For example:
untitled1.py
def fun1(a,b):
x = a+b
return x
and I want to pass the a as a variable to the following function which is another py file..
untitled2.py
def fun2(c):
d=c/a
return d
You should define the variable 'a' as global.
variable.py
class A:
value = None
untitled1.py
def fun1(a,b):
x = a.value+b
return x
untitled2.py
def fun2(c):
d=c/a.value
return d
where to call func1, func2
A.value = 2
func1(A, 4)
func2(10)
Try this:
`untitled1.py
def fun1(a,b):
x = a+b
return x,a
untitled2.py
import untitled1
def fun2(c):
var1,var2 = fun1(a,b)
d=c/var2
return d`

Python decorator TypeError 'object is not callable'

I am trying to get myself familiar with decorators.
This is a program I created to do so, but it keeps giving me an TypeError: 'int' object is not callable error, which I don't know how to fix.
#Filename: decorator_practice.py
def add(x):
def add_1():
add_1 = x() + 1
return add_1
def minus(x):
def minus_1():
return x() - 1
return minus_1
def multi(x, times=2):
def multi_2():
return x() * 2
def multi_3():
return x() * 3
def multi_4():
return x() * 4
if times == 2:
return multi_2
elif times == 3:
return multi_3
elif times == 4:
return multi_4
else:
return "Please enter times between 2 and 4"
def create_x():
x = input('Give variable x a value: ')
return x
add(create_x()())
I run this and type: 5
Can anyone help me? Thanks!
Your create_x function returns an integer:
def create_x():
x = input('Give variable x a value: ')
return x
so create_x()() is never going to work.
Part of the problem is that you've used poor parameter names, which is confusing you - you have two xs which refer to two completely different things. Using your add decorator as an example, modify to:
def add(func):
def add_1():
return func() + 1 # you should return from the inner function
return add_1
Now hopefully it is clear that the argument to add should be a function, which is called inside add_1. Therefore you could do:
adder = add(create_x) # don't call create_x yet!
adder() # calling add_1, which calls create_x
which simplifies to:
add(create_x)() # note ordering of parentheses
Note that this could also be written:
#add
def create_x():
...
create_x()
where the syntax #add means create_x = add(create_x).
Once you've mastered simple decorators, note that your multi will not work as you expect - see e.g. python decorators with parameters for creating decorators that take arguments.
You have unnecessary (), change add(create_x()()) to add(create_x()),
and I suggest using x = int(raw_input('Give variable x a value: '))
See the following example:
def add(x):
def add_1():
#add_1 = x() + 1 # remove this line
return x+1
return add_1
def create_x():
x = input('Give variable x a value: ')
return x
b = add(create_x())
print 'answer: ', b()
localhost# python t.py
Give variable x a value: 5
answer: 6

Get inner function result without interaction of outer function in python

I want to get inner function result so i code it like
def main():
def sub():
a = 1
print a
exec main.__code__.co_consts[1]
using above code working successfully but i want to pass the argument to the sub function like...
def main():
def sub(x):
a = x + 1
return a
ans = exec main.__code__.co_consts[1]
print ans
in that problem is i don't know how to pass that x value.
that work must need to exec so that how to pass that x value with exec without interaction of main function
Maybe something like the code below, as suggested by this SO answer
def main():
def sub():
a = x + 1
print a
return a
exec(main.__code__.co_consts[1], {'x': 1} )

OOP python program

from collections import Counter
class Runlength:
def __init__(self):
self.str = 0
def returner(self,str):
self.str = str
self.__str = ','.join(str(n) for n in self.__str)
self.__str = self.__str[::-1]
self.__str = self.__str.replace(',', '')
return self.__str
def final(self,num):
self.num = num
k = []
c = Counter(self.num).most_common()
for x in c:
k += x
return k
math = Runlength()
def Main():
a = "aabbcc"
b = math.returner(a)
c = math.final(b)
print(c)
Main()
The program takes a word as input and gives the occurrence of each repeating character and
outputs that number along with a single character of the repeating sequence.
I cant figure it out, why this doesn't work. I get this error:
NameError: global name 'returner' is not defined
The problem is that in Main() you are not accessing the global (outside the scope of the Main() method) math variable. Instead try initializing your math inside the Main() function
This lets the method know that it should use the global math variable instead of trying to look for a non-existent local one.
I got this error with your code:
self.__str = ','.join(str(n) for n in self.__str)
AttributeError: Runlength instance has no attribute '_Runlength__str'
Maybe you mean:
self.__str = ','.join(str(n) for n in self.str
And choose input argument for returner() method as str_ not str, cause str -- is the name of python built-in type, so better to not choose variable names with built-in type names.
So after this changes I got this output:
['a', 2, 'c', 2, 'b', 2]
So my python version is 2.7.3 and error you've got does not appear with my python version.
What python version you use to compile your code? If this python3 it works fine too.So try this code, it works fine for me:
from collections import Counter
class Runlength:
def __init__(self):
self.str = 0
def returner(self,str_):
self.string = str_
self.__str = ','.join(str(n) for n in self.string)
self.__str = self.__str[::-1]
self.__str = self.__str.replace(',', '')
return self.__str
def final(self,num):
self.num = num
k = []
c = Counter(self.num).most_common()
for x in c:
k += x
return k
math = Runlength()
def Main():
a = "aabbcc"
b = math.returner(a)
c = math.final(b)
print(c)
Main()
def Main():
math = Runlength()
a = "aabbcc"
b = math.returner(a)
c = math.final(b)
print(c)
Main()
This should work fine..
But I observed that the object can even be accessed if it is not declared as global. Is their any explantion for it in the above scenario?

Categories