Passing Data between functions - python

I have been trying to figure out how to pass data between functions, I'm new to coding. I have tried multiple way to do it, I am struggling to understand how data is passed my code is below. Help would be awesome.
x = []
y = []
z = []
def w(): #Welcome greeting the user and asking for their name
print("Welcome to the BMI Index Calculator.")
name = input("Enter employee's name or Exit to quit: ") # Allows the user to input there name as a variable
if str.isnumeric(name): # Test as a string
print("That is not a name.")
w()
if name == 'Exit': # sets the Exit for the program
print("Exiting program...")
exit() # ends program
else:
name = x.append(name)
def h():
height = input("Enter employee's height in inches: ")
if height == '0': # sets the Exit for the program
print("Exiting program...")
exit() # ends program
else:
height = y.append(height)
def wt():
weight = input("Enter employee's weight in lbs: ")
if weight == '0': # sets the Exit for the program
print("Exiting program...")
exit() # ends program
else:
weight = z.append(weight)
def bmi(): #gives the data back to the user
print(str(x).replace('[', '').replace(']', '').replace("'", '') + "'s " + "BMI profile")
print("---------------------------")
print("Height: ", str(y).replace('[', '').replace(']', '').replace("'", ''), '"')
print("Weight: ", str(z).replace('[', '').replace(']', '').replace("'", ''), "lbs.")
def math_cal():
bmi_weight = int(z) * 703
bmi_height = int(y) ** 2
print("BMI: ", bmi_weight / bmi_height)
def run():
x = w()
y = h()
z = wt()
xy = bmi()
xz = math_cal()
__main__()
run()
__main__()
I have been successful in passing the data to other functions but the code fails to see the list as an int. Thus I have found my way here, trying to get ideas of how to rewrite this code in a more efficient manner. I am looking for a way to reference functions to pass data between functions, however I have not been find a clean way to execute that process.

There are to points where values are passed when using functions:
at the start of the function, with parameters
at the end of the function, as return value
let us first take a look at the return value:
For example in your h() function, you ask the user for the height. This value is stored in height
height = input("Enter employee's height in inches: ")
after checking for all the cases you want, you can return one value at the end of the function by using "return":
return height
the complete function becomes:
def h():
height = input("Enter employee's height in inches: ")
if height == '0': # sets the Exit for the program
print("Exiting program...")
exit() # ends program
return height
This means if you call the function h() it will ask for the height and return the value which it obtained. This could be used by you program like this:
bmi_height = h()
or
bmi_height = h()*2
if you want to multiply the entered value with 2.
The second part, passing values to a function at the start of the function with parameters:
for example you want to use the height and weight when calculating the BMI, then the function becomes:
def bmi(height, weight)
print("BMI: ", bmi_weight / bmi_height)
this function has to be called like this:
bmi(170, 85)
when entering the values hard-coded or
height = 170
weight = 85
bmi(height, weight)
when you use variables.

Related

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

Using var() to instantiate object from user input. Syntax error

I've made these classes and now I'm trying to make a function that allows you to instantiate a new object from data a user inputs. But I'm getting syntax errors with using var()
The class structure is that there is one main with two sub-classes. The main, "Gokemon" is:
class Gokemon:
def __init__(self,NAME,TYPE,HEALTH,POWER): #Contructor #Mayb think about using dict key words
self._Name = str(NAME)
self._Type = str(TYPE) #Water, Earth, Fire or Flying. Used in Battle() to allow adders
self._HP = int(HEALTH) #Health Points
self._DP = int(POWER) #Power Points - attacking power
and the two sub-classes are named "Tame" and "Wild".
class Tame(Gokemon):
def __init__(self,NAME,TYPE,HEALTH,POWER):
Gokemon.__init__(self,NAME,TYPE,HEALTH,POWER)
self._Owner = ""
self._Time = 0 #How long have they owned it
class Wild(Gokemon):
def __init__(self,NAME,TYPE,HEALTH,POWER):
Gokemon.__init__(self,NAME,TYPE,HEALTH,POWER)
The function for making the new object by user input is as follows:
def NewGokemon():
n = input("What's its name?: ")
while True:
t = input("what's its type?: ")
if t == "Water" or t == "Fire" or t=="Earth" or t =="Flying":
break
else:
print("please try again, the types include:\nFire\nWater\nEarth\nFlying")
while True:
h = input("How many Health Points(HP) does it have")
try:
int(h)/2
except ValueError:
print("Sorry please input a numerical value")
else:
break
while True:
p = input("How many Health Points(HP) does it have")
try:
int(p)/2
except ValueError:
print("Sorry please input a numerical value")
else:
break
while True:
dom = input("Is the Gokemon tame(input t) or wild(input w)?")
if dom =="t":
return var()[n] = Tame(n,t,h,p)
if dom == 'w':
return var()[n] = Wild(n,t,h,p)
The function is fine until at the bottom, when im compiling to execute my Editor (VS code) says.
File "c:\Users\rufar\Desktop\python\little projects\Gokemon - learning class\Gokemon.py", line 38
return var()[n] = Tame(n,t,h,p)
^
SyntaxError: invalid syntax
What am i doing wrong? Is there a better way of doing this?
replaced the whole bit with vars() with this:
while True:
dom = input("Is the Gokemon tame(input t) or wild(input w)?")
if dom =="t":
globals()[n] = Tame(n,t,h,p)
return n
elif dom == 'w':
globals()[n] = Wild(n,t,h,p)
return n
else:
print("Did not understand input")
And now it works fine.

Python: ' ' is not defined

Here is my code:
# This program makes the robot calculate the average amount of light in a simulated room
from myro import *
init("simulator")
from random import*
def pressC():
""" Wait for "c" to be entered from the keyboard in the Python shell """
entry = " "
while(entry != "c"):
entry = raw_input("Press c to continue. ")
print("Thank you. ")
print
def randomPosition():
""" This gets the robot to drive to a random position """
result = randint(1, 2)
if(result == 1):
forward(random(), random())
if(result == 2):
backward(random(), random())
def scan():
""" This allows the robot to rotate and print the numbers that each light sensors obtains """
leftLightSeries = [0,0,0,0,0,0]
centerLightSeries = [0,0,0,0,0,0]
rightLightSeries = [0,0,0,0,0,0]
for index in range(1,6):
leftLight = getLight("left")
leftLightSeries[index] = leftLightSeries[index] + leftLight
centerLight = getLight("center")
centerLightSeries[index] = centerLightSeries[index] + centerLight
rightLight = getLight("right")
rightLightSeries[index] = rightLightSeries[index] + rightLight
turnRight(.5,2.739)
return leftLightSeries
return centerLightSeries
return rightLightSeries
def printResults():
""" This function prints the results of the dice roll simulation."""
print " Average Light Levels "
print " L C R "
print "========================="
for index in range(1, 6):
print str(index) + " " + str(leftLightSeries[index]) + " " + str(centerLightSeries[index]) + " " + str(rightLightSeries[index])
def main():
senses()
pressC()
randomPosition()
scan()
printResults()
main()
So, I am getting this error when I run my program.
NameError: global name 'leftLightSeries' is not defined
I understand that I must be doing something wrong related to the return statement. I'm not sure if I can only return one variable at the end of a user-defined function. If that were to be true, then I should probably separate the scan(): function. Anyways, I would appreciate any help on how to fix this error. Also, this is the result that I am looking for when I successfully complete my program:
Click Here
I am looking to complete the average values like the picture shows, but I am not worried about them at this point, only the list of values from the light sensors. I do not need to reach those exact numbers, the numbers will vary in the simulator.
If you want to return multiple items from scan(), don't use three separate return statements. Instead, do this:
return leftLightSeries, centerLightSeries, rightLightSeries
Also, when you call the function, you have to assign variable(s) to the returned values; it won't automatically create new local variables with the same names. So in main, call scan() like this:
leftLightSeries, centerLightSeries, rightLightSeries = scan()

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)

Working on a basic python calculator and can't get my menu to loop properly

Thanks to this site I was able to get this far, being the python novice I am, however I'm kind of stuck. I'm trying to loop 'selection', so after a user does some math, rather than just ending it will give them the option to do something else until they select 0 to quit. I tried a bunch of other try and conditional statements but just end up getting answers and such stuck in an infinite loop.
Also, I'm pretty here, but any help is appreciated, also I'm a python nub. I'm writing this with python 2.7, if that matters.
def sum ( arg1, arg2):
total = a + b
return total;
def subtract ( arg1 , arg2):
total = a - b
return total;
def mult ( arg1, arg2):
total = a * b
return total;
def division ( arg1, arg2):
total = (a / b)
return total;
options = ["1", "2", "3", "4", "5", "0"]
print ("Please choose an option for mathing")
print ("1 for addition")
print ("2 for division")
print ("3 for subtraction")
print ("4 for multiplication")
print ("5 ")
print ("0 to exit")
#this will keep prompting the user to provide an input that is listed in 'options'
while True:
selection = input("Please select choose an option to continue")
if selection in options:
break
else:
print("Please choose a valid option")
#user input for mathing
#input will be validated as follows
a = None
while a is None:
try:
a = int(input("please provide a number for A"))
except ValueError:
print "please use a valid integer"
pass
b = None
while b is None:
try:
b = int(input("please provide a number for B"))
except ValueError:
print "please use a valid integer"
pass
#performing the operations
if selection == '1':
print "The sum is", str(sum(a, b))
elif selection == '2':
print "The quotient is", str(division(a, b))
elif selection == '3':
print "The difference is", str(subtract(a, b))
elif selection == '4':
print "The product is", str(mult(a, b))
elif selection == '0':
exit()
heres a few things I would do to make this more efficient..
options should be a dictionary... your in is a lot more efficient on a dictionary than on a list. the beauty of this is the value for each key can be function methods.
ex. options = {1: 'sum', 2: 'subtract' ..... }
then make a class with your math operations in it
class Calculator(object):
def sum(self, x, y):
return x + y
def subtract(self, x, y):
return x - y
#add more operations here
#staticmethod
def start():
while True:
#prompt for input and the operator
whats nice about this is in your checks for the selection you can dynamically call the class method to clean the code up a lot
if selection in options:
getattr(options[selection], Calculator)(a, b)
if you want me to explain more I can finish the example.
for your loop, you can add a method that starts the action and continues looping and doing more operations each time
here is a basic class you can use using those methods I described
class Calculator(object):
loop = None
calculations = 1
current_value = 0
selection = 0
options = {1: 'add', 2: 'subtract', 3: 'multiply', 4: 'divide'}
def __init__(self, loop=True):
self.loop = loop
print 'Welcome to my basic calculator!'
if not self.loop: # dont loop just execute once
self.run()
else:
while True:
self.run()
#staticmethod
def add(x, y):
return x + y
#staticmethod
def subtract(x, y):
return x - y
#staticmethod
def multiply(x, y):
return x * y
#staticmethod
def divide(x, y):
if y != 0: #cant divide by 0
return x / y
#staticmethod
def quit():
exit(0)
def run(self):
if self.calculations == 1:
self.current_value = self.prompt_user_input('please provide a number: ')
self.prompt_operator('Please choose an operator to continue\n1 for addition\n2 for subtraction\n3 for multiplication \n4 for division\n0 to quit\n')
y = self.prompt_user_input('please provide a number: ')
self.current_value = getattr(Calculator, self.options[self.selection])(self.current_value,y)
self.calculations += 1
print 'New value is: ' + str(self.current_value)
def prompt_operator(self, prompt_message):
while True:
self.selection = input(prompt_message)
if self.selection in self.options:
break
elif self.selection == 0:
self.quit()
else:
print("Please choose a valid option")
def prompt_user_input(self, prompt_message):
val = None
while val is None:
try:
val = int(input(prompt_message))
except ValueError:
print "please use a valid integer"
pass
return val
finally to start your calculator off you can just call it and either pass true to continue loops or pass false to only do one calculation
Calculator(loop=True)
Just put a loop around the prompting and calculation. If they enter 0, break from the outer-most loop:
while True:
#this will keep prompting the user to provide an input that is listed in 'options'
while True:
selection = input("Please select choose an option to continue")
if selection in options:
break
else:
print("Please choose a valid option")
if selection == '0':
break
...
#this will keep prompting the user to provide an input that is listed in 'options'
while True:
selection = input("Please select choose an option to continue")
if selection in options:
if selection == 1:
sum()
if selection == 2:
subtract()
.....
if selection == 'q'
break
Change the logic to what I did above, for option,take some action and do break on the quit character/
Firstly, your code should not work as it is now:
if selection == '1': #should return false
That's because using input you are taking a numeric quantity and then comparing it to a string.
change the input of selection to raw_input
Or change the conditional statements like below:
if selection == 1:
Then add a while True over the entire execution block to go through the execution again and again, until 0 is selected.

Categories

Resources