How to fill a input() function with variable - python

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. The resultant function should be defined something like following:
def input_values(func,var1, var2):
#The computation should be held here.
It should be called like this:
input_values(func=sum(), var1=first_number,var2=second_number)
Again specifying, the input_values should follow the following algo.
Initiate the function given to it(in this case it is the sum function)
When the sum function ask to enter the first value from user, fill the value of var1 in it and somehow proceed.
Again, when it asks to enter the other number, enter the value of var2 in it and proceed.
When the given function(sum) is executed, return its value.

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()

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.

Related

Define a function called avg4. Returns the average of four numbers

There is a similar question on this website but I found the answers were only for string outputs. e.g dramatically different things. Imagine if I have this python program:
#!/usr/bin/env python
def printAndReturnNothing():
x = "hello"
print(x)
def printAndReturn():
x = "hello"
print(x)
return x
def main():`enter code here`
ret = printAndReturn()
other = printAndReturnNothing()
print("ret is: %s" % ret)
print("other is: %s" % other)
if __name__ == "__main__":
main()
What do you expect to be the output?
hello
hello
ret is : hello
other is: None
However, the question is to define a function called avg4. It asks the user for four numbers and returns the average of four numbers. The second question asks to define a function called avg. It asks the user for three numbers and prints the average.
Wouldn't these be the same output?
This is my code for avg4:
def avg4(a,b,c,d):
a=int(input(ënter a number")
b
c
d
avg=a+b+c+d/4
return
When I call it it prompts the user to enter four numbers, but doesn't return anything. While the second one, avg will print the average.
You need to return something using a return statement at the end of your def. There's also some other changes you needed to make. Your new code would be this:
def avg4(): # You don't need parameters for this function; they're overwritten by your input
a=int(input("Enter a number")) # Added missing quote and bracket
b=int(input("Enter a second number")) # Filled in inputs for b, c and d
c=int(input("Enter a third number"))
d=int(input("Enter a fourth number"))
avg=(a+b+c+d)/4 # Changed to suit BODMAS
return avg # Returns the variable avg
Now you can do this because avg returns something:
result = avg()
Your avg4 function have several issues. Try to use
def avg4():
a=int(raw_input("Enter a number").strip())
b=int(raw_input("Enter a second number").strip())
c=int(raw_input("Enter a third number").strip())
d=int(raw_input("Enter a fourth number").strip())
avg=float(a+b+c+d)/4.0 # avg must be float, not int
return avg
...
print avg4()

Passing Variables/lists through Functions

Im having trouble with sorting Variables/lists and then being able to transfer them across functions. Im still quite new to python and am probably missing something very basic. but ive been going over this for hours.
I need to create a program which generates 20 random integers and indicates whether each number is odd or even. I need to sort the two original integers into ascending order and transfer them to random.randint function but am having trouble, any help would be appreciated.
This is what i have so far.
import random
def userinput():
global number1
global number2
number1 = int(input("Enter First Integer: "))
number2 = int(input("Enter Second Integer: "))
userinput()
def numbersorting():
global both
both = [(number1),(number2)]
sorted(both)
numbersorting()
def random_gen():
global num
i = 0
for i in range(20):
num = random.randint(number1,number2)
def get_num():
return values.pop
def odd_even():
if num % 2 == 0:
print("Random Number", num, "is even")
else:
print("Random Number", num, "is odd")
odd_even()
random_gen()
Well it doesn't seems so clear on the question what actually you want to do but the use of global is a really bad practice in general.
However you can use the methods that returns the values you need for instace:
If you need a user input that returns 2 numbers it is better to use this approach:
def get_numeric_input(label):
try:
return int(input(label))
except NameError:
print "Please enter a number"
return get_numeric_input(label)
With this function you can get a numeric value from a user.
Using it you can the 2 next values like
def get_user_input():
n = get_numeric_input("Enter First Integer: ")
m = get_numeric_input("Enter First Integer: ")
return [n, m]
Now you have a function that returns the 2 values from the user and using the sort method for list you have those values sorted
def get_sorted_values(l):
return l.sort()
Check this information about sorting in python https://wiki.python.org/moin/HowTo/Sorting
Using the random numbers as you have described is ok, but also try to use the is_odd and is_even function outside of any other function and you will be able to reuse them more times.
Are you looking for something like this?
I edited your code to work with what I understand your problem to be...
You want the user to input 2 numbers to set the upper and lower bound of each random number. Then you want to generate 20 random numbers within that range and find out whether each number of even or odd?
import random
def random_gen(number1, number2):
for i in range(20):
num = random.randint(number1,number2)
if num % 2 == 0:
print("Random Number", num, "is even")
else:
print("Random Number", num, "is odd")
number1 = int(input("Enter First Integer: "))
number2 = int(input("Enter Second Integer: "))
random_gen(number1, number2)
You have a few problems with your current code:
Indentation (fixed in the edit)
Unnecessary use of global variables. If you need that type of functionality you should consider passing the variables into each function as you need it instead
A number of functions are unnecessary too. For example, you dont need the get_num() and odd_even() functions as you can just perform those actions within the loop that you have. Even in the case I just posted you dont even really need the random_gen() function - you can just move all of that code to after user input. I just left it there to show what I mean with point #2 above
from random import randint
def user_input():
number1 = int(input("Enter First Integer: "))
number2 = int(input("Enter Second Integer: "))
if number1 > number2:
number1, number2 = number2, number1
return number1, number2
def odd_even(num):
if num % 2 == 0:
print("Random Number " + str(num) + " is even")
else:
print("Random Number " + str(num) + " is odd")
def random_gen():
number1, number2 = user_input()
for i in range(20):
num = randint(number1, number2)
odd_even(num)
random_gen()
You generally want to try to avoid using global variables when possible. It's just good programming practice, as they can get rather messy and cause problems if you don't keep careful track of them. As far as sorting your two integers, I think that that one if statement is a much more pythonic way of doing things. Well, I think it's easier at least. Also, in Python, you don't need to declare your for loop variables, so the line i=0 is unnecessary. Also, I'm sure this is an assignment, but in real life you're going to want to run an exception clause, in which you would say something like
while True:
try:
number1 = int(input("Enter First Integer: "))
number2 = int(input("Enter Second Integer: "))
break
except ValueError:
print("Oops! Try entering an integer!")
Hope that helps!
Avoid globals by passing the variables to functions and returning the new values from functions.
import random
def userinput():
number1 = int(input("Enter First Integer: "))
number2 = int(input("Enter Second Integer: "))
return number1, number2
def numbersorting(nums):
return sorted(nums)
def random_gen(hi, lo):
return random.sample(range(hi, lo), 20)
def odd_even(num):
if num % 2 == 0:
print("Random Number %d is even" % num)
else:
print("Random Number %d is odd" % num)
nums = userinput()
sortnum = numbersorting(nums)
randoms = random_gen(*sortnum)
[odd_even(n) for n in randoms]
In keeping with your original function names.
You should be aware of the difference between list.sort and sorted. If you have a list li then li.sort() sorts in place, that is it alters the original list and returns None. So return li.sort() is always wrong. on the other hand return sorted(li) is ok, but just sorted(li) is a wasted sort since the result is thrown away.
Try both.sort()
sorted returns a new list.
sort() is done in place.

Regarding passing variables to an argument

I am working in python 2.7.8.
I'm currently learning about parameters and methods. What I'm trying to accomplish is have a user enter two different variables then pass them to an argument within different methods, sum() and difference().
My following code is something like this:
def computeSum(x, t):
x = int(raw_input('Please enter an integer: '))
t = int(raw_input('Please enter a second integer: '))
x+t
return Sum
def computeDif(y, j):
y = int(raw_input('Please enter an integer: '))
j = int(raw_input('Please enter a second integer: '))
y+j
return Dif
def main():
raw_input('Would you like to find the sum of two numbers or the difference of two numbers?: ')
answer = 'sum'
while True:
computeSum()
else:
computeDif()
For some reason my compiler (pyScriptor) isn't running and I cannot see any output nor error messages, its just blank. Can anyone possibly help me with any syntax/logic errors?
There are a few problems with your code
Your indentation is way off
computeSum and computeDif expect the two numbers as parameters, but then also ask for them from the terminal
You return the variables Sum and Dif, but never assign values to them
You call either computeSum or computeDif, but never do anything with the returned value
You never call main. Do you know that you don't need a main function? You can just put the code in line after the function definitions
This is probably a little closer to what you had in mind
def computeSum(x, t):
return x + t
def computeDif(y, j):
return y - j
def main():
while True:
answer = raw_input('Would you like to find the "sum" of two numbers or the "dif"ference of two numbers? ')
a = int(raw_input('Please enter an integer: '))
b = int(raw_input('Please enter a second integer: '))
if answer == 'sum':
print(computeSum(a, b))
elif answer == 'dif':
print(computeDif(a, b))
else:
print('Please enter "sum" or "dif"')
main()
The problem is that you don't need a main() function. Just put the code, unindented, by itself, and it will run when you run the program.

How do I improve my code for Think Python, Exercise 7.4 eval and loop

The task:
Write a function called eval_loop that iteratively prompts the user, takes the resulting input and evaluates it using eval(), and prints the result.
It should continue until the user enters 'done', and then return the value of the last expression it evaluated.
My code:
import math
def eval_loop(m,n,i):
n = raw_input('I am the calculator and please type: ')
m = raw_input('enter done if you would like to quit! ')
i = 0
while (m!='done' and i>=0):
print eval(n)
eval_loop(m,n,i)
i += 1
break;
eval_loop('','1+2',0)
My code cannot return the value of the last expression it evaluated!
Three comments:
Using recursion for this means that you will eventually hit the system recursion limit, iteration is probably a better approach (and the one you were asked to take!);
If you want to return the result of eval, you will need to assign it; and
I have no idea what i is for in your code, but it doesn't seem to be helping anything.
With those in mind, a brief outline:
def eval_loop():
result = None
while True:
ui = raw_input("Enter a command (or 'done' to quit): ")
if ui.lower() == "done":
break
result = eval(ui)
print result
return result
For a more robust function, consider wrapping eval in a try and dealing with any errors stemming from it sensibly.
import math
def eval_loop():
while True:
x=input('Enter the expression to evaluate: ')
if x=='done':
break
else:
y=eval(x)
print(y)
print(y)
eval_loop()
This is the code I came up with. As a start wrote it using the If,else conditionals to understand the flow of code. Then wrote it using the while loop
import math
#using the eval function
"""eval("") takes a string as a variable and evaluates it
Using (If,else) Conditionals"""
def eval_(n):
m=int(n)
print("\nInput n = ",m)
x=eval('\nmath.pow(m,2)')
print("\nEvaluated value is = ", x)
def run():
n= input("\nEnter the value of n = ")
if n=='done' or n=='Done':
print("\nexiting program")
return
else:
eval_(n)
run() # recalling the function to create a loop
run()
Now Performing the same using a While Loop
"using eval("") function using while loop"
def eval_1():
while True:
n=input("\nenter the value of n = ") #takes a str as input
if n=="done" or n=="Done": #using string to break the loop
break
m=int(n) # Since we're using eval to peform a math function.
print("\n\nInput n = ",m)
x=eval('\nmath.pow(m,2)') #Using m to perform the math
print("\nEvaluated value is " ,x)
eval_1()
This method will run the eval on what a user input first, then adds that input to a new variable called b.
When the word "done" is input by the user, then it will print the newly created variable b - exactly as requested by the exercise.
def eval_loop():
while True:
a = input("enter a:\n")
if a == "done":
print(eval(b)) # if "done" is entered, this line will print variable "b" (see comment below)
break
print(eval(a))
b = a # this adds the last evaluated to a new variable "b"
eval_loop()
import math
b = []
def eval_loop():
a = input('Enter something to eval:')
if a != 'done':
print(eval(a))
b.append(eval(a))
eval_loop()
elif a == 'done':
print(*b)
eval_loop()

Python return a value from my function

I am currently trying to figure out how to extract the list of numbers created by this function.
def getInput():
numlist = []
while True:
z = float(input("Enter a number (-9999 to quit): "))
if z == -9999:
print(numlist)
return numlist
else:
numlist.append(z)
print(numlist)
getInput()
Right now the print commands are just for me to confirm that I'm adding numbers to the list, but when the user quits, I need to be able to use new numlist in other functions (I'm going to find the averages of these numbers), and when I try to print the numlist after the function is done, I get an error, which leads me to believe the numlist is disappearing. Could I have some help please?
You are not capturing the numlist being returned.
def getInput():
numlist = []
while True:
z = float(input("Enter a number (-9999 to quit): "))
if z == -9999:
print(numlist)
return numlist
else:
numlist.append(z)
print(numlist)
numlist = getInput()
#do processing here
Your function uses return to return the list object to the caller. You'd store that return value of the function in a new name:
result = getInput()
Now result will be a reference to the same list you built in the function.
You can give it any name you like; it can even be the same name as what was used in the function, but because this name isn't part of the function namespace, that name is entirely separate from the one in the function.
your problem is essentially that any data acquired during a function call is put on the stack, and at the end of the function the stack is cleared. so as mentioned above, result = getInput() would do. or you could pass in a variable to the function as an argument and use that.

Categories