Reputation: 27
I know this is probably a super simple answer but I'm having some issues with a basic programming question.
I'm trying to program for python to add a specific variable in this case "age" + 1. It doesn't seem to be working
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>")
Upvotes: 2
Views: 621
Reputation: 134008
There are other problems with your code; there is a empty line missing after the Content-Type
header; the code could use str.format
, and variables were incorrectly named. Thus:
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)
Upvotes: 0
Reputation: 327
I think it should be
print ("Next year you will be " + str(age+1) + " years old.")
Upvotes: 1
Reputation: 1668
You're mixing "+" as string concatenation and variable incrementation.
It should be 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.")
Tested at http://www.compileonline.com/execute_python3_online.php
Upvotes: 1
Reputation: 862
You are doing a +1 on the str in the example
print "Next year you will be %s years old" % (int(age)+1)
Upvotes: 1