Reputation: 11
I am writing a piece of code which asks for the users first name then second name and then their age but then i print it out but I'm not sure how to please give an answer.
print ("What is your first name?"),
firstName = input()
print ("What is you last name?"),
secondName = input()
print ("How old are you?")
age = input()
print ("So, you're %r %r and you're %r years old."), firstName, secondName, age
Upvotes: 0
Views: 410
Reputation: 328
There are two ways to format the output string:
Old way
print("So, you're %s %s and you're %d years old." % (firstName, secondName, age)
New way (Preferred way)
print("So, you're {} {} and you're {} years old.".format(firstName, secondName, age))
The new way is much more flexible and provides neat little conveniences like giving placeholders an index. You can find all the differences and advantages here : PyFormat
Upvotes: 0
Reputation: 111
This is the fixed code:
firstName = input("What is your first name?")
secondName = input("What is you last name?")
age = input("How old are you?")
print ("So, you're " + firstName + " " + secondName + " and you're " + age + " years old.")
It is pretty easy to understand, since this just uses concatenation.
Upvotes: 0
Reputation: 4409
You want to use string.format.
You use it like so:
print ("So, you're {} {} and you're {} years old.".format(firstName, secondName, age))
Or in Python 3.6 upwards, you can use the following shorthand:
print (f"So, you're {firstName} {secondName} and you're {age} years old.")
Upvotes: 6
Reputation: 789
New style string formatting in Python:
print("So, you're {} {} and you're {} years old.".format(firstName, secondName, age))
Upvotes: 0
Reputation: 59426
Use
print ("So, you're %r %r and you're %r years old." % (
firstName, secondName, age))
You might want to consider using %s
for the strings and %d
for the number, though ;-)
Upvotes: 0