Python and Variable Passing - python

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

Related

How Can I Call A Function With Variable Value in 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()}')

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: Can 1 function accept variables from 2 different fucntions

OK - I am trying to get a Python function to accept variables from two other functions. Is this possible ?
A sample of what I am trying to do it below (I have simmed down the original code - for input here). Hopefully you get theidea of what I am trying to do. In a nutshell, I have Rectangle () which calls Extras() and the I want the output from Rectangle and Extras to be sent to the Calculate_Deposit ().
Is this possible ?
def calculate_deposit(total_cost, extras):
deposit_percent = float(raw_input("Enter Deposit % (as a decimal) of Total Cost: "))
months_duration = float(raw_input("Enter the number of months client requires: "))
if deposit_percent >0:
IN HERE JUST SOME CALCULATIONS
else:
print "The total amount required is: ", total_cost
def rectangle(width, height, depth, thickness):
type = raw_input("Enter lowercase c for concrete: ")
if type == 'c':
output = IN HERE JUST COME CALCULATIONS
else:
return raw_input("Oops!, something went wrong")
print output + extras()
total_cost = calculate_deposit(output, extras)
def extras():
type = float(raw_input("Enter 1 for lights: "))
if type == 1:
light = 200
print "The cost of lights are: ", light
return light
else:
return raw_input("No extras entered")
In rectangle, you call extras(), then you send just the function extras to calculate_deposit(). You want to send the result of the extras() call, not a reference to the function itself. You can make a minor change and save that value, referring to it when you print and when you go into calculate_deposit.
Change this:
print output + extras()
total_cost = calculate_deposit(output, extras)
To this:
extra = extras()
print output + extra
total_cost = calculate_deposit(output, extra)

Referenced before assignment Python

I have the following code:
#AON = Amount of Numbers to average
def general():
print "Enter how many numbers you will enter."
print "Maximum amount is 10: "
aon = raw_input()
try:
aon = int(aon)
if aon >= 10:
print "I cannot average more than 10 numbers."
general()
else:
start_average()
except ValueError:
print "You entered an invalid input, try again."
general()
def start_average():
if aon == 1:
print "You cannot average one number."
general()
elif aon == 2:
def first_number():
print "First number: "
first_ni = raw_input()
second_number()
first_number()
def second_number():
print "Second number: "
second_ni = raw_input()
ans_two = first_ni / second_ni
second_number()
final_two()
elif aon == 3:
def third_number():
first_number()
second_number()
print "Third number: "
third_ni = raw_input()
ans_three = ans_two / third_ni
third_number()
final_three()
elif aon == 4:
def fourth_number():
first_number()
second_number()
third_number()
print "Fourth number: "
fourth_ni = raw_input()
ans_four = ans_three / fourth_ni
fourth_number()
final_four()
elif aon == 5:
def fifth_number():
first_number()
second_number()
third_number()
fourth_number()
print "Fifth number: "
fifth_ni = raw_input()
ans_five = ans_four / fifth_ni
fifth_number()
final_five
def final_two():
final_input = ans_two
final_answer()
def final_three():
final_input = ans_three
final_answer()
def final_four():
final_input = ans_four
final_answer
def final_five():
final_input = ans_five
final_answer()
def final_six():
final_input = ans_six
final_answer()
def final_seven():
final_input = ans_seven
final_answer()
def final_eight():
final_input = ans_eight
final_answer()
def final_nine():
final_input = ans_nine
final_answer()
def final_answer():
listofnumbers = [first_ni, second_ni, third_ni, fourth_ni, fifth_ni, sixth_ni, seventh_ni, eight_ni, ninth_ni]
print "The average of your numbers:"
print listofnumbers
print "Is = %d." % final_input
general()
It's purpose is to find the average of a number, but when I run it through PowerShell, I get the following error:
Traceback (most recent call last):
File "average.py", line 97, in <module>
general()
File "average.py", line 10, in general
general()
File "average.py", line 10, in general
general()
File "average.py", line 12, in general
start_average()
UnboundLocalError: local variable 'start_average' referenced before assignment
I've probably done this more throughout my code, and I just made this, but I just don't know how to fix it or what is the error showing! I don't understand.
It's hard to tell from what you've pasted, because you've clearly broken the indentation.
But it looks like this code:
print "Enter how many numbers you will enter."
print "Maximum amount is 10: "
… is meant to be inside general, while this code:
aon = raw_input()
try:
aon = int(aon)
if aon >= 10:
print "I cannot average more than 10 numbers."
general()
else:
start_average()
except ValueError:
print "You entered an invalid input, try again."
general()
… is meant to be at module level.
Code is executed in the order it appears. Function definitions are just code, like anything else. So, you can't call a function before you define it, because the function doesn't exist yet.
You're probably about to object, with an example like this:
def foo():
bar()
def bar():
print('Hi!')
foo()
It looks like we're calling bar before it exists, and yet it works. How?
Well, the definition of foo is being executed before bar exists, but that's fine. That just defines a function that will, when run, call whatever bar means. As long as we've defined bar before we call it—and we have—everything is fine.
However, you have a number of similar problems in your code. For example, let's look at this part:
elif aon == 2:
def first_number():
print "First number: "
first_ni = raw_input()
second_number()
first_number()
def second_number():
print "Second number: "
second_ni = raw_input()
ans_two = first_ni / second_ni
second_number()
final_two()
That first_ni is a local variable within the first_number function. Every time you call first_number, a new first_ni gets defined, but only visible within that function. You can't use it in second_number, because second_number can only see its own local variables, and global variables, and first_ni is neither.
The concept you need to understand is called scope. Python has some nice tools to help you understand scope. You can print out locals() and globals() and dir() at any part of your program to see what's in scope there. But you'll need to read the tutorial first.
Indentation and a few other things are questionable. I'm not sure why you're defining all of these functions inside of other functions... I think this will do what you want. You're going to need a lot more error checking though (making sure the inputs are integers, divide by 0, etc.)
>>> def getMean(maxNumsToDivide):
... listNums = []
... for i in range(maxNumsToDivide):
... num = raw_input("Please enter a number: ")
... if not num:
... break
... listNums.append(int(num))
... return float(sum(listNums))/len(listNums)
...
>>> getMean(100)
Please enter a number: 2
Please enter a number: 3
Please enter a number: 4
Please enter a number: 5
Please enter a number: 3
Please enter a number:
3.4

Categories

Resources