Basic input and output

From Training Material
Revision as of 19:20, 6 February 2013 by Bernard Szlachta (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search


Reading from the text console

User input can be read from the keyboard with or without a message text. The value returned is always a string:

a = raw_input()
a = raw_input('Please enter a number')

Writing to the text console

The Python print statement is very versatile and accepts almost any combination of strings, numbers, function calls, and arithmetic operations separated by commas.

print 'Hello World'
print 3 + 4
print 3.4
print ”””Text that stretches over
multiple lines.”””
print 'number', 77
print
print int(a) * 7

String formatting

Variables and strings can be combined, using formatting characters. This works also within a print statement. In both cases, the number of values and formatting characters must be equal.

s = 'Result: %i'%(number)
print 'Hello %s!'%('Roger')
print '(%6.3f/%6.3f)'%(a,b)

The formatting characters include:

  • %i – an integer.
  • %4i – an integer formatted to length 4.
  • %6.2f – a float number with length 6 and 2 after the comma.
  • %10s – a right-oriented string with length 10.

Escape characters

Strings may contain also the symbols: \t (tabulator), \n (newline), \r (carriage return), and \\ (backslash).