使用全局变量很容易呈现整个设计。但是全局变量有一些约束。它不能在全班发挥作用。你知道吗
最好在代码中编写一个选择函数。你知道吗
这将是课堂上的首选。你知道吗
现在choice变量在类之外。你知道吗
将代码重写到类中。你知道吗
输出为
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.
不要使用全局变量并使用“def choice:”重写它。
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,"aa@smail.com")
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()
您可以使用字典和函数,它们需要在每个select中运行。下面是一个示例代码。您需要修改此代码以满足您的需要。你知道吗
相关问题 更多 >
编程相关推荐