将1添加到整数值会产生TypeError

时间:2014-07-25 06:13:36

标签: python python-3.x

我知道这可能是一个非常简单的答案,但我对基本的编程问题有一些问题。

我试图为python编程以在这种情况下添加特定变量" age" + 1.它似乎没有工作

import cgi
form = cgi.FieldStorage()
text1 = form.getvalue("name")
text2 = int(form.getvalue("age"))
# print HTTP/HTML headers
print ("""Content-type: text/html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html><head>
<title>A CGI Script</title>
</head><body>
""")
print ("<p>Hello," +name+ ".</p>")
print ("<p>Next year you will be"  + str(age)+ 1 "years old</p>")
print ("</body></html>")

4 个答案:

答案 0 :(得分:1)

你正在混合&#34; +&#34;作为字符串连接和变量递增。

应为str(age + 1)

age = 26
print ("This year I am " + str(age) + " years old.")
print ("Next year I will be " + str(age + 1) + " years old.")

http://www.compileonline.com/execute_python3_online.php

进行测试

答案 1 :(得分:1)

你在示例

中对str进行了+1
print "Next year you will be  %s years old" % (int(age)+1)

答案 2 :(得分:1)

我认为应该是

print ("Next year you will be " + str(age+1) + " years old.")

答案 3 :(得分:0)

您的代码还有其他问题; Content-Type标题后缺少空行;代码可以使用str.format,并且变量命名不正确。因此:

import cgi

form = cgi.FieldStorage()

name = form.getvalue("name")
age = int(form.getvalue("age"))
age_next_year = age + 1

content = """Content-type: text/html

<!DOCTYPE html>
<html>
<head><title>A CGI Script</title></head>
<body>
<p>Hello, {name}</p>
<p>Next year, you will be {age} years old</p>
</body>
</html>"""

formatted = content.format(name=name, age=age_next_year)
print(formatted)