Returning values to other functions - python

I am fairly new to python and I am trying to figure out how to use variables from one function in another one. I can't seem to use the return command correctly. All help is appreciated! Here is an example of what I want:
{
def a():
num1 = input("number: ")
return num1
def b():
str1 = input("letter :")
return str1
def main():
a()
b()
print(num1,str1)
}

Simply assign the returned values to variables in main(), and don't forget to add a return statement in b(). By default a function returns None in Python.
def a():
num1 = input("number: ")
return num1
def b():
str1 = input("letter :")
return str1
def main():
num1 = a() #here you can use any variable name, not necessarily `num1`
str1 = b() #here you can use any variable name, not necessarily `str1`
print(num1,str1)
Demo:
>>> main()
number: 10
letter :a
10 a

Try like this,
def main():
print(a(),b())

Related

How to call a python function "with arguments" present within a class which has a constructor from a pytest function?

I could not find a similar question based on pytest. Stuck with this for quite sometime. Please do not close this until it is answered. thank you.
The python class looks like:
class Calculator:
def __init__(self, num1=None, num2=None):
self.logger = get_logger(__name__)
self.num1 = num1
self.num2 = num2
def calculate(self):
if self.num1 and self.num2:
num = self.__divider(num1, num2)
else:
raise Exception('num2 cannot be 0')
return self.__faulty_displayer(num)
def __divider(self, num1, num2):
value = num1/num2
return value
def __faulty_displayer(self,num)
value = num + 1
return value
What I want to be able to do is, write a pytest for calculate() method. But, I am unable to do so, as I am unable to call the method with any values. So, inherently, every time, the exception is getting called.
What I have tried so far is:
import pytest
#pytest.fixture
def obj():
return Calculator()
# Need help in writing a test case which can take the values of num1, and num2
def test_calculate(obj):
expected_value = 1
actual_value = obj.calculate() #How to pass num1, and num2 values
assert expected_value == actual_value
The way that your class is defined, num1 and num2 have to be defined at the time the object is constructed. This is an awkward design (as you're discovering now in trying to write your test), but assuming that we need to work with that class as-is instead of fixing it, then the test needs to construct the object with the test values, like this:
def test_calculate(num1, num2, expected):
"""Test that Calculator.calculate() produces the expected result."""
assert Calculator(num1, num2).calculate() == expected
test_calculate(1, 1, 2) # 1 / 1 + 1 = 2
test_calculate(4, 2, 3) # 4 / 2 + 1 = 3

Using variables from another function in a function

I have tried to search this but I don't quite understand. I am coming across this error so I formed a quick easy example.
def test():
global a
a = 0
a+=1
def test2():
a+=1
print (a)
inp = input('a?')
if inp == 'a':
test()
test2()
When I input a. I expected the code to output 2. However, I get this error UnboundLocalError: local variable 'a' referenced before assignment. When I searched around about this, I found that you need to use global, but I already am using it.
So I don't understand. Can someone briefly explain what I'm doing wrong?
Thanks.
A global declaration only applies within that function. So the declaration in test() means that uses of the variable a in that function will refer to the global variable. It doesn't have any effect on other functions, so if test2 also wants to access the global variable, you need the same declaration there as well.
def test2():
global a
a += 1
print(a)
1) You can return the modified value like:
def test():
a = 0
a+=1
return a
def test2(a):
a+=1
print (a)
inp = input('a?')
if inp == 'a':
a = test()
test2(a)
2) Or you can use a class:
class TestClass:
a = 0
def test(self):
self.a = 0
self.a+=1
def test2(self):
self.a+=1
print (self.a)
Usage of option 2:
>>> example = TestClass()
>>> example.test()
>>> example.test2()
2

How to call variables from other files python with classes?

Hi all I would like to know how to call variables (which are inside classes) from other python files. I am aware of the bellow method of doing this however it will not work if the class is called from the original file.
from (insert_file_name_hear) import *
This a similar sample to what I'm working with:
functions.py
num = 0
num2 = 0
class Test():
def alt_num(self):
global alt_num
alt = 55
def change(self):
global num, num2
num += alt_num
num2 = num
def print_num():
global num2
print(num2)
def work():
Test.alt_num(Test)
Test.change(Test)
print_num()
print.py
from functions import *
work()
def printing():
print(num2)
printing()
When I run print.py it will accuratly print in the functions.py file however it will print 0 in the print.py file. Note: Both files are in the same folder and I am running this in Python 3.
Thanks
Instead of using Globals you can use class variables with a little bit of effort
functions.py
class Test():
num = 0
num2 = 0
alt = 0
#classmethod
def alt_num(cls):
cls.alt = 55
#classmethod
def change(cls):
cls.num += cls.alt
cls.num2 = cls.num
def print_num():
print(Test.num2)
def work():
Test.alt_num()
Test.change()
print_num()
Test.change()
print_num()
Test.change()
print_num()
return Test.num2
print.py
from functions import *
work()
def printing():
print(Test.num2)
printing()
Note: the output of the above is
55
110
165
165
The first three come from work(), the last from printing()
First - alt and alt_num are not defined
Second - You need to return the variable through a function to use it elsewhere
Below is how you can do this
functions.py
alt = 0
num = 0
num2 = 0
class Test():
def alt_num(self):
global alt
alt = 55
def change(self):
global num, num2
num += alt
num2 = num
def print_num():
global num2
def work():
Test.alt_num(Test)
Test.change(Test)
print_num()
return num2
print.py
from functions import *
def printing():
print(work())
printing()
In functions.py you declare num2 = 0, the rest of the manipulation of num2 is made inside functions that do not return the new value.
The function print_num() actually prints the new value of num2, this is where 55 comes from in the output.
In print.py you are printing the num2 that is declared on line 2 of functions.py
If you are only interested in num2 after the value has been updated you could skip the printing in functions.py, instead return the value and print it from print.py.
It could look something like this.
functions.py
num = 0
class Test():
def alt_num():
global alt
alt = 55
def change():
global num
global num2
num += alt
num2 = num
def work():
Test.alt_num()
Test.change()
return(num2)
print.py
from functions import *
def printing():
print(work())
printing()

How to use the def function in IF or ELSE/ ELIF satement in python?

I have a sub program that uses a def option, so if i ever want to repeat the program. Eg:
def op1():
print ("Something Something")
So I just write in the program:
op1()
which makes the program run.
Now I have a lot of subprograms each one with a different def so I can run them by easily.
eg:
def op1():
def op2():
def op3():
So I wanted to know how can I use this in if-else statement.
eg:
option = input ("Enter either A, B or C here: ")
if option == A:
def op1():
else:
def op2():
or even
if option == A:
def op1():
elif:
def op2():
elif:
def op3():
Something like that, but it doesn't work. Can anyone help, Please?
Also I'm using the newer version of python if that helps 3.5.0.
You do not need to define functions conditionally.
def op1():
print('1')
def op2():
print('2')
def op3():
print('3')
if option == 'A':
op1()
elif option == 'B'::
op2()
else:
op3()
You need to define your functions first but if you have multiple choices you can store references to functions in a dict then call based on what the user enters, using dict.get with a default function will act like your if/elif else logic:
def op1():
return '1'
def op2():
return '2'
def op3():
return "3"
option_fs = {"A": op1, "B": op2}
option = input("Enter either A, B or C here: ").upper()
print(option_fs.get(option, op3)())

python accessing another function variable error

I am trying to get input from one function and dispaying it in another function but i could not get the expected result
class Base(object):
def user_selection(self):
self.usr_input = input("Enter any choice")
user_input = self.usr_input
return user_input
def switch_selection(user_input):
print user_input
b = Base()
b.user_selection()
b.switch_selection()
When i execute this program i get
Enter any choice1
<__main__.Base object at 0x7fd622f1d850>
I should get the value which i entered but i get
<__main__.Base object at 0x7fd622f1d850>
How could i get the value which i entered?
def switch_selection(user_input):
print user_input
..
b.switch_selection()
You may notice that you're not passing any argument into switch_selection when calling it, yet you're expecting to receive one argument. That's something of a cognitive disconnect there. You happen to actually receive an argument though, which is b. An object method in Python receives its object instance as its first parameter. The argument you're receiving is not user_input, it's self. That's what you're printing, that's the output you're seeing.
Two possibilities to fix this:
class Base(object):
def user_selection(self):
self.user_input = input("Enter any choice")
def switch_selection(self):
print self.user_input
or:
class Base(object):
def user_selection(self):
return input("Enter any choice")
def switch_selection(self, user_input):
print user_input
b = Base()
input = b.user_selection()
b.switch_selection(input)
Try this Code Working perfect for me,
class Base(object):
def user_selection(self):
self.usr_input = input("Enter any choice")
user_input = self.usr_input
return user_input
def switch_selection(self,user_input):
print user_input
b = Base()
g=b.user_selection()
b.switch_selection(g)

Categories

Resources