Andrew Pampuch
Andrew Pampuch

Reputation: 65

When using sys.stdout.write, "None" appears after what I write

My code looks like this:

import sys
print "What are his odds of hitting?", ( 25.0 / 10.0 ) * 8 + 65, sys.stdout.write('%')

When I run it in Powershell (Windows 7), I get this:

What are his odds of hitting? 85.0%None

What I want to get is this:

What are his odds of hitting? 85.0%

Why do I get the "None" at the end of it? How do I stop this from happening?

Upvotes: 0

Views: 1070

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1121196

You are printing the return value of the sys.stdout.write() call:

print "What are his odds of hitting?", ( 25.0 / 10.0 ) * 8 + 65, sys.stdout.write('%')

That function returns None. The function also writes to the same file descriptor as print does, so you are first writing % to stdout, then ask print to write more text to stdout including the return value None.

You probably just wanted to add % at the end there without a space. Use string concatenation or formatting:

print "What are his odds of hitting?", str(( 25.0 / 10.0 ) * 8 + 65) + '%'

or

print "What are his odds of hitting? %.02f%%" % (( 25.0 / 10.0 ) * 8 + 65)

or

print "What are his odds of hitting? {:.02f}%".format((25.0 / 10.0 ) * 8 + 65)

The two string formatting variations format the floating point value with two decimals after the decimal point. See String formatting operations (for the '..' % ... variant, old style string formatting), or Format String Syntax (for the str.format() method, a newer addition to the language)

Upvotes: 3

TerryA
TerryA

Reputation: 59974

sys.stdout.write('%') returns None. It simply prints the message and does not return anything.

Just put "%" at the end instead of calling sys.stdout.write

Or, you can use .format() here:

print "What are his odds of hitting? {}%".format(( 25.0 / 10.0 ) * 8 + 65)

Upvotes: 1

Related Questions