为了账号安全,请及时绑定邮箱和手机立即绑定

我在尝试计算退休年龄的脚本中有错误

我在尝试计算退休年龄的脚本中有错误

不负相思意 2022-06-22 20:35:30
我正在尝试计算一个人的年龄,以验证他是否已达到退休年龄。这是python 2.7from datetime import datetimedef getName():  name = input("What is your name?: ")  return namedef getAge():  age = input("How old are you?: ")  return int(age)def ifOrNot():  retirementAge = 65  if(getAge() >= retirementAge):    print("Hello  ",getName(), ", are you in retirment age")  else:    timeToRetirement = retirementAge - getAge()    print("Hello ", getName(), " are you not in retirement age, you need to wait ", timeToRetirement, " more").def main():  ifOrNot()main()“你多大了”这个问题在屏幕上出现了两次。然后显示一次“你叫什么名字”这个问题。然后是这些错误:Traceback (most recent call last):   File "main.py", line 22, in<module>    main()   File "main.py", line 20, in main    ifOrNot()   File "main.py", line 17, in ifOrNot    print("Hola ", getName(), " aun no estas en edad de retiro, te faltan ", timeToRetirement)   File "main.py", line 4, in getName    name = input("What is your name?: ")   File "<string>", line 1, in <module> NameError: name 'Diesan' is not defined我想先问名字,再问年龄,然后计算出能够退休的剩余年限。奇怪的是,我不需要使用datetime,对吧?
查看完整描述

2 回答

?
芜湖不芜

TA贡献1796条经验 获得超7个赞

def getName():

  name = input("What is your name?: ")

  return name

input()在 python2.7 中尝试评估它作为函数获得的任何内容-raw_input()改为使用获取字符串,该字符串将作为纯字符串返回。


def ifOrNot():

  retirementAge = 65

  if(getAge() >= retirementAge):

    print("Hello  ",getName(), ", are you in retirment age")

  else:

    timeToRetirement = retirementAge - getAge()

    print("Hello ", getName(), " are you not in retirement age, you need to wait ", timeToRetirement, " more").

如果您未到退休年龄,getAge()将在第一个if语句中调用一次,然后在else语句中再次调用。考虑将结果分配给getAge()变量并重用它。此外,您在第二个语句.的末尾有一个迷路。print()


你是对的,你不需要使用datetime.


正确的代码如下:


def getName():

  name = raw_input("What is your name?: ")

  return name


def getAge():

  age = input("How old are you?: ")

  return int(age)


def ifOrNot():

  retirementAge = 65

  myAge = getAge()

  if(myAge >= retirementAge):

    print("Hello  ",getName(), ", are you in retirment age")

  else:

    timeToRetirement = retirementAge - myAge

    print("Hello ", getName(), " are you not in retirement age, you need to wait ", timeToRetirement, " more")


def main():

  ifOrNot()


main()


查看完整回答
反对 回复 2022-06-22
?
森林海

TA贡献2011条经验 获得超2个赞

将答案保存在变量中:


def ifOrNot():

    retirementAge = 65

    name = getName()

    age = getAge()

    if (age >= retirementAge):

        print("Hello  ", name, ", are you in retirment age")

    else:

        timeToRetirement = retirementAge - age

        print("Hello ", getName(), " are you not in retirement age, you need to wait ", timeToRetirement, " more").



查看完整回答
反对 回复 2022-06-22
  • 2 回答
  • 0 关注
  • 84 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信