Suppose I have the following function that asks for 2 numbers and adds them.
def sum():
a = int(input('Enter the first number: '))
b = int(input('Enter the second number: '))
return a b
Also I have two variables:
first_number = 2
second_number = 4
Considering that I can't copy paste the values of variable or change the function and the variables I want to fill in the values of these variables into the sum
function. So, I was trying to do this by creating a function like input_values
that could take the function and the variables as arguments and return the output of the function entered in it as an argument after imputing the variable values in it. I am working in a jupyter notebook and not able to understand how to build this function. Or is it possible even. Please help!
CodePudding user response:
You can try something like : Reference
Installation:
pip install pexpect
Then simply try this snippet
import pexpect
first_number = 2
second_number = 4
child = pexpect.spawn('your_script.py')
child.expect('Enter the first number:.*')
child.sendline(first_number)
child.expect('Enter the second number:.*')
child.sendline(second_number)
Make sure you call the function in your source main code
first_number = 2
second_number = 4
def sum():
a = int(input('Enter the first number: '))
b = int(input('Enter the second number: '))
return a b
sum()
CodePudding user response:
I apologize if I am misunderstanding your question, but is this what you are trying to achieve?
def input_values():
try:
a = int(input('Enter the first number: '))
b = int(input('Enter the second number: '))
except(ValueError) as e:
print(f'{str(e)}. Please only input integers.')
input_values()
return sum_numbers(a, b)
def sum_numbers(a, b):
try:
print(f'The sum of your two numbers is: {a b}')
except(ArithmeticError) as e:
print(f'{str(e)}.')
if __name__ == "__main__":
input_values()
Please note that I have included some simple error handling to prevent unwanted input. You will want to expand on this to ensure all user input is handled correctly.