How Can I Call A Function With Variable Value in python - python

'''
operator = input("Enter What You Wanna Do (add/sub/multi/div")
firstNum = int(input("Enter First Number:"))
secondNum = int(input("Enter Second Number:"))
def add(result):
result = firstNum + secondNum
return result
def sub(result):
result = firstNum - secondNum
def multi(result):
result = firstNum * secondNum
return result
def div(resukt):
result = firstNum / secondNum
return result
'''
in this code how can i call all those functions when needed without 4 if statements i tried to add like operator() in hopes of it will take value of operator variable and call specific user entered function but it failed can some one give an option

If Someone Wonders The Answer Ive Been Able To Figure That Out
eval(operator+"()")
Adding this function willl fix it ;)

To answer the question in the title you can use globals() to return a function based on a string. Here, that would look something like:
operator = input("Enter What You Wanna Do (add/sub/multi/div)")
firstNum = int(input("Enter First Number:"))
secondNum = int(input("Enter Second Number:"))
def add():
result = firstNum + secondNum
return result
func_obj = globals()[operator]
print(f'The answer is {func_obj()}')

Related

python : passing multiple variables from a function to another from a user PROMPT

How do I pass multiple (2 or more) variables from a function to another in python? I have searched all around the internet, yet I am unable to understand most of the explanations given, many examples just do not fit my case, and I cannot fix the problem with a MRE. Here is the example code:
def prompt_user():
money1 = input("insert a value")
money2 = input(" insert another value")
return money1, money2
def add(money1, money2):
cash = int(money1) + int(money2)
return cash
two_values = prompt_user()
total = add(two_values)
print("you have "+ str(total))
Is this just unable to be done in python? Or do you have to use something like lists to pass arguments in this case?
Examples I have found(yet not understood):
Python — Passing Multiple Arguments
https://www.geeksforgeeks.org/how-to-pass-multiple-arguments-to-function/
EDIT: I fixed it. Turns out we have to break the tuple when passing values from another function. Thank you everyone.
I think the problem is due to the definition of arguments in method definition. So in general you can pass lists, functions, etc. to a function. In this case, I have collected the inputs in a tuple and pass the tuple to the function.
def prompt_user():
money1 = input("insert a value")
money2 = input(" insert another value")
z=(money1,money2)
return z
def add(z):
cash = int(z[0]) + int(z[1])
return cash
two_values = prompt_user()
total = add(two_values)
print("you have "+ str(total))
You either want to unpack those values on function call:
total = add(*two_values)
Or unpack them on assignment:
val_one, val_two = prompt_user()
total = add(val_one, val_two)
def prompt_user():
money1 = int(input("Insert a value: "))
money2 = int(input("Insert another value: "))
# You can get many more input like above
return (money1, money2) # pass paratmeter inside () as tuple
def add(values):
return sum(list(values))
multi_vaules = prompt_user()
total = add(multi_vaules)
print("you have "+ str(total))
If you need to get sum of any variable then you follow the code
def prompt_user():
money1 = input("Insert a value: ")
money2 = input("Insert another value: ")
# You can get many more input like above
return (money1, money2) # pass paratmeter inside () as tuple
def add(values):
res=''
for val in values:
res+=val
return res
multi_vaules = prompt_user()
total = add(multi_vaules)
print("you have "+ str(total))
You can customize val if you need to convert int or float like anything by using type casting. If you need to get int type then use int(val) to get res. But before on that you also need to declare res as int or any others
Look for integer value
def add(values):
res=0
for val in values:
res+=int(val)
return res
If you run it like this it works:
money1 = 5
money2 = 7
def add(money1, money2):
cash = int(money1) + int(money2)
return cash
total = add(money1,money2)
print("you have "+ str(total))
As you can see you just have to put the first variable , and then second variable.
If you have the prompt you can just split the answers as:
money1, money2 = prompt_user()
EDIT:
def prompt_user():
money1 = input("insert a value")
money2 = input(" insert another value")
return money1, money2
def add(money1, money2):
cash = int(money1) + int(money2)
return cash
money1, money2 = prompt_user()
total = add(money1, money2)
print("you have "+ str(total))
I would change the last sentence to
print(f'You have {total}')

Python: How receive values from an input function and have them working as an integer? [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 2 years ago.
I am currently writing a program that receives input from users and processes them in separate functions.
MRE:
def prompt_user():
money1 = input("insert a value")
money2 = input(" insert another value")
return money1, money2
def add(money1, money2):
cash = int(money1) + int(money2)
return cash
two_values = prompt_user()
total = add(*two_values)
print("you have "+ str(total))
My problem with the code above is that it's really ugly. How am I able to process the data from users WITHOUT writing int() for every variable I used?
You can use a map:
def prompt_user():
money1 = input("insert a value")
money2 = input(" insert another value")
return map(int, (money1, money2))
Or you can create a function named input_int(text) to avoid duplication:
def input_int(text=""):
return int(input(text))
def prompt_user():
money1 = input_int("insert a value")
money2 = input_int(" insert another value")
return money1, money2
Here is a better version of input_int(text):
def input_int(text=""):
while True:
try:
res = int(input(text))
break
except ValueError:
print("The input must be an integer")
return res
No, you have to cast the input to integer at a point. Better approach will be to use int() on input() and .format():
def prompt_user():
money1 = int(input("insert a value"))
money2 = int(input(" insert another value"))
return money1, money2
def add(money1, money2):
cash = money1 + money2
return cash
two_values = prompt_user()
total = add(*two_values)
print("you have {}".format(total))

How can i check if what I input into my text based calculator is an number?

When I prompt the console to ask the user to input a number for the calculator, I want to check if what the user input is a number. In the first_input() I used a if else condition to check if what the user input was a number. Although if false the function is called again to prompt the user to type a number, it returns none once i try calculating it into my calculator, why is this and how can I properly return the number properly after the user fails to input a number?
# Operations variable
oper = "+-*/"
# Calculates basic operations
def calc(x, op, y):
for i in oper:
if i == str(op):
return eval(str(x) + op + str(y))
# Main function that controls the text-based calculator
def console_calculator():
def first_input():
x = input('Type your first number: ')
if x.isnumeric():
return x
else:
print('Please type in a number')
first_input()
def operation_input():
operat = input('Type one of the following, "+ - * /": ')
return operat
def next_input():
y = input('Type your next number: ')
return y
answer = calc(first_input(), operation_input(), next_input())
print(answer)
console_calculator()
I'd suggest a try/except block. This way it will return the integer itself especially since you're already turning them into strings in the eval block.
x = input('Type your first number: ')
try:
return int(x)
except ValueError:
print('Please type in a number')
...
Also to keep asking the user for an integer until they input the correct value I'd use a while loop.
Instead of using two functions for user input you can use single function call it two times. and you also need to add return before function call in user input.
def console_calculator():
def user_input():
x = input('Type your number: ')
if x.isnumeric():
return x
else:
print('Please type in a number')
return user_input()
def operation_input():
operat = input('Type one of the following, "+ - * /": ')
return operat
answer = calc(user_input(), operation_input(), user_input())
print(answer)
You actually hid the answer in your own question:
how can I properly return the number
You forgot to return in your else branch:
# Calculates basic operations
def calc(x, op, y):
for i in op:
if i == str(op):
return eval(str(x) + op + str(y))
# Main function that controls the text-based calculator
def console_calculator():
def first_input():
x = input('Type your first number: ')
if x.isnumeric():
return x
else:
print('Please type in a number')
return first_input() # missing return
def operation_input():
operat = input('Type one of the following, "+ - * /": ')
return operat
def next_input():
y = input('Type your next number: ')
return y
answer = calc(first_input(), operation_input(), next_input())
print(answer)
console_calculator()
But you also have a compilation error because you refer to oper but the parameter is called op.
This merely answers your question, but doesn't address the architecture (which others will, as they cover better implementations).

Python main() not executing properly

In my python program, I have multiple functions defined, then a main function that also holds the menu. The menu is the first thing that should be displayed, but the program is attempting to run the defined functions that are before the main function, first. This is resulting in many problems. Any suggestions.
#!usr/bin/env python
import operator
saved_string = ''
def remove_letter():
return
def num_compare():
return
def print_string():
print saved_string
return
def calculator():
sign_dict = {"+": operator.add(), "-": operator.sub(), "*": operator.mul(), "&": operator.div()}
num1 = int(raw_input("First number: "))
sign = str(raw_input("Action: "))
num2 = int(raw_input("Second number: "))
print sign_dict[sign] (num1, num2)
return
def accept_store():
global saved_string
saved_string = str(raw_input("Enter string: "))
return
def main():
opt_list = [accept_store(),
calculator(),
print_string(),
num_compare(),
remove_letter()]
while(True):
print "SELLECT OPTIONS:"
print "1\tAccept and Store"
print "2\tCalculator"
print "3\tPrint String"
print "4\tNumber Compare"
print "5\tRemove Letter"
opt_choice = int(raw_input("SELLECTION: "))
opt_choice -= 1
opt_list[opt_choice]()
return
main()
() is a function call notation. So in opt_list, you're listing all the function calls, not the function names. You'd have to change it to:
opt_list = [fn1, fn2, ...]
Then call each function like:
for f in opt_list:
f()

Python and Variable Passing

I have spent the last few hours reading around on the net and looking at the Python online manual (currently using Python v2.7) but I'm still struggling to understand how I pass a variable from one function to another.
At the moment I am just starting out with something simple, to get my head around passing variables. I have 3 functions (one which will display a hello message), another that will ask for user input and the third that will take the user input and perform the calculation).
For the life of me I cant figure how to get the user input values into the calculation function. I thought that once I entered the values in the user input, I could send them to the calc function. But I cant.......I keep getting an error message:
calc = calculation(num1, num2)
NameError: global name 'num1' is not defined
Can someone point out where I am going wrong ? This is driving me nuts !
def main():
message()
input = user()
calc = cal(num1, num2)
def message():
print "Welcome message"
def user():
side_a = int(raw_input("Enter a: "))
side_b = int(raw_input("Enter b: "))
return side_a, side_b
def cal(num1, num2):
side_c = side_a + side_b
return side_c
So think of it like this:
You have a function (def user() ) which will return two values. You have to receive those two values and store them somewhere. In your main() you use variable "input" which is now have to hold two values as written. If you were to do:
print input
You'd get (value of side A, value of side B) passed back to you. If you instead wrote
print input[0]
It would print just side A. More easy (in my mind) would be having two variables standing by to receive the returned values:
input1, input2 = user()
Now in your def cal(num1,num2) it is expecting to receive two arguments and return one value. So your main should look like this:
def main()
message()
input = user()
calc = cal(input[0], input[1])
When you define your function, the variables you use (num1, num2) is how you are going to represent the inputs in that function. If you just pass the arguments num1, num2 they have no value as they were not declared in main. The names do not have to match, you just have to pass the right number(and type) of arguments.
So for example:
def sample(int1, int2, string):
number3 = number1 + number2
print(string1 + str(number3))
You could pass this raw data, or pass it variables. In this sample main, the printed output would be the same:
def main():
number1 = 2
number2 = 2
string1 = "two plus two equals: "
sample(2,2,"two plus two equals: ")
sample(number1,number2,string1)
Change what you have to
def main():
message()
num1, num2 = user() # grab the numbers from user fn and store them in num1, num2
calc = cal(num1, num2)
def message():
print "Welcome message"
def user():
side_a = int(raw_input("Enter a: "))
side_b = int(raw_input("Enter b: "))
return side_a, side_b
def cal(side_a, side_b):
side_c = side_a + side_b
return side_c

Categories

Resources