I am new to python and trying to figure out the issues in my first python code. I am taking an input temp
from user in method parameter
and i want to compare this temp
with another variable oven_temp
in make_item
method. But I get a NameError
that name temp
is not defined. I read some posts here and it was mentioned that I had to return value from a method. I returned it but not getting exactly how to proceed.
class maker:
def parameter(self):
temp = int (input ('At what temperature do you want to make \n'))
return temp
def make_item (self):
def oven (self):
oven_temp = 0
while (oven_temp is not temp):
oven_temp += 1
print ("waiting for right oven temp")
oven(self)
person = maker ()
person.parameter()
person.make_item()
Keep it in your self
!
class MyMaker:
def ask_temperature(self):
self.temp = int(input('Temperature? \n'))
def print_temperature(self):
print("temp", self.temp)
Try it:
> maker = MyMaker()
> maker.ask_temperature()
Temperature?
4
> maker.print_temperature()
temp 4
The following should work to solve your problem. Basically, you want to store the variables you want to pass between methods as members of the class. You do this by assigning an attribute of the self
parameter to the functions.
class maker:
def parameter(self):
self.temp = int (input ('At what temperature do you want to make \n'))
def make_item (self):
def oven ():
oven_temp = 0
while (oven_temp is not self.temp):
oven_temp += 1
print ("waiting for right oven temp")
oven()
person = maker ()
person.parameter()
person.make_item()
This is another way as to how you can return value from one method and pass the same to another method and finally print the result.
class Maker():
def parameter(self):
temp = int(input('At what temperature do you want to make \n'))
return temp
def make_item(self,temp):
def oven():
oven_temp = 0
while (oven_temp is not temp):
oven_temp += 1
print ("waiting for right oven temp")
return oven_temp
return oven()
person = Maker()
val = person.parameter()
print(person.make_item(val))
Output:
waiting for right oven temp
waiting for right oven temp
waiting for right oven temp
waiting for right oven temp
4
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.