Reputation: 55
use global variable is easy to present the whole design. but global variable has some constraint. It can not function as in the whole class.
It would be better to write a choice function in the code.
It will be def choice in the class.
Now the choice variable is outside the class.
Rewrite the code into the class.
the output is
Enter choice: 1 for full_name, 2 for age, 3 for bmi, 4 for analysis
user enter 1
output: Alex L.
user enter 2
output:28
user enter 3
ouput:0.0024691358024691358
user enter 4
output:You need to eat more.
do not use global variable and use the "def choice:" to rewrite it.
import datetime
choice=input('Enter choice: 1 for full_name, 2 for age, 3 for bmi, 4 for analysis')
choice=int(choice)
class Person:
def __init__(self, name, birthday_year, address, telephone, email):
self.name = name
self.birthday_year = birthday_year
self.address= address
self.telephone = telephone
self.email = email
def full_name(self,surname,firstname):
self.surname = surname
self.firstname = firstname
return self.firstname+" "+self.surname
def age(self,birthday_year):
self.birthday_year=birthday_year
currentyear= datetime.datetime.now().year
age = currentyear - self.birthday_year
return age
def bmi(self,weight,height):
self.weight= weight
self.height = height
result= self.weight / (self.height**2)
return result
def analysis(self,result):
self.result=result
if result < 18.5:
print ("You need to eat more.")
elif result > 25:
print ("Try to care yourself.")
else:
print ("You are a healthy person.")
def main():
s= Person ("Alex",1990,"Wonderland",2345678,"[email protected]")
if choice== 1:
a = s.full_name("L.", "Alex")
print(a)
elif choice==2:
b = s.age(1990)
print(b)
elif choice==3:
c = s.bmi(80, 180)
print(c)
elif choice ==4:
c = s.bmi(80, 180)
d = s.analysis(c)
print(d)
else:
print("invaild entry")
if __name__ == "__main__":
main()
Upvotes: 0
Views: 1397
Reputation: 181
You can use a dictionary and functions, which are needed to be run in each select. Here is a sample code. You will need to modify this code to serve your needs.
def one():
return "Alex L"
def two():
return "28"
def three():
return "0.0024691358024691358"
def four():
return "You need to eat more"
def choice(argument):
switcher = {
1: one,
2: two,
3: three,
4: four,
}
# Get the function from switcher dictionary
func = switcher.get(argument, lambda: "Invalid choice")
# Execute the function
print(func())
choice(1)
choice(2)
choice(3)
choice(4)
Upvotes: 1