Python 2.7 – Fundamentals – Basic Input & Output

The input() function

Python has numerous GUI libraries which can create complex user interfaces, but within the core language it has a single input() function which takes input from the keyboard. Whatever is typed is stored in a variable. Whatever is entered is interpreted literally. So in other words, if you enter a string without surrounding quotes it will throw an error. Some examples are given below:

 

 

 

 

 

 

print function without formatting

As you already know the print function is the main way of showing output. It can be used to show multiple values at a time, either separated by commas or by using concatenation:

 

 

 

 

But the print statement has more powerful formatting parameters which can be used to show more complex output .

print function with formatting

The format operator is used within the print function. The left part of the % operator contains the output string template and the right part contains the values which will be put into the template.

The following character format operators are used:

  • d, i – integer
  • u – unsigned integer
  • f – floating point number as m.ddddd
  • e – floating point number in exponential format
  • g –  Use %e for exponents less than −4 or greater than +5, otherwise use %f
  • c – single character
  • s – any string data
  • % – insert the % as a literal

 

 

 

 

 

 

 

 

 

 

 

 

 

Formatting operators can also have modifiers. They are put between the % and the modifier character. They can be used individually or together. Modifiers add further formatting control to the basic formatting operators:

  • number –  set field width to the number of characters specified by the number
  •  – – left justify the value
  • + – right justify the value
  • 0 – fill in leading space with zeros
  • . – specify number of decimal places
  • (name)  – get value of key with name from supplied dictionary

 

 

 

 

 

 

 

 

In the next post we will look at Control Structures.

1 Trackback / Pingback

  1. Python 2.7 – Fundamentals – Collections – Dictionaries – Truelogic Blog

Leave a Reply

Your email address will not be published.


*