Python return a value from my function - python

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.

Related

How to fill a input() function with variable

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.

I'm having issues using generators with the input function in python 3

def prime():
n = 1000
if n<2:
return 0
yield 2
x = 3
while x <= n:
for i in range(3,x,2):
if x%i==0:
x+=2
break
else:
yield x
x+=2
#if i try to call each yielded value with an input function i don't get anything!
def next_prime():
generator = prime()
y = input('Find next prime? yes/no or y/n: ')
if y[0].lower == 'y':
print(generator.next())
next_prime()
#but if i call the function without using an input i get my values back
generator = prime()
def next_prime():
print(next(generator))
next_prime()
How do I make the first next_prime function work with the input function. If I try to call each yielded value with an input function, I don't get anything but if I call the function without using an input, I get my values back. Is it that generators don't work with the input function?
The mistake you have done is you have forgot the round brackets of the lower keyword
def next_prime():
generator = prime()
y = input('Find next prime? yes/no or y/n: ')
#forgot the round brackets
if y[0].lower() == 'y':
print(next(generator))
next_prime()

Can input exist within a defined function in Python?

I am trying to shorten the process of making lists through the use of a defined function where the variable is the list name. When run, the code skips the user input.
When I run my code, the section of user input seems to be completely skipped over and as such it just prints an empty list. I've tried messing around with the variable names and defining things at different points in the code. Am I missing a general rule of Python or is there an obvious error in my code I'm missing?
def list_creation(list_name):
list_name = []
num = 0
while num != "end":
return(list_name)
num = input("Input a number: ")
print("To end, type end as number input")
if num != "end":
list_name.append(num)
list_creation(list_Alpha)
print("This is the first list: " + str(list_Alpha))
list_creation(list_Beta)
print("This is the second list: " + str(list_Beta))
I want the two seperate lists to print out the numbers that the user has input. Currently it just prints out two empty lists.
You need to move the return statement to the end of the function, because return always stops function execution.
Also, what you're trying to do (to my knowledge) is not possible or practical. You can't assign a variable by making it an argument in a function, you instead should remove the parameter list_name altogether since you immediately reassign it anyway, and call it like list_alpha = list_creation()
As a side note, the user probably wants to see the whole "To end, type end as number input" bit before they start giving input.
Dynamically defining your variable names is ill advised. With that being said, the following code should do the trick. The problem consisted of a misplaced return statement and confusion of variable name with the variable itself.
def list_creation(list_name):
g[list_name] = []
num = 0
while num != "end":
num = input("Input a number: ")
print("To end, type end as number input")
if num != "end":
g[list_name].append(num)
g = globals()
list_creation('list_Alpha')
print("This is the first list: " + str(list_Alpha))
list_creation('list_Beta')
print("This is the second list: " + str(list_Beta))
There are a couple of fundamental flaws in your code.
You redefine list_name which is what Alpha and Beta lists are using as the return.(list_name = [] disassociates it with Alpha and Beta so your function becomes useless.)
You return from the function right after starting your while loop(so you will never reach the input)
In your function:
list_Alpha = []
list_Beta = []
def list_creation(list_name):
# list_name = [] <-- is no longer Alpha or Beta, get rid of this!
num = 0
...
The return should go at the end of the while loop in order to reach your input:
while num != "end":
num = input("Input a number: ")
print("To end, type end as number input")
if num != "end":
list_name.append(num)
return(list_name)

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

Categories