Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Learn Python the Hard Way Example 5

In the Example 5 of Learn Python the Hard Way I ran into a problem. I went ahead and converted the inches to centimeters and the pounds to kilograms. I ran into an error though with the formatter and the syntax error read not all arguments converted during string formatting. My inches to cm and pounds to kg is fine but it didn't show the variable in the string. It looked like this:

print "%s is", cm, "tall in centimeters." % name

I was having a hard time posting the variables because it wants to be posted a certain way. The variables aren't the issue I'm confused why my variable didn't print using the formatter. I even tried it with %r instead of %s but it still wouldn't print the name variable. Can someone tell me what I did wrong?

like image 558
pynoob00 Avatar asked Aug 28 '26 12:08

pynoob00


2 Answers

use format:

print "{0} is {1} tall in centimeters.".format(name, cm)
like image 58
midori Avatar answered Aug 31 '26 03:08

midori


Your string formatting is acting on this :

"tall in centimeters." % name

As %s is not found in the above string, the interpreter fails.

A way to do what you want :

print "%s is %s tall in centimeters." % (name, cm)

Or

print "%s is %.2f tall in centimeters." % (name, cm)

if you'd like to show cm on 2 digits.

like image 36
Loïc Avatar answered Aug 31 '26 05:08

Loïc