Python - 3. Input and Output

from:http://interactivepython.org/courselib/static/pythonds/Introduction/InputandOutput.html

  • Input

Python’s input function takes a single parameter that is a string. This string is often called the prompt because it contains some helpful text prompting the user to enter something. For example, you might call input as follows:

aName = input('Please enter your name: ')

aName = input("Please enter your name ")

print("Your name in all capitals is",aName.upper(),

"and has length", len(aName))

It is important to note that the value returned from the input function will be a string representing the exact characters that were entered after the prompt. If you want this string interpreted as another type, you must provide the type conversion explicitly.

sradius = input("Please enter the radius of the circle ")
radius = float(sradius)
diameter = 2 * radius
  • Output (String Formatting)

>>> print("Hello")
Hello
>>> print("Hello","World")
Hello World
>>> print("Hello","World", sep="***")
Hello***World
>>> print("Hello","World", end="***")
Hello World***
>>>print(aName, "is", age, "years old.")
>>>print("%s is %d years old." % (aName, age))
The % operator is a string operator called the format operator.
CharacterOutput Format
d, iInteger
uUnsigned integer
fFloating point as m.ddddd
eFloating point as m.ddddde+/-xx
EFloating point as m.dddddE+/-xx
gUse %e for exponents less than %f
cSingle character
sString, or any Python data object that can be converted to a string by using the str function.
%Insert a literal % character
In addition to the format character, you can also include a format modifier between the % and the format character. Format modifiers may be used to left-justify or right-justifiy the value with a specified field width. 
ModifierExampleDescription
number%20dPut the value in a field width of 20
-%-20dPut the value in a field 20 characters wide, left-justified
+%+20dPut the value in a field 20 characters wide, right-justified
0%020dPut the value in a field 20 characters wide, fill in with leading zeros.
.%20.2fPut the value in a field 20 characters wide with 2 characters to the right of the decimal point.
(name)%(name)dGet the value from the supplied dictionary using name as the key.
>>> price = 24
>>> item = "banana"
>>> print("The %s costs %d cents"%(item,price))
The banana costs 24 cents
>>> print("The %+10s costs %5.2f cents"%(item,price))
The     banana costs 24.00 cents
>>> print("The %+10s costs %10.2f cents"%(item,price))
The     banana costs      24.00 cents
>>> itemdict = {"item":"banana","cost":24}
>>> print("The %(item)s costs %(cost)7.1f cents"%itemdict)
The banana costs    24.0 cents
>>>
In addition to format strings that use format characters and format modifiers, Python strings also include a format method that can be used in conjunction with a new Formatter class to implement complex string formatting. More about these features can be found in the Python library reference manual.