Input & Output

Simple Input#

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

String Formatting#

Print Function#

  • The print function is able to take 0 or more parameters.
  • We can separate various parameters with a comma.
  • We can also provide sep argument to specify the separator we want between the parameters.
  • By default, print ends with a newline. Otherwise, we can specify end argument.


>>> print("Hello")
>>> print("Hello","World")
Hello World
>>> print("Hello","World", sep="***")
>>> print("Hello","World", end="***")
Hello World***>>>

We can print a statement the following two ways:

  • print(aName, "is", age, "years old.")
  • print("%s is %d years old." % (aName, age))

The second method uses the format operator.

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 โˆ’4โˆ’4 or greater than +5+5, otherwise use %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

We can also put a number in-between '%' and the format operator which is the format modifier.

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.

Using Format Function#

"{} can be {}".format("Strings", "interpolated") # => "Strings can be interpolated"

Using Keywords#

"{name} wants to eat {food}".format(name="Bob", food="lasagna")

Repeating Formatting Arguments#

# You can repeat the formatting arguments to save some typing.
"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick")