0
year = raw_input("What year were you born?: ")

def age_calc(f):
    print "To calculate your age, I will subtract the current year from your birthyear!"
    return 2011 - "%d" % (f)

age = age_calc(year)

print age

这是我写的代码练习,这是我无法解决的错误......

File "agecalc.py", line 7, in <module>
  age = age_calc(year)
File "agecalc.py", line 5, in age_calc
  return 2011 - "%d" % (f)
TypeError: int argument required
4

2 回答 2

4

问题是您在计算中混淆了字符串和数字。在原始代码中

return 2011 - "%d" % (f)
         ^      ^
         |      |
     integer   string

从整数中减去一个字符串 - 这会导致错误消息:TypeError: int argument required

这是一个改进的版本:

def age_calc(yr):
    print "To calculate your age, I will subtract the current year from your birthyear!"
    return 2011 - yr

year = int(raw_input("What year were you born?: ")) # convert string to int
age = age_calc(year)

print age

请注意,我将用户输入从字符串转换为int提示输入的位置,然后使用数字而不是字符串和数字进行所有计算。

在原始代码中,您传递一个字符串age_calc(),然后使用它从数字 2011 中减去。现在您发送一个整数,age_calc()从另一个整数(2011)中减去一个整数没有问题。

我还为您的函数参数使用了一个更具描述性的标识符,yr而不是f.

于 2012-07-03T15:53:00.903 回答
1

%df成为一个整数,而在你的情况下它是一个字符串。

`return 2011 - "%d" % (f)` 

同样在2011 - "%d" % (f)你试图从一个数字中减去一个字符串,这也是错误的。

您的代码的工作版本:

year = int(raw_input("What year were you born?: ")) #convert to int using int()

def age_calc(f):
    print "To calculate your age, I will subtract the current year from your birthyear!"
    return 2011 - f # or return "{0}".format(2011-f)  if you want to return a string 

age = age_calc(year)

print age
于 2012-07-03T15:52:56.310 回答