String Formatting with %, Part 1


#1

name = raw_input ("what is your name? ")
age = raw_input ("how old are you? ")

print “so your name is %s and you are %s years old” % (name,age)


this is going to work in codecademy
but if i put it in anaconda jupyter notebook it gives me this messege


File “”, line 4
print “so your name is %s and you are %s years old” % (name,age)
^
SyntaxError: invalid syntax


so what is the problem ? is it because of the different versions ?


#2

yes, but i am surprised it throws that error message. In pyhton3, raw_input also no long exist


#3

so in codecadmy i am working in what version ?
and what do i have to put if i want the same program


#4
import sys
print sys.version

ther are always ways to find out. The more you find out on your own, the better. Well, you could google the differences between the two versions, and discover that print is a function call in pytho3, an no longer a statement like it was in python2


#5

thanks anyway …


#6

I hope i pushed you in the right direction, let me know if you need more help

its weird, the less i help, the better that actually is (the more you learn yourself)


#7

yes now i know how to write
i am going to write it like this

name = input("what is your name ? )
print ("nice to meet you Mr ",name)

the problem here is i didnt know how about if i want to put a question about the age

i tried to make it like this

name = input("what is your name ? ")
age = input("how old are you ? ")
print ("nice to meet you Mr ",name) +("you are “,age"old”)
but it didnt work


#8

but + joins the string, so the final result is a single string, so you only need one set of parentheses for print


#9

so how do you think i can join

name = input("what is your name ? ")
age = input("how old are you ? ")

to the print , can you give me a hint


#10

well, this is pretty good:

print ("nice to meet you Mr ",name) +("you are “,age"old”)

but you can just join the string and variables into a string with + or , whichever you prefer. But its still a single print function call, so only one set of parentheses is needed


#11

this is the problem with codecadmy

now i am here

from datetime import datetime
now = datetime.now()

print ‘%s/%s/%s %s:%s:%s’ % (now.year, now.month, now.day, now.hour, now.minute, now.second)

i know this is pretty good on the older version but i cant do anything with it in the new version unless i put a code that tells Python 3 you have to read it the old way


#12

you could simply upgrade print to a function call? Have you found out how you write print() in python3? All you need is one additional set of parentheses.


#13

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.